commit 791b9984891347070de7d9fbb517e96f763c0e42 Author: Fmstrat Date: Fri Mar 22 10:17:29 2019 -0400 Automated build for v0.01 diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..119b50a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,6 @@ +[*] +end_of_line = lf +insert_final_newline = true + +[*.php] +indent_style = tab diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4c5a9c8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +Thumbs.db +/deploy.exclude +/deploy.sh +/messages.mo +*~ +*.DS_Store +#* +.idea/* +data/* +tags +cache/htmlpurifier/*/*ser +lib/htmlpurifier/library/HTMLPurifier/DefinitionCache/Serializer/*/*ser +web.config +/.save.cson +/.tags* +/.gutentags diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..cd5ecb0 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,44 @@ +phpmd: + image: php:5.6 + when: manual + script: + - sh utils/gitlab-ci/php-lint.sh + - curl -o /usr/bin/phpmd -L http://static.phpmd.org/php/2.6.0/phpmd.phar + - chmod +x /usr/bin/phpmd + - sh utils/gitlab-ci/phpmd.sh + +schema: + image: fox/selenium-ci + when: manual + script: + - /etc/init.d/postgresql start + - /usr/local/sbin/init-database.sh + - sh ./utils/gitlab-ci/check-schema.sh + +phpunit_basic: + image: fox/selenium-ci + when: manual + script: + - /etc/init.d/postgresql start + - /usr/local/sbin/init-database.sh + - sh ./utils/gitlab-ci/check-schema.sh + - cp utils/gitlab-ci/config-template.php config.php + - su -s /bin/bash www-data -c "php ./update.php --debug-feed 1" + - wget -O /usr/bin/phpunit https://phar.phpunit.de/phpunit-5.7.phar + - chmod +x /usr/bin/phpunit + - phpunit tests/*.php + +phpunit_functional: + image: fox/selenium-ci + when: manual + script: + - /etc/init.d/postgresql start + - /etc/init.d/nginx start + - /etc/init.d/php5-fpm start + - /usr/local/sbin/init-database.sh + - sh ./utils/gitlab-ci/check-schema.sh + - ln -s `pwd` ../../tt-rss + - cp utils/gitlab-ci/config-template.php config.php + - chmod -R 777 cache lock feed-icons + - /usr/local/sbin/init-selenium.sh + - phpunit tests/functional/*.php diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..89cf5a9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,12 @@ + +Contributing +============ +There are two ways to contribute to Agriget. One is to contribute directly to the upstream TT-RSS project, and the other is to contribute here, to Agriget directly. + +When to contribute to TT-RSS +---------------------------- +For back end functional updates and bug fixes, it is best to contribute to TT-RSS directly. This way, all users benefit from the code you are creating. + +When to contribute to Agriget +----------------------------- +While TT-RSS is a strong and stable project built over the course of many years, it has been well documented that the author is not interested in accepting contributions that go outside of what is possible with the standard plug-in structure, regardless of if those features are optional for the users. This is the author's decision to ensure a long-term and stable product for his users and is of course an acceptable path for TT-RSS. Agriget was created to allow for an evolution of the UI and other areas of TT-RSS, and therefore exists as an open environment for users to contribute in these ways. diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..94a9ed0 --- /dev/null +++ b/COPYING @@ -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/PLUGINHOOKS.md b/PLUGINHOOKS.md new file mode 100644 index 0000000..062ae88 --- /dev/null +++ b/PLUGINHOOKS.md @@ -0,0 +1,117 @@ + +Hook Documentation +============ +In progress documentation on hooks for plugins. + +This documentation may not be up to date. Please see https://github.com/Fmstrat/agriget/blob/master/classes/pluginhost.php#L21 for the latest list of hooks. + +Feed Fetch Hooks +--------------- +These hooks run in the background when feed data is fetched. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_FEED_BASIC_INFO` | Used to replace basic feed information prior to fetching from the provider. | `$basic_info` - Blank array that is also returned
`$fetch_url` - URL of feed
`$owner_uid` - The user who owns the feed
`$feed` - Feed object
`$auth_login` - Auth user if requred
`$auth_pass` - Auth password if requred | `$basic_info` | +| `HOOK_FETCH_FEED` | Used to update feed data right before it is fetched from the provider URL. | `$feed_data` - Blank feed data that is also returned
`$fetch_url` - URL of feed
`$owner_uid` - The user who owns the feed
`$feed` - Feed object
`0` - Unknown
`$auth_login` - Auth user if requred
`$auth_pass` - Auth password if requred | `$feed_data` | +| `HOOK_FEED_FETCHED` | Used to update feed data right after it is fetched from the provider URL. | `$feed_data` - Populated feed data that is also returned
`$fetch_url` - URL of feed
`$owner_uid` - The user who owns the feed
`$feed` - Feed object | `$feed_data` | +| `HOOK_FEED_PARSED` | Unknown. Runs after the Feed Parser inits. | `$rss` - Feed parser object | None | +| `HOOK_ARTICLE_FILTER` | Used to update inidividual articles after the feed is fetched and parsed. | `$article` - Object containing an article | `$article` | +| `HOOK_FILTER_TRIGGERED` | Used to change the filters that match an article. | `$feed` - Feed object
`$owner_uid` - The user who owns the feed
`$article` - Object containing an article
`$matched_filters` - Array of matched filters
`$matched_rules` - Array of matched rules
`$article_filters` - All filters | None | +| `HOOK_ARTICLE_FILTER_ACTION` | Used to update an article as filter actions are applied. | `$article` - Object containing an article
`$pfaction` - The filter action
`$matched_rules` - Array of matched rules
`$article_filters` - All filters | `$article` | +| `HOOK_HOUSE_KEEPING` | Used to run code at the end of processing. | No inputs | None | + + +Page Load Hooks +--------------- +These hooks run when the page loads. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_MAIN_TOOLBAR_BUTTON` | Used to add HTML/buttons to the main toolbar area at the top left. | No inputs | HTML string | +| `HOOK_TOOLBAR_BUTTON` | Used to add HTML/dropdowns to the main toolbar area at the top right. | No inputs | HTML string | +| `HOOK_ACTION_ITEM` | Used to add options to the upper right action drop-down menu. | No inputs | HTML string | + + +Grabbing Hooks +--------------- +These hooks run when an article is grabbed, reguardless of client (mobile/HTML/etc). + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_RENDER_ARTICLE_API` | Used to alter the article object (and headline object) as it is returned to the client. Format of object can be found here: https://gitlab.com/gothfox/tt-rss/blob/master/classes/api.php#L349 | `array("article" => $article)` - The article object as a single element array | `$article` | +| `HOOK_QUERY_HEADLINES` | Used to alter the headlines as they are queried. | `$line` - The headline object
`$excerpt_length` - The length of content to display
`true` - Unknown | `$line` | + + +Feed Display Hooks +--------------- +These hooks run when the page loads a feed. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_HEADLINE_TOOLBAR_BUTTON` | Used to add options to the upper-right menu titled Select. | `$feed_id` - The feed id of the current feed displayed
`$is_cat` - The category of that feed | HTML code | +| `HOOK_HEADLINES_BEFORE` | Used to add HTML code before the headlines are displayed. | `$feed` - The feed object
`$cat_view` - The category view
`$qfh_ret` - Unknown | HTML code | +| `HOOK_QUERY_HEADLINES` | Used to alter listing previews as they are added to the display. | `$line` - The object containing that headline's content preview.
`250` - Unknown (Character length?)
`false` - Unknown | `$line` | +| `HOOK_ARTICLE_EXPORT_FEED` | Runs after HOOK_QUERY_HEADLINES but only for public feeds. | `$line` - Array of lines of HTML code)
`$feed` - Object with feed info and the array of articles (populates each article after this runs)
`$is_cat` - Category | `$line` | + + +Article Display Hooks +--------------- +These hooks run when the page loads an article. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_ARTICLE_LEFT_BUTTON` | Used to add buttons to the left of each individual article as it is displayed. | `$line` - Object of article data. | `$line["buttons_left"]` | +| `HOOK_ARTICLE_BUTTON` | Used to add buttons to the top of each individual article as it is displayed. | `$line` - Object of article data. | `$line["buttons"]` | +| `HOOK_RENDER_ARTICLE_CDM` | Used to alter article content or anything else in the displayed article. | `$line` - Object of article data. | `$line` | +| `HOOK_RENDER_ARTICLE` | Used to alter article content or anything else in the displayed article before everything has been placed into html. Note: This only runs on public feeds. | `$line` - Object of article data. | `$line` | +| `HOOK_FORMAT_ARTICLE` | Used to alter article content or anything else in the displayed article after everything has been placed into html (including buttons). Note: This only runs on public feeds. | `$rv` - The HTML to be returned for each article
`$line` - Object of article data.
`true` - Unknown | `$rv` | + + +Embedded Media Hooks +--------------- +Used to alter embedded media containers. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_FORMAT_ENCLOSURES` | Used to add content and replace default enclosures for media (url, content types, width, title, etc). | `$rv` - The HTML code for the enclosure
`$result` - Lines of entries
`$id` - Unknown
`$always_display_enclosures` - Unknown
`$article_content` - Content of the article
`$hide_images` - Whether images are displayed | `$retval ([0] = $rv, [1] = $result)` | +| `HOOK_ENCLOSURE_ENTRY` | Used to alter each media item. | `$line` - The information on that item (url, width, title, etc) | `$line` | +| `HOOK_RENDER_ENCLOSURE` | Used to alter HTML as the media item is displayed. | `$entry` - The media item
`$hide_images` - If hide images is on or off | HTML code placed in the IMG tag | + + +Interaction Hooks +--------------- +Runs when an action is executed int the client. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_SUBSCRIBE_FEED` | Used to alto feed content as a feed is subscribed to, right after the data is pulled. | `$contents` - Contents of the feed after first pull
`$url` - URL of the feed
`$auth_login` - Auth user if requred
`$auth_pass` - Auth password if requred | `$content` | +| `HOOK_UNSUBSCRIBE_FEED` | Used to run code when a feed is unsubscribed. | `$id` - The feed id
`$owner_uid` - The owner of the feed | Boolean for success | +| `HOOK_SEARCH` | Used to alter search results. | `$search` - The search object | The search list | +| `HOOK_AUTH_USER` | Used to add authentication methods. | `$login` - Username
`$password` - Password | `$user_id` | + + +Settings Hooks +--------------- +These hooks alter settings and preferences. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_HOTKEY_INFO` | Used to alter the information returned about hotkeys. | `$hotkeys` - Object of hotkey info | `$hotkeys` | +| `HOOK_HOTKEY_MAP` | Used to add/alter hotkeys. | `$hotkeys` - Array of hotkeys | `$hotkeys` | +| `HOOK_PREFS_EDIT_FEED` | Used to alter a feed when the settings screen for a feed is displayed. | `$feed_id` - The feed's id | None | +| `HOOK_PREFS_SAVE_FEED` | Used to execute commands when a feed is saved (before commit). | `$feed_id` - The feed's id | None | +| `HOOK_PREFS_TAB_SECTION` | Used to run code when preferences tabs are loaded. | No inputs | None | +| `HOOK_PREFS_TAB` | Used to run code inside a preference tab. | No inputs | None | +| `HOOK_PREFS_TABS` | Used to add HTML tabs to the top of preferences. | No inputs | None | + + +Misc Hooks +--------------- +Other hooks. + +| Hook | Description | Inputs | Return | +| ---- | ----------- | ------ | ------ | +| `HOOK_SANITIZE` | Runs whenever content is sanitized. | `$doc` - Unknown
`$site_url` - Unknown
`$allowed_elements` - HTML ellements allowed in fields
`$disallowed_attributes` - HTML elements not allowed in fields
`$article_id` - The current article id | `$retval ([0] = $doc, [1] = $allowed_elements, [2] = $disallowed_attributes)` | +| `HOOK_SEND_LOCAL_FILE` | Runs when a local file is sent to a client (such as proxied media). | `$filename` - The file being sent | Boolean for success (not used) | +| `HOOK_SEND_MAIL` | Used to execute an action when email is sent. | `$this` - The current object
`$params` - See https://gitlab.com/gothfox/tt-rss/blob/master/classes/mailer.php#L9 | `$rc` (See https://gitlab.com/gothfox/tt-rss/blob/master/classes/mailer.php#L24) | +| `HOOK_UPDATE_TASK` | Unknown | No inputs | None | diff --git a/README.md b/README.md new file mode 100644 index 0000000..d86458c --- /dev/null +++ b/README.md @@ -0,0 +1,89 @@ +Agriget +======= + +Agriget is a fork of Tiny Tiny RSS (TT-RSS) that focuses on a more modern "Feedly styled" UI while retaining all compatibility and updates with and from the TT-RSS backend and mobile applications. While the original features of Agriget were started as a PR to TT-RSS, due to development differences Agriget was instead created to foster an open environment for developers to contribute. + +
+ + + +
+ + + +
+
+ +**Core differences from TT-RSS include:** +- UI enhancements to include visuals and make view changes and night mode more seamless +- Greater 12h time support in UI +- Consolidated data directory for easier deployment in container infrastructures such as Docker + +**Todo:** +- Refactor full UI including settings screens in CSS Grid +- Remove requirement for popout top menu +- Cross platform mobile implementation leveraging new UI + +Install +------- +The easiest installation method is to use the prebuilt Docker image located at: https://hub.docker.com/r/nowsci/agriget. The below will set up the containers required for Agriget. You should seperatly set up an nginx instance proxying to `agriget:80`, or you could open ports to the host. + +In your `docker-compose.yml`: +``` +version: '2.1' + +services: + + agriget-mariadb: + image: mariadb + container_name: agriget-mariadb + environment: + - MYSQL_ROOT_PASSWORD=agriget + - MYSQL_PASSWORD=agriget + - MYSQL_DATABASE=agriget + - MYSQL_USER=agriget + volumes: + - /etc/localtime:/etc/localtime:ro + - ./agriget/mariadb/data/:/var/lib/mysql + restart: always + + agriget: + image: nowsci/agriget + container_name: agriget + volumes: + - /etc/localtime:/etc/localtime:ro + - ./agriget/apache/data:/data + depends_on: + - agriget-mariadb + restart: always +``` + +**If you do not wish to use Docker**, you can follow the standard TT-RSS instructions from https://git.tt-rss.org/fox/tt-rss/wiki/InstallationNotes while substituting the https://github.com/Fmstrat/agriget repo for Tiny Tiny RSS. + +Migrating from TT-RSS +--------------------- +Migration from TT-RSS is a fairly straight forward process unless you are running some really custom plugins. +- Copy your `config.php` file to Agriget's `/data` directory. +- Make the following changes to `config.php`: + - Add `define('DATA_DIR', 'data');` + - Change `define('LOCK_DIRECTORY', 'lock');` to `define('LOCK_DIRECTORY', 'data/lock');` + - Change `define('CACHE_DIR', 'cache');` to `define('CACHE_DIR', 'data/cache');` + - Change `define('ICONS_DIR', "feed-icons");` to `define('ICONS_DIR', "data/feed-icons");` + - Change `define('ICONS_URL', "feed-icons");` to `define('ICONS_URL', "data/feed-icons");` + - Ensure `define('PLUGINS', ...)` includes `toggle_sidebar, bookmarklets, close_button` as these are required by Agriget + +Now Agriget will be pointed at your existing TT-RSS database and function as TT-RSS did before. Please be sure TT-RSS is not running before you start Agriget, and it is highly recommended you run a backup before beginning this process. + +Plugins +------- +Looking to develop TT-RSS style plugins? See the [Hook Documentation](https://github.com/Fmstrat/agriget/blob/master/PLUGINHOOKS.md) for information on which hooks are available. + +Disclaimer +---------- +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 . + +- Uses Silk icons by Mark James: http://www.famfamfam.com/lab/icons/silk/ +- Originally forked from TT-RSS: http://tt-rss.org +- Base Feedly theme from: https://github.com/levito/tt-rss-feedly-theme diff --git a/api/index.php b/api/index.php new file mode 100644 index 0000000..ed53f54 --- /dev/null +++ b/api/index.php @@ -0,0 +1,91 @@ + -1, + "status" => 1, + "content" => array("error" => "NOT_LOGGED_IN"))); + + return; + } + + load_user_plugins( $_SESSION["uid"]); + } + + $method = strtolower($_REQUEST["op"]); + + $handler = new API($_REQUEST); + + if ($handler->before($method)) { + if ($method && method_exists($handler, $method)) { + $handler->$method(); + } else if (method_exists($handler, 'index')) { + $handler->index($method); + } + $handler->after(); + } + + header("Api-Content-Length: " . ob_get_length()); + + ob_end_flush(); + diff --git a/atom-to-html.xsl b/atom-to-html.xsl new file mode 100644 index 0000000..f32d599 --- /dev/null +++ b/atom-to-html.xsl @@ -0,0 +1,51 @@ + + + + + + + + + <xsl:value-of select="atom:title"/> + + + + + + + + +
+ +

+ +

This feed has been exported from + Tiny Tiny RSS. + It contains the following items:

+ + +

+ +
+ +
+ + +

Extra...

+
+ + +
+ +
+ + + +
+ +
+ diff --git a/backend.php b/backend.php new file mode 100644 index 0000000..fd6f44b --- /dev/null +++ b/backend.php @@ -0,0 +1,147 @@ + __("Use default"), + -1 => __("Never purge"), + 5 => __("1 week old"), + 14 => __("2 weeks old"), + 31 => __("1 month old"), + 60 => __("2 months old"), + 90 => __("3 months old")); + + $update_intervals = array( + 0 => __("Default interval"), + -1 => __("Disable updates"), + 15 => __("15 minutes"), + 30 => __("30 minutes"), + 60 => __("Hourly"), + 240 => __("4 hours"), + 720 => __("12 hours"), + 1440 => __("Daily"), + 10080 => __("Weekly")); + + $update_intervals_nodefault = array( + -1 => __("Disable updates"), + 15 => __("15 minutes"), + 30 => __("30 minutes"), + 60 => __("Hourly"), + 240 => __("4 hours"), + 720 => __("12 hours"), + 1440 => __("Daily"), + 10080 => __("Weekly")); + + $access_level_names = array( + 0 => __("User"), + 5 => __("Power User"), + 10 => __("Administrator")); + + $op = str_replace("-", "_", $op); + + $override = PluginHost::getInstance()->lookup_handler($op, $method); + + if (class_exists($op) || $override) { + + if ($override) { + $handler = $override; + } else { + $handler = new $op($_REQUEST); + } + + if ($handler && implements_interface($handler, 'IHandler')) { + if (validate_csrf($csrf_token) || $handler->csrf_ignore($method)) { + if ($handler->before($method)) { + if ($method && method_exists($handler, $method)) { + $handler->$method(); + } else { + if (method_exists($handler, "catchall")) { + $handler->catchall($method); + } + } + $handler->after(); + return; + } else { + header("Content-Type: text/json"); + print error_json(6); + return; + } + } else { + header("Content-Type: text/json"); + print error_json(6); + return; + } + } + } + + header("Content-Type: text/json"); + print error_json(13); + +?> diff --git a/cache/export/.empty b/cache/export/.empty new file mode 100755 index 0000000..e69de29 diff --git a/cache/feeds/.empty b/cache/feeds/.empty new file mode 100644 index 0000000..e69de29 diff --git a/cache/images/.empty b/cache/images/.empty new file mode 100755 index 0000000..e69de29 diff --git a/cache/upload/.empty b/cache/upload/.empty new file mode 100644 index 0000000..e69de29 diff --git a/classes/api.php b/classes/api.php new file mode 100755 index 0000000..e505dcc --- /dev/null +++ b/classes/api.php @@ -0,0 +1,888 @@ +wrap(self::STATUS_ERR, array("error" => 'NOT_LOGGED_IN')); + return false; + } + + if ($_SESSION["uid"] && $method != "logout" && !get_pref('ENABLE_API_ACCESS')) { + $this->wrap(self::STATUS_ERR, array("error" => 'API_DISABLED')); + return false; + } + + $this->seq = (int) clean($_REQUEST['seq']); + + return true; + } + return false; + } + + function wrap($status, $reply) { + print json_encode(array("seq" => $this->seq, + "status" => $status, + "content" => $reply)); + } + + function getVersion() { + $rv = array("version" => VERSION); + $this->wrap(self::STATUS_OK, $rv); + } + + function getApiLevel() { + $rv = array("level" => self::API_LEVEL); + $this->wrap(self::STATUS_OK, $rv); + } + + function login() { + @session_destroy(); + @session_start(); + + $login = clean($_REQUEST["user"]); + $password = clean($_REQUEST["password"]); + $password_base64 = base64_decode(clean($_REQUEST["password"])); + + if (SINGLE_USER_MODE) $login = "admin"; + + $sth = $this->pdo->prepare("SELECT id FROM ttrss_users WHERE login = ?"); + $sth->execute([$login]); + + if ($row = $sth->fetch()) { + $uid = $row["id"]; + } else { + $uid = 0; + } + + if (!$uid) { + $this->wrap(self::STATUS_ERR, array("error" => "LOGIN_ERROR")); + return; + } + + if (get_pref("ENABLE_API_ACCESS", $uid)) { + if (authenticate_user($login, $password)) { // try login with normal password + $this->wrap(self::STATUS_OK, array("session_id" => session_id(), + "api_level" => self::API_LEVEL)); + } else if (authenticate_user($login, $password_base64)) { // else try with base64_decoded password + $this->wrap(self::STATUS_OK, array("session_id" => session_id(), + "api_level" => self::API_LEVEL)); + } else { // else we are not logged in + user_error("Failed login attempt for $login from {$_SERVER['REMOTE_ADDR']}", E_USER_WARNING); + $this->wrap(self::STATUS_ERR, array("error" => "LOGIN_ERROR")); + } + } else { + $this->wrap(self::STATUS_ERR, array("error" => "API_DISABLED")); + } + + } + + function logout() { + logout_user(); + $this->wrap(self::STATUS_OK, array("status" => "OK")); + } + + function isLoggedIn() { + $this->wrap(self::STATUS_OK, array("status" => $_SESSION["uid"] != '')); + } + + function getUnread() { + $feed_id = clean($_REQUEST["feed_id"]); + $is_cat = clean($_REQUEST["is_cat"]); + + if ($feed_id) { + $this->wrap(self::STATUS_OK, array("unread" => getFeedUnread($feed_id, $is_cat))); + } else { + $this->wrap(self::STATUS_OK, array("unread" => Feeds::getGlobalUnread())); + } + } + + /* Method added for ttrss-reader for Android */ + function getCounters() { + $this->wrap(self::STATUS_OK, Counters::getAllCounters()); + } + + function getFeeds() { + $cat_id = clean($_REQUEST["cat_id"]); + $unread_only = API::param_to_bool(clean($_REQUEST["unread_only"])); + $limit = (int) clean($_REQUEST["limit"]); + $offset = (int) clean($_REQUEST["offset"]); + $include_nested = API::param_to_bool(clean($_REQUEST["include_nested"])); + + $feeds = $this->api_get_feeds($cat_id, $unread_only, $limit, $offset, $include_nested); + + $this->wrap(self::STATUS_OK, $feeds); + } + + function getCategories() { + $unread_only = API::param_to_bool(clean($_REQUEST["unread_only"])); + $enable_nested = API::param_to_bool(clean($_REQUEST["enable_nested"])); + $include_empty = API::param_to_bool(clean($_REQUEST['include_empty'])); + + // TODO do not return empty categories, return Uncategorized and standard virtual cats + + if ($enable_nested) + $nested_qpart = "parent_cat IS NULL"; + else + $nested_qpart = "true"; + + $sth = $this->pdo->prepare("SELECT + id, title, order_id, (SELECT COUNT(id) FROM + ttrss_feeds WHERE + ttrss_feed_categories.id IS NOT NULL AND cat_id = ttrss_feed_categories.id) AS num_feeds, + (SELECT COUNT(id) FROM + ttrss_feed_categories AS c2 WHERE + c2.parent_cat = ttrss_feed_categories.id) AS num_cats + FROM ttrss_feed_categories + WHERE $nested_qpart AND owner_uid = ?"); + $sth->execute([$_SESSION['uid']]); + + $cats = array(); + + while ($line = $sth->fetch()) { + if ($include_empty || $line["num_feeds"] > 0 || $line["num_cats"] > 0) { + $unread = getFeedUnread($line["id"], true); + + if ($enable_nested) + $unread += Feeds::getCategoryChildrenUnread($line["id"]); + + if ($unread || !$unread_only) { + array_push($cats, array("id" => $line["id"], + "title" => $line["title"], + "unread" => $unread, + "order_id" => (int) $line["order_id"], + )); + } + } + } + + foreach (array(-2,-1,0) as $cat_id) { + if ($include_empty || !$this->isCategoryEmpty($cat_id)) { + $unread = getFeedUnread($cat_id, true); + + if ($unread || !$unread_only) { + array_push($cats, array("id" => $cat_id, + "title" => Feeds::getCategoryTitle($cat_id), + "unread" => $unread)); + } + } + } + + $this->wrap(self::STATUS_OK, $cats); + } + + function getHeadlines() { + $feed_id = clean($_REQUEST["feed_id"]); + if ($feed_id !== "") { + + if (is_numeric($feed_id)) $feed_id = (int) $feed_id; + + $limit = (int)clean($_REQUEST["limit"]); + + if (!$limit || $limit >= 200) $limit = 200; + + $offset = (int)clean($_REQUEST["skip"]); + $filter = clean($_REQUEST["filter"]); + $is_cat = API::param_to_bool(clean($_REQUEST["is_cat"])); + $show_excerpt = API::param_to_bool(clean($_REQUEST["show_excerpt"])); + $show_content = API::param_to_bool(clean($_REQUEST["show_content"])); + /* all_articles, unread, adaptive, marked, updated */ + $view_mode = clean($_REQUEST["view_mode"]); + $include_attachments = API::param_to_bool(clean($_REQUEST["include_attachments"])); + $since_id = (int)clean($_REQUEST["since_id"]); + $include_nested = API::param_to_bool(clean($_REQUEST["include_nested"])); + $sanitize_content = !isset($_REQUEST["sanitize"]) || + API::param_to_bool($_REQUEST["sanitize"]); + $force_update = API::param_to_bool(clean($_REQUEST["force_update"])); + $has_sandbox = API::param_to_bool(clean($_REQUEST["has_sandbox"])); + $excerpt_length = (int)clean($_REQUEST["excerpt_length"]); + $check_first_id = (int)clean($_REQUEST["check_first_id"]); + $include_header = API::param_to_bool(clean($_REQUEST["include_header"])); + + $_SESSION['hasSandbox'] = $has_sandbox; + + $skip_first_id_check = false; + + $override_order = false; + switch (clean($_REQUEST["order_by"])) { + case "title": + $override_order = "ttrss_entries.title, date_entered, updated"; + break; + case "date_reverse": + $override_order = "score DESC, date_entered, updated"; + $skip_first_id_check = true; + break; + case "feed_dates": + $override_order = "updated DESC"; + break; + } + + /* do not rely on params below */ + + $search = clean($_REQUEST["search"]); + + list($headlines, $headlines_header) = $this->api_get_headlines($feed_id, $limit, $offset, + $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $override_order, + $include_attachments, $since_id, $search, + $include_nested, $sanitize_content, $force_update, $excerpt_length, $check_first_id, $skip_first_id_check); + + if ($include_header) { + $this->wrap(self::STATUS_OK, array($headlines_header, $headlines)); + } else { + $this->wrap(self::STATUS_OK, $headlines); + } + } else { + $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE')); + } + } + + function updateArticle() { + $article_ids = explode(",", clean($_REQUEST["article_ids"])); + $mode = (int) clean($_REQUEST["mode"]); + $data = clean($_REQUEST["data"]); + $field_raw = (int)clean($_REQUEST["field"]); + + $field = ""; + $set_to = ""; + + switch ($field_raw) { + case 0: + $field = "marked"; + $additional_fields = ",last_marked = NOW()"; + break; + case 1: + $field = "published"; + $additional_fields = ",last_published = NOW()"; + break; + case 2: + $field = "unread"; + $additional_fields = ",last_read = NOW()"; + break; + case 3: + $field = "note"; + }; + + switch ($mode) { + case 1: + $set_to = "true"; + break; + case 0: + $set_to = "false"; + break; + case 2: + $set_to = "NOT $field"; + break; + } + + if ($field == "note") $set_to = $this->pdo->quote($data); + + if ($field && $set_to && count($article_ids) > 0) { + + $article_qmarks = arr_qmarks($article_ids); + + $sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET + $field = $set_to $additional_fields + WHERE ref_id IN ($article_qmarks) AND owner_uid = ?"); + $sth->execute(array_merge($article_ids, [$_SESSION['uid']])); + + $num_updated = $sth->rowCount(); + + if ($num_updated > 0 && $field == "unread") { + $sth = $this->pdo->prepare("SELECT DISTINCT feed_id FROM ttrss_user_entries + WHERE ref_id IN ($article_qmarks)"); + $sth->execute($article_ids); + + while ($line = $sth->fetch()) { + CCache::update($line["feed_id"], $_SESSION["uid"]); + } + } + + $this->wrap(self::STATUS_OK, array("status" => "OK", + "updated" => $num_updated)); + + } else { + $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE')); + } + + } + + function getArticle() { + + $article_ids = explode(",", clean($_REQUEST["article_id"])); + $sanitize_content = !isset($_REQUEST["sanitize"]) || + API::param_to_bool($_REQUEST["sanitize"]); + + if ($article_ids) { + + $article_qmarks = arr_qmarks($article_ids); + + $sth = $this->pdo->prepare("SELECT id,guid,title,link,content,feed_id,comments,int_id, + marked,unread,published,score,note,lang, + ".SUBSTRING_FOR_DATE."(updated,1,16) as updated, + author,(SELECT title FROM ttrss_feeds WHERE id = feed_id) AS feed_title, + (SELECT site_url FROM ttrss_feeds WHERE id = feed_id) AS site_url, + (SELECT hide_images FROM ttrss_feeds WHERE id = feed_id) AS hide_images + FROM ttrss_entries,ttrss_user_entries + WHERE id IN ($article_qmarks) AND ref_id = id AND owner_uid = ?"); + + $sth->execute(array_merge($article_ids, [$_SESSION['uid']])); + + $articles = array(); + + while ($line = $sth->fetch()) { + + $attachments = Article::get_article_enclosures($line['id']); + + $article = array( + "id" => $line["id"], + "guid" => $line["guid"], + "title" => $line["title"], + "link" => $line["link"], + "labels" => Article::get_article_labels($line['id']), + "unread" => API::param_to_bool($line["unread"]), + "marked" => API::param_to_bool($line["marked"]), + "published" => API::param_to_bool($line["published"]), + "comments" => $line["comments"], + "author" => $line["author"], + "updated" => (int) strtotime($line["updated"]), + "feed_id" => $line["feed_id"], + "attachments" => $attachments, + "score" => (int)$line["score"], + "feed_title" => $line["feed_title"], + "note" => $line["note"], + "lang" => $line["lang"] + ); + + if ($sanitize_content) { + $article["content"] = sanitize( + $line["content"], + API::param_to_bool($line['hide_images']), + false, $line["site_url"], false, $line["id"]); + } else { + $article["content"] = $line["content"]; + } + + foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE_API) as $p) { + $article = $p->hook_render_article_api(array("article" => $article)); + } + + $article['content'] = rewrite_cached_urls($article['content']); + + array_push($articles, $article); + + } + + $this->wrap(self::STATUS_OK, $articles); + } else { + $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE')); + } + } + + function getConfig() { + $config = array( + "icons_dir" => ICONS_DIR, + "icons_url" => ICONS_URL); + + $config["daemon_is_running"] = file_is_locked("update_daemon.lock"); + + $sth = $this->pdo->prepare("SELECT COUNT(*) AS cf FROM + ttrss_feeds WHERE owner_uid = ?"); + $sth->execute([$_SESSION['uid']]); + $row = $sth->fetch(); + + $config["num_feeds"] = $row["cf"]; + + $this->wrap(self::STATUS_OK, $config); + } + + function updateFeed() { + $feed_id = (int) clean($_REQUEST["feed_id"]); + + if (!ini_get("open_basedir")) { + RSSUtils::update_rss_feed($feed_id); + } + + $this->wrap(self::STATUS_OK, array("status" => "OK")); + } + + function catchupFeed() { + $feed_id = clean($_REQUEST["feed_id"]); + $is_cat = clean($_REQUEST["is_cat"]); + + Feeds::catchup_feed($feed_id, $is_cat); + + $this->wrap(self::STATUS_OK, array("status" => "OK")); + } + + function getPref() { + $pref_name = clean($_REQUEST["pref_name"]); + + $this->wrap(self::STATUS_OK, array("value" => get_pref($pref_name))); + } + + function getLabels() { + $article_id = (int)clean($_REQUEST['article_id']); + + $rv = array(); + + $sth = $this->pdo->prepare("SELECT id, caption, fg_color, bg_color + FROM ttrss_labels2 + WHERE owner_uid = ? ORDER BY caption"); + $sth->execute([$_SESSION['uid']]); + + if ($article_id) + $article_labels = Article::get_article_labels($article_id); + else + $article_labels = array(); + + while ($line = $sth->fetch()) { + + $checked = false; + foreach ($article_labels as $al) { + if (Labels::feed_to_label_id($al[0]) == $line['id']) { + $checked = true; + break; + } + } + + array_push($rv, array( + "id" => (int)Labels::label_to_feed_id($line['id']), + "caption" => $line['caption'], + "fg_color" => $line['fg_color'], + "bg_color" => $line['bg_color'], + "checked" => $checked)); + } + + $this->wrap(self::STATUS_OK, $rv); + } + + function setArticleLabel() { + + $article_ids = explode(",", clean($_REQUEST["article_ids"])); + $label_id = (int) clean($_REQUEST['label_id']); + $assign = API::param_to_bool(clean($_REQUEST['assign'])); + + $label = Labels::find_caption(Labels::feed_to_label_id($label_id), $_SESSION["uid"]); + + $num_updated = 0; + + if ($label) { + + foreach ($article_ids as $id) { + + if ($assign) + Labels::add_article($id, $label, $_SESSION["uid"]); + else + Labels::remove_article($id, $label, $_SESSION["uid"]); + + ++$num_updated; + + } + } + + $this->wrap(self::STATUS_OK, array("status" => "OK", + "updated" => $num_updated)); + + } + + function index($method) { + $plugin = PluginHost::getInstance()->get_api_method(strtolower($method)); + + if ($plugin && method_exists($plugin, $method)) { + $reply = $plugin->$method(); + + $this->wrap($reply[0], $reply[1]); + + } else { + $this->wrap(self::STATUS_ERR, array("error" => 'UNKNOWN_METHOD', "method" => $method)); + } + } + + function shareToPublished() { + $title = strip_tags(clean($_REQUEST["title"])); + $url = strip_tags(clean($_REQUEST["url"])); + $content = strip_tags(clean($_REQUEST["content"])); + + if (Article::create_published_article($title, $url, $content, "", $_SESSION["uid"])) { + $this->wrap(self::STATUS_OK, array("status" => 'OK')); + } else { + $this->wrap(self::STATUS_ERR, array("error" => 'Publishing failed')); + } + } + + static function api_get_feeds($cat_id, $unread_only, $limit, $offset, $include_nested = false) { + + $feeds = array(); + + $pdo = Db::pdo(); + + $limit = (int) $limit; + $offset = (int) $offset; + $cat_id = (int) $cat_id; + + /* Labels */ + + if ($cat_id == -4 || $cat_id == -2) { + $counters = Counters::getLabelCounters(true); + + foreach (array_values($counters) as $cv) { + + $unread = $cv["counter"]; + + if ($unread || !$unread_only) { + + $row = array( + "id" => (int) $cv["id"], + "title" => $cv["description"], + "unread" => $cv["counter"], + "cat_id" => -2, + ); + + array_push($feeds, $row); + } + } + } + + /* Virtual feeds */ + + if ($cat_id == -4 || $cat_id == -1) { + foreach (array(-1, -2, -3, -4, -6, 0) as $i) { + $unread = getFeedUnread($i); + + if ($unread || !$unread_only) { + $title = Feeds::getFeedTitle($i); + + $row = array( + "id" => $i, + "title" => $title, + "unread" => $unread, + "cat_id" => -1, + ); + array_push($feeds, $row); + } + + } + } + + /* Child cats */ + + if ($include_nested && $cat_id) { + $sth = $pdo->prepare("SELECT + id, title, order_id FROM ttrss_feed_categories + WHERE parent_cat = ? AND owner_uid = ? ORDER BY id, title"); + + $sth->execute([$cat_id, $_SESSION['uid']]); + + while ($line = $sth->fetch()) { + $unread = getFeedUnread($line["id"], true) + + Feeds::getCategoryChildrenUnread($line["id"]); + + if ($unread || !$unread_only) { + $row = array( + "id" => (int) $line["id"], + "title" => $line["title"], + "unread" => $unread, + "is_cat" => true, + "order_id" => (int) $line["order_id"] + ); + array_push($feeds, $row); + } + } + } + + /* Real feeds */ + + if ($limit) { + $limit_qpart = "LIMIT $limit OFFSET $offset"; + } else { + $limit_qpart = ""; + } + + if ($cat_id == -4 || $cat_id == -3) { + $sth = $pdo->prepare("SELECT + id, feed_url, cat_id, title, order_id, ". + SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated + FROM ttrss_feeds WHERE owner_uid = ? + ORDER BY cat_id, title " . $limit_qpart); + $sth->execute([$_SESSION['uid']]); + + } else { + + $sth = $pdo->prepare("SELECT + id, feed_url, cat_id, title, order_id, ". + SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated + FROM ttrss_feeds WHERE + (cat_id = :cat OR (:cat = 0 AND cat_id IS NULL)) + AND owner_uid = :uid + ORDER BY cat_id, title " . $limit_qpart); + $sth->execute([":uid" => $_SESSION['uid'], ":cat" => $cat_id]); + } + + while ($line = $sth->fetch()) { + + $unread = getFeedUnread($line["id"]); + + $has_icon = Feeds::feedHasIcon($line['id']); + + if ($unread || !$unread_only) { + + $row = array( + "feed_url" => $line["feed_url"], + "title" => $line["title"], + "id" => (int)$line["id"], + "unread" => (int)$unread, + "has_icon" => $has_icon, + "cat_id" => (int)$line["cat_id"], + "last_updated" => (int) strtotime($line["last_updated"]), + "order_id" => (int) $line["order_id"], + ); + + array_push($feeds, $row); + } + } + + return $feeds; + } + + /** + * @SuppressWarnings(PHPMD.UnusedFormalParameter) + */ + static function api_get_headlines($feed_id, $limit, $offset, + $filter, $is_cat, $show_excerpt, $show_content, $view_mode, $order, + $include_attachments, $since_id, + $search = "", $include_nested = false, $sanitize_content = true, + $force_update = false, $excerpt_length = 100, $check_first_id = false, $skip_first_id_check = false) { + + $pdo = Db::pdo(); + + if ($force_update && $feed_id > 0 && is_numeric($feed_id)) { + // Update the feed if required with some basic flood control + + $sth = $pdo->prepare( + "SELECT cache_images,".SUBSTRING_FOR_DATE."(last_updated,1,19) AS last_updated + FROM ttrss_feeds WHERE id = ?"); + $sth->execute([$feed_id]); + + if ($row = $sth->fetch()) { + $last_updated = strtotime($row["last_updated"]); + $cache_images = API::param_to_bool($row["cache_images"]); + + if (!$cache_images && time() - $last_updated > 120) { + RSSUtils::update_rss_feed($feed_id, true); + } else { + $sth = $pdo->prepare("UPDATE ttrss_feeds SET last_updated = '1970-01-01', last_update_started = '1970-01-01' + WHERE id = ?"); + $sth->execute([$feed_id]); + } + } + } + + $params = array( + "feed" => $feed_id, + "limit" => $limit, + "view_mode" => $view_mode, + "cat_view" => $is_cat, + "search" => $search, + "override_order" => $order, + "offset" => $offset, + "since_id" => $since_id, + "include_children" => $include_nested, + "check_first_id" => $check_first_id, + "skip_first_id_check" => $skip_first_id_check + ); + + $qfh_ret = Feeds::queryFeedHeadlines($params); + + $result = $qfh_ret[0]; + $feed_title = $qfh_ret[1]; + $first_id = $qfh_ret[6]; + + $headlines = array(); + + $headlines_header = array( + 'id' => $feed_id, + 'first_id' => $first_id, + 'is_cat' => $is_cat); + + if (!is_numeric($result)) { + while ($line = $result->fetch()) { + $line["content_preview"] = truncate_string(strip_tags($line["content"]), $excerpt_length); + foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_QUERY_HEADLINES) as $p) { + $line = $p->hook_query_headlines($line, $excerpt_length, true); + } + + $is_updated = ($line["last_read"] == "" && + ($line["unread"] != "t" && $line["unread"] != "1")); + + $tags = explode(",", $line["tag_cache"]); + + $label_cache = $line["label_cache"]; + $labels = false; + + if ($label_cache) { + $label_cache = json_decode($label_cache, true); + + if ($label_cache) { + if ($label_cache["no-labels"] == 1) + $labels = array(); + else + $labels = $label_cache; + } + } + + if (!is_array($labels)) $labels = Article::get_article_labels($line["id"]); + + $headline_row = array( + "id" => (int)$line["id"], + "guid" => $line["guid"], + "unread" => API::param_to_bool($line["unread"]), + "marked" => API::param_to_bool($line["marked"]), + "published" => API::param_to_bool($line["published"]), + "updated" => (int)strtotime($line["updated"]), + "is_updated" => $is_updated, + "title" => $line["title"], + "link" => $line["link"], + "feed_id" => $line["feed_id"] ? $line['feed_id'] : 0, + "tags" => $tags, + ); + + if ($include_attachments) + $headline_row['attachments'] = Article::get_article_enclosures( + $line['id']); + + if ($show_excerpt) + $headline_row["excerpt"] = $line["content_preview"]; + + if ($show_content) { + + if ($sanitize_content) { + $headline_row["content"] = sanitize( + $line["content"], + API::param_to_bool($line['hide_images']), + false, $line["site_url"], false, $line["id"]); + } else { + $headline_row["content"] = $line["content"]; + } + } + + // unify label output to ease parsing + if ($labels["no-labels"] == 1) $labels = array(); + + $headline_row["labels"] = $labels; + + $headline_row["feed_title"] = $line["feed_title"] ? $line["feed_title"] : + $feed_title; + + $headline_row["comments_count"] = (int)$line["num_comments"]; + $headline_row["comments_link"] = $line["comments"]; + + $headline_row["always_display_attachments"] = API::param_to_bool($line["always_display_enclosures"]); + + $headline_row["author"] = $line["author"]; + + $headline_row["score"] = (int)$line["score"]; + $headline_row["note"] = $line["note"]; + $headline_row["lang"] = $line["lang"]; + + foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_RENDER_ARTICLE_API) as $p) { + $headline_row = $p->hook_render_article_api(array("headline" => $headline_row)); + } + + $headline_row['content'] = rewrite_cached_urls($headline_row['content']); + + array_push($headlines, $headline_row); + } + } else if (is_numeric($result) && $result == -1) { + $headlines_header['first_id_changed'] = true; + } + + return array($headlines, $headlines_header); + } + + function unsubscribeFeed() { + $feed_id = (int) clean($_REQUEST["feed_id"]); + + $sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE + id = ? AND owner_uid = ?"); + $sth->execute([$feed_id, $_SESSION['uid']]); + + if ($row = $sth->fetch()) { + Pref_Feeds::remove_feed($feed_id, $_SESSION["uid"]); + $this->wrap(self::STATUS_OK, array("status" => "OK")); + } else { + $this->wrap(self::STATUS_ERR, array("error" => "FEED_NOT_FOUND")); + } + } + + function subscribeToFeed() { + $feed_url = clean($_REQUEST["feed_url"]); + $category_id = (int) clean($_REQUEST["category_id"]); + $login = clean($_REQUEST["login"]); + $password = clean($_REQUEST["password"]); + + if ($feed_url) { + $rc = Feeds::subscribe_to_feed($feed_url, $category_id, $login, $password); + + $this->wrap(self::STATUS_OK, array("status" => $rc)); + } else { + $this->wrap(self::STATUS_ERR, array("error" => 'INCORRECT_USAGE')); + } + } + + function getFeedTree() { + $include_empty = API::param_to_bool(clean($_REQUEST['include_empty'])); + + $pf = new Pref_Feeds($_REQUEST); + + $_REQUEST['mode'] = 2; + $_REQUEST['force_show_empty'] = $include_empty; + + if ($pf){ + $data = $pf->makefeedtree(); + $this->wrap(self::STATUS_OK, array("categories" => $data)); + } else { + $this->wrap(self::STATUS_ERR, array("error" => + 'UNABLE_TO_INSTANTIATE_OBJECT')); + } + + } + + // only works for labels or uncategorized for the time being + private function isCategoryEmpty($id) { + + if ($id == -2) { + $sth = $this->pdo->prepare("SELECT COUNT(id) AS count FROM ttrss_labels2 + WHERE owner_uid = ?"); + $sth->execute([$_SESSION['uid']]); + $row = $sth->fetch(); + + return $row["count"] == 0; + + } else if ($id == 0) { + $sth = $this->pdo->prepare("SELECT COUNT(id) AS count FROM ttrss_feeds + WHERE cat_id IS NULL AND owner_uid = ?"); + $sth->execute([$_SESSION['uid']]); + $row = $sth->fetch(); + + return $row["count"] == 0; + + } + + return false; + } + + +} diff --git a/classes/article.php b/classes/article.php new file mode 100755 index 0000000..ff83143 --- /dev/null +++ b/classes/article.php @@ -0,0 +1,788 @@ +pdo->prepare("SELECT link FROM ttrss_entries, ttrss_user_entries + WHERE id = ? AND id = ref_id AND owner_uid = ? + LIMIT 1"); + $sth->execute([$id, $_SESSION['uid']]); + + if ($row = $sth->fetch()) { + $article_url = $row['link']; + $article_url = str_replace("\n", "", $article_url); + + header("Location: $article_url"); + return; + + } else { + print_error(__("Article not found.")); + } + } + + /* + function view() { + $id = clean($_REQUEST["id"]); + $cids = explode(",", clean($_REQUEST["cids"])); + $mode = clean($_REQUEST["mode"]); + + // in prefetch mode we only output requested cids, main article + // just gets marked as read (it already exists in client cache) + + $articles = array(); + + if ($mode == "") { + array_push($articles, $this->format_article($id, false)); + } else if ($mode == "zoom") { + array_push($articles, $this->format_article($id, true, true)); + } else if ($mode == "raw") { + if (isset($_REQUEST['html'])) { + header("Content-Type: text/html"); + print ''; + } + + $article = $this->format_article($id, false, isset($_REQUEST["zoom"])); + print $article['content']; + return; + } + + $this->catchupArticleById($id, 0); + + if (!$_SESSION["bw_limit"]) { + foreach ($cids as $cid) { + if ($cid) { + array_push($articles, $this->format_article($cid, false, false)); + } + } + } + + print json_encode($articles); + } */ + + /* + private function catchupArticleById($id, $cmode) { + + if ($cmode == 0) { + $sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET + unread = false,last_read = NOW() + WHERE ref_id = ? AND owner_uid = ?"); + } else if ($cmode == 1) { + $sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET + unread = true + WHERE ref_id = ? AND owner_uid = ?"); + } else { + $sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET + unread = NOT unread,last_read = NOW() + WHERE ref_id = ? AND owner_uid = ?"); + } + + $sth->execute([$id, $_SESSION['uid']]); + + $feed_id = $this->getArticleFeed($id); + CCache::update($feed_id, $_SESSION["uid"]); + } + */ + + static function create_published_article($title, $url, $content, $labels_str, + $owner_uid) { + + $guid = 'SHA1:' . sha1("ttshared:" . $url . $owner_uid); // include owner_uid to prevent global GUID clash + + if (!$content) { + $pluginhost = new PluginHost(); + $pluginhost->load_all(PluginHost::KIND_ALL, $owner_uid); + $pluginhost->load_data(); + + $af_readability = $pluginhost->get_plugin("Af_Readability"); + + if ($af_readability) { + $enable_share_anything = $pluginhost->get($af_readability, "enable_share_anything"); + + if ($enable_share_anything) { + $extracted_content = $af_readability->extract_content($url); + + if ($extracted_content) $content = $extracted_content; + } + } + } + + $content_hash = sha1($content); + + if ($labels_str != "") { + $labels = explode(",", $labels_str); + } else { + $labels = array(); + } + + $rc = false; + + if (!$title) $title = $url; + if (!$title && !$url) return false; + + if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) return false; + + $pdo = Db::pdo(); + + $pdo->beginTransaction(); + + // only check for our user data here, others might have shared this with different content etc + $sth = $pdo->prepare("SELECT id FROM ttrss_entries, ttrss_user_entries WHERE + guid = ? AND ref_id = id AND owner_uid = ? LIMIT 1"); + $sth->execute([$guid, $owner_uid]); + + if ($row = $sth->fetch()) { + $ref_id = $row['id']; + + $sth = $pdo->prepare("SELECT int_id FROM ttrss_user_entries WHERE + ref_id = ? AND owner_uid = ? LIMIT 1"); + $sth->execute([$ref_id, $owner_uid]); + + if ($row = $sth->fetch()) { + $int_id = $row['int_id']; + + $sth = $pdo->prepare("UPDATE ttrss_entries SET + content = ?, content_hash = ? WHERE id = ?"); + $sth->execute([$content, $content_hash, $ref_id]); + + $sth = $pdo->prepare("UPDATE ttrss_user_entries SET published = true, + last_published = NOW() WHERE + int_id = ? AND owner_uid = ?"); + $sth->execute([$int_id, $owner_uid]); + + } else { + + $sth = $pdo->prepare("INSERT INTO ttrss_user_entries + (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, + last_read, note, unread, last_published) + VALUES + (?, '', NULL, NULL, ?, true, '', '', NOW(), '', false, NOW())"); + $sth->execute([$ref_id, $owner_uid]); + } + + if (count($labels) != 0) { + foreach ($labels as $label) { + Labels::add_article($ref_id, trim($label), $owner_uid); + } + } + + $rc = true; + + } else { + $sth = $pdo->prepare("INSERT INTO ttrss_entries + (title, guid, link, updated, content, content_hash, date_entered, date_updated) + VALUES + (?, ?, ?, NOW(), ?, ?, NOW(), NOW())"); + $sth->execute([$title, $guid, $url, $content, $content_hash]); + + $sth = $pdo->prepare("SELECT id FROM ttrss_entries WHERE guid = ?"); + $sth->execute([$guid]); + + if ($row = $sth->fetch()) { + $ref_id = $row["id"]; + + $sth = $pdo->prepare("INSERT INTO ttrss_user_entries + (ref_id, uuid, feed_id, orig_feed_id, owner_uid, published, tag_cache, label_cache, + last_read, note, unread, last_published) + VALUES + (?, '', NULL, NULL, ?, true, '', '', NOW(), '', false, NOW())"); + $sth->execute([$ref_id, $owner_uid]); + + if (count($labels) != 0) { + foreach ($labels as $label) { + Labels::add_article($ref_id, trim($label), $owner_uid); + } + } + + $rc = true; + } + } + + $pdo->commit(); + + return $rc; + } + + function editArticleTags() { + + $param = clean($_REQUEST['param']); + + $tags = Article::get_article_tags($param); + + $tags_str = join(", ", $tags); + + print_hidden("id", "$param"); + print_hidden("op", "article"); + print_hidden("method", "setArticleTags"); + + print "
" . __("Tags for this article (separated by commas):")."
"; + + print "
"; + print " + "; + print "
"; + + print "
"; + print " "; + print ""; + print "
"; + + } + + function setScore() { + $ids = explode(",", clean($_REQUEST['id'])); + $score = (int)clean($_REQUEST['score']); + + $ids_qmarks = arr_qmarks($ids); + + $sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET + score = ? WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?"); + + $sth->execute(array_merge([$score], $ids, [$_SESSION['uid']])); + + print json_encode(["id" => $ids, "score" => (int)$score]); + } + + function getScore() { + $id = clean($_REQUEST['id']); + + $sth = $this->pdo->prepare("SELECT score FROM ttrss_user_entries WHERE ref_id = ? AND owner_uid = ?"); + $sth->execute([$id, $_SESSION['uid']]); + $row = $sth->fetch(); + + $score = $row['score']; + + print json_encode(["id" => $id, "score" => (int)$score]); + } + + + function setArticleTags() { + + $id = clean($_REQUEST["id"]); + + $tags_str = clean($_REQUEST["tags_str"]); + $tags = array_unique(trim_array(explode(",", $tags_str))); + + $this->pdo->beginTransaction(); + + $sth = $this->pdo->prepare("SELECT int_id FROM ttrss_user_entries WHERE + ref_id = ? AND owner_uid = ? LIMIT 1"); + $sth->execute([$id, $_SESSION['uid']]); + + if ($row = $sth->fetch()) { + + $tags_to_cache = array(); + + $int_id = $row['int_id']; + + $sth = $this->pdo->prepare("DELETE FROM ttrss_tags WHERE + post_int_id = ? AND owner_uid = ?"); + $sth->execute([$int_id, $_SESSION['uid']]); + + foreach ($tags as $tag) { + $tag = sanitize_tag($tag); + + if (!tag_is_valid($tag)) { + continue; + } + + if (preg_match("/^[0-9]*$/", $tag)) { + continue; + } + + // print ""; + + if ($tag != '') { + $sth = $this->pdo->prepare("INSERT INTO ttrss_tags + (post_int_id, owner_uid, tag_name) + VALUES (?, ?, ?)"); + + $sth->execute([$int_id, $_SESSION['uid'], $tag]); + } + + array_push($tags_to_cache, $tag); + } + + /* update tag cache */ + + sort($tags_to_cache); + $tags_str = join(",", $tags_to_cache); + + $sth = $this->pdo->prepare("UPDATE ttrss_user_entries + SET tag_cache = ? WHERE ref_id = ? AND owner_uid = ?"); + $sth->execute([$tags_str, $id, $_SESSION['uid']]); + } + + $this->pdo->commit(); + + $tags = Article::get_article_tags($id); + $tags_str = $this->format_tags_string($tags, $id); + $tags_str_full = join(", ", $tags); + + if (!$tags_str_full) $tags_str_full = __("no tags"); + + print json_encode(array("id" => (int)$id, + "content" => $tags_str, "content_full" => $tags_str_full)); + } + + + function completeTags() { + $search = clean($_REQUEST["search"]); + + $sth = $this->pdo->prepare("SELECT DISTINCT tag_name FROM ttrss_tags + WHERE owner_uid = ? AND + tag_name LIKE ? ORDER BY tag_name + LIMIT 10"); + + $sth->execute([$_SESSION['uid'], "$search%"]); + + print "
    "; + while ($line = $sth->fetch()) { + print "
  • " . $line["tag_name"] . "
  • "; + } + print "
"; + } + + function assigntolabel() { + return $this->labelops(true); + } + + function removefromlabel() { + return $this->labelops(false); + } + + private function labelops($assign) { + $reply = array(); + + $ids = explode(",", clean($_REQUEST["ids"])); + $label_id = clean($_REQUEST["lid"]); + + $label = Labels::find_caption($label_id, $_SESSION["uid"]); + + $reply["info-for-headlines"] = array(); + + if ($label) { + + foreach ($ids as $id) { + + if ($assign) + Labels::add_article($id, $label, $_SESSION["uid"]); + else + Labels::remove_article($id, $label, $_SESSION["uid"]); + + $labels = $this->get_article_labels($id, $_SESSION["uid"]); + + array_push($reply["info-for-headlines"], + array("id" => $id, "labels" => $this->format_article_labels($labels))); + + } + } + + $reply["message"] = "UPDATE_COUNTERS"; + + print json_encode($reply); + } + + function getArticleFeed($id) { + $sth = $this->pdo->prepare("SELECT feed_id FROM ttrss_user_entries + WHERE ref_id = ? AND owner_uid = ?"); + $sth->execute([$id, $_SESSION['uid']]); + + if ($row = $sth->fetch()) { + return $row["feed_id"]; + } else { + return 0; + } + } + + static function format_article_enclosures($id, $always_display_enclosures, + $article_content, $hide_images = false) { + + $result = Article::get_article_enclosures($id); + $rv = ''; + + foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_FORMAT_ENCLOSURES) as $plugin) { + $retval = $plugin->hook_format_enclosures($rv, $result, $id, $always_display_enclosures, $article_content, $hide_images); + if (is_array($retval)) { + $rv = $retval[0]; + $result = $retval[1]; + } else { + $rv = $retval; + } + } + unset($retval); // Unset to prevent breaking render if there are no HOOK_RENDER_ENCLOSURE hooks below. + + if ($rv === '' && !empty($result)) { + $entries_html = array(); + $entries = array(); + $entries_inline = array(); + + foreach ($result as $line) { + + foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ENCLOSURE_ENTRY) as $plugin) { + $line = $plugin->hook_enclosure_entry($line); + } + + $url = $line["content_url"]; + $ctype = $line["content_type"]; + $title = $line["title"]; + $width = $line["width"]; + $height = $line["height"]; + + if (!$ctype) $ctype = __("unknown type"); + + //$filename = substr($url, strrpos($url, "/")+1); + $filename = basename($url); + + $player = format_inline_player($url, $ctype); + + if ($player) array_push($entries_inline, $player); + +# $entry .= " " . +# $filename . " (" . $ctype . ")" . ""; + + $entry = "
$filename ($ctype)
"; + + array_push($entries_html, $entry); + + $entry = array(); + + $entry["type"] = $ctype; + $entry["filename"] = $filename; + $entry["url"] = $url; + $entry["title"] = $title; + $entry["width"] = $width; + $entry["height"] = $height; + + array_push($entries, $entry); + } + + if ($_SESSION['uid'] && !get_pref("STRIP_IMAGES") && !$_SESSION["bw_limit"]) { + if ($always_display_enclosures || + !preg_match("/get_hooks(PluginHost::HOOK_RENDER_ENCLOSURE) as $plugin) + $retval = $plugin->hook_render_enclosure($entry, $hide_images); + + + if ($retval) { + $rv .= $retval; + } else { + + if (preg_match("/image/", $entry["type"])) { + + if (!$hide_images) { + $encsize = ''; + if ($entry['height'] > 0) + $encsize .= ' height="' . intval($entry['height']) . '"'; + if ($entry['width'] > 0) + $encsize .= ' width="' . intval($entry['width']) . '"'; + $rv .= "

\"".htmlspecialchars($entry["filename"])."\"

"; + } else { + $rv .= "

" .htmlspecialchars($entry["url"]) . "

"; + } + + if ($entry['title']) { + $rv.= "
${entry['title']}
"; + } + } + } + } + } + } + + if (count($entries_inline) > 0) { + //$rv .= "
"; + foreach ($entries_inline as $entry) { $rv .= $entry; }; + $rv .= "
"; + } + + $rv .= "
". + "" . __('Attachments').""; + + $rv .= "
"; + + foreach ($entries as $entry) { + if ($entry["title"]) + $title = " — " . truncate_string($entry["title"], 30); + else + $title = ""; + + if ($entry["filename"]) + $filename = truncate_middle(htmlspecialchars($entry["filename"]), 60); + else + $filename = ""; + + $rv .= "
".$filename . $title."
"; + + }; + + $rv .= "
"; + $rv .= "
"; + } + + return $rv; + } + + static function get_article_tags($id, $owner_uid = 0, $tag_cache = false) { + + $a_id = $id; + + if (!$owner_uid) $owner_uid = $_SESSION["uid"]; + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT DISTINCT tag_name, + owner_uid as owner FROM ttrss_tags + WHERE post_int_id = (SELECT int_id FROM ttrss_user_entries WHERE + ref_id = ? AND owner_uid = ? LIMIT 1) ORDER BY tag_name"); + + $tags = array(); + + /* check cache first */ + + if ($tag_cache === false) { + $csth = $pdo->prepare("SELECT tag_cache FROM ttrss_user_entries + WHERE ref_id = ? AND owner_uid = ?"); + $csth->execute([$id, $owner_uid]); + + if ($row = $csth->fetch()) $tag_cache = $row["tag_cache"]; + } + + if ($tag_cache) { + $tags = explode(",", $tag_cache); + } else { + + /* do it the hard way */ + + $sth->execute([$a_id, $owner_uid]); + + while ($tmp_line = $sth->fetch()) { + array_push($tags, $tmp_line["tag_name"]); + } + + /* update the cache */ + + $tags_str = join(",", $tags); + + $sth = $pdo->prepare("UPDATE ttrss_user_entries + SET tag_cache = ? WHERE ref_id = ? + AND owner_uid = ?"); + $sth->execute([$tags_str, $id, $owner_uid]); + } + + return $tags; + } + + static function format_tags_string($tags) { + if (!is_array($tags) || count($tags) == 0) { + return __("no tags"); + } else { + $maxtags = min(5, count($tags)); + $tags_str = ""; + + for ($i = 0; $i < $maxtags; $i++) { + $tags_str .= "" . $tags[$i] . ", "; + } + + $tags_str = mb_substr($tags_str, 0, mb_strlen($tags_str)-2); + + if (count($tags) > $maxtags) + $tags_str .= ", …"; + + return $tags_str; + } + } + + static function format_article_labels($labels) { + + if (!is_array($labels)) return ''; + + $labels_str = ""; + + foreach ($labels as $l) { + $labels_str .= sprintf("
%s
", + $l[2], $l[3], $l[1]); + } + + return $labels_str; + + } + + static function format_article_note($id, $note, $allow_edit = true) { + + if ($allow_edit) { + $onclick = "onclick='Plugins.Note.edit($id)'"; + $note_class = 'editable'; + } else { + $onclick = ''; + $note_class = ''; + } + + return "
+ note +
$note
+
"; + + return $str; + } + + static function get_article_enclosures($id) { + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT * FROM ttrss_enclosures + WHERE post_id = ? AND content_url != ''"); + $sth->execute([$id]); + + $rv = array(); + + while ($line = $sth->fetch()) { + + if (file_exists(CACHE_DIR . '/images/' . sha1($line["content_url"]))) { + $line["content_url"] = get_self_url_prefix() . '/public.php?op=cached_url&hash=' . sha1($line["content_url"]); + } + + array_push($rv, $line); + } + + return $rv; + } + + static function purge_orphans() { + + // purge orphaned posts in main content table + + if (DB_TYPE == "mysql") + $limit_qpart = "LIMIT 5000"; + else + $limit_qpart = ""; + + $pdo = Db::pdo(); + $res = $pdo->query("DELETE FROM ttrss_entries WHERE + NOT EXISTS (SELECT ref_id FROM ttrss_user_entries WHERE ref_id = id) $limit_qpart"); + + if (Debug::enabled()) { + $rows = $res->rowCount(); + Debug::log("Purged $rows orphaned posts."); + } + } + + static function catchupArticlesById($ids, $cmode, $owner_uid = false) { + + if (!$owner_uid) $owner_uid = $_SESSION["uid"]; + + $pdo = Db::pdo(); + + $ids_qmarks = arr_qmarks($ids); + + if ($cmode == 1) { + $sth = $pdo->prepare("UPDATE ttrss_user_entries SET + unread = true + WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?"); + } else if ($cmode == 2) { + $sth = $pdo->prepare("UPDATE ttrss_user_entries SET + unread = NOT unread,last_read = NOW() + WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?"); + } else { + $sth = $pdo->prepare("UPDATE ttrss_user_entries SET + unread = false,last_read = NOW() + WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?"); + } + + $sth->execute(array_merge($ids, [$owner_uid])); + + /* update ccache */ + + $sth = $pdo->prepare("SELECT DISTINCT feed_id FROM ttrss_user_entries + WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?"); + $sth->execute(array_merge($ids, [$owner_uid])); + + while ($line = $sth->fetch()) { + CCache::update($line["feed_id"], $owner_uid); + } + } + + static function getLastArticleId() { + $pdo = DB::pdo(); + + $sth = $pdo->prepare("SELECT ref_id AS id FROM ttrss_user_entries + WHERE owner_uid = ? ORDER BY ref_id DESC LIMIT 1"); + $sth->execute([$_SESSION['uid']]); + + if ($row = $sth->fetch()) { + return $row['id']; + } else { + return -1; + } + } + + static function get_article_labels($id, $owner_uid = false) { + $rv = array(); + + if (!$owner_uid) $owner_uid = $_SESSION["uid"]; + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT label_cache FROM + ttrss_user_entries WHERE ref_id = ? AND owner_uid = ?"); + $sth->execute([$id, $owner_uid]); + + if ($row = $sth->fetch()) { + $label_cache = $row["label_cache"]; + + if ($label_cache) { + $tmp = json_decode($label_cache, true); + + if (!$tmp || $tmp["no-labels"] == 1) + return $rv; + else + return $tmp; + } + } + + $sth = $pdo->prepare("SELECT DISTINCT label_id,caption,fg_color,bg_color + FROM ttrss_labels2, ttrss_user_labels2 + WHERE id = label_id + AND article_id = ? + AND owner_uid = ? + ORDER BY caption"); + $sth->execute([$id, $owner_uid]); + + while ($line = $sth->fetch()) { + $rk = array(Labels::label_to_feed_id($line["label_id"]), + $line["caption"], $line["fg_color"], + $line["bg_color"]); + array_push($rv, $rk); + } + + if (count($rv) > 0) + Labels::update_cache($owner_uid, $id, $rv); + else + Labels::update_cache($owner_uid, $id, array("no-labels" => 1)); + + return $rv; + } + +} diff --git a/classes/auth/base.php b/classes/auth/base.php new file mode 100644 index 0000000..dbc77f8 --- /dev/null +++ b/classes/auth/base.php @@ -0,0 +1,62 @@ +pdo = Db::pdo(); + } + + /** + * @SuppressWarnings(unused) + */ + function check_password($owner_uid, $password) { + return false; + } + + /** + * @SuppressWarnings(unused) + */ + function authenticate($login, $password) { + return false; + } + + // Auto-creates specified user if allowed by system configuration + // Can be used instead of find_user_by_login() by external auth modules + function auto_create_user($login, $password = false) { + if ($login && defined('AUTH_AUTO_CREATE') && AUTH_AUTO_CREATE) { + $user_id = $this->find_user_by_login($login); + + if (!$password) $password = make_password(); + + if (!$user_id) { + $salt = substr(bin2hex(get_random_bytes(125)), 0, 250); + $pwd_hash = encrypt_password($password, $salt, true); + + $sth = $this->pdo->prepare("INSERT INTO ttrss_users + (login,access_level,last_login,created,pwd_hash,salt) + VALUES (?, 0, null, NOW(), ?,?)"); + $sth->execute([$login, $pwd_hash, $salt]); + + return $this->find_user_by_login($login); + + } else { + return $user_id; + } + } + + return $this->find_user_by_login($login); + } + + function find_user_by_login($login) { + $sth = $this->pdo->prepare("SELECT id FROM ttrss_users WHERE + login = ?"); + $sth->execute([$login]); + + if ($row = $sth->fetch()) { + return $row["id"]; + } else { + return false; + } + + } +} diff --git a/classes/backend.php b/classes/backend.php new file mode 100644 index 0000000..5bd7247 --- /dev/null +++ b/classes/backend.php @@ -0,0 +1,163 @@ +"; + } + + function digestTest() { + if (isset($_SESSION['uid'])) { + header("Content-type: text/html"); + + $rv = Digest::prepare_headlines_digest($_SESSION['uid'], 1, 1000); + + print "

HTML

"; + print $rv[0]; + print "

Plain text

"; + print "
".$rv[3]."
"; + } else { + print error_json(6); + } + } + + private function display_main_help() { + $info = get_hotkeys_info(); + $imap = get_hotkeys_map(); + $omap = array(); + + foreach ($imap[1] as $sequence => $action) { + if (!isset($omap[$action])) $omap[$action] = array(); + + array_push($omap[$action], $sequence); + } + + print "
    "; + + print "

    " . __("Keyboard Shortcuts") . "

    "; + + foreach ($info as $section => $hotkeys) { + + print "

  • "; + print "
  • " . $section . "

  • "; + + foreach ($hotkeys as $action => $description) { + + if (is_array($omap[$action])) { + foreach ($omap[$action] as $sequence) { + if (strpos($sequence, "|") !== FALSE) { + $sequence = substr($sequence, + strpos($sequence, "|")+1, + strlen($sequence)); + } else { + $keys = explode(" ", $sequence); + + for ($i = 0; $i < count($keys); $i++) { + if (strlen($keys[$i]) > 1) { + $tmp = ''; + foreach (str_split($keys[$i]) as $c) { + switch ($c) { + case '*': + $tmp .= __('Shift') . '+'; + break; + case '^': + $tmp .= __('Ctrl') . '+'; + break; + default: + $tmp .= $c; + } + } + $keys[$i] = $tmp; + } + } + $sequence = join(" ", $keys); + } + + print "
  • "; + print "
    $sequence
    "; + print "
    $description
    "; + print "
  • "; + } + } + } + } + + print "
"; + + + } + + function help() { + $topic = basename(clean($_REQUEST["topic"])); // only one for now + + if ($topic == "main") { + $info = get_hotkeys_info(); + $imap = get_hotkeys_map(); + $omap = array(); + + foreach ($imap[1] as $sequence => $action) { + if (!isset($omap[$action])) $omap[$action] = array(); + + array_push($omap[$action], $sequence); + } + + print "
    "; + + $cur_section = ""; + foreach ($info as $section => $hotkeys) { + + if ($cur_section) print "
  •  
  • "; + print "
  • " . $section . "

  • "; + $cur_section = $section; + + foreach ($hotkeys as $action => $description) { + + if (is_array($omap[$action])) { + foreach ($omap[$action] as $sequence) { + if (strpos($sequence, "|") !== FALSE) { + $sequence = substr($sequence, + strpos($sequence, "|")+1, + strlen($sequence)); + } else { + $keys = explode(" ", $sequence); + + for ($i = 0; $i < count($keys); $i++) { + if (strlen($keys[$i]) > 1) { + $tmp = ''; + foreach (str_split($keys[$i]) as $c) { + switch ($c) { + case '*': + $tmp .= __('Shift') . '+'; + break; + case '^': + $tmp .= __('Ctrl') . '+'; + break; + default: + $tmp .= $c; + } + } + $keys[$i] = $tmp; + } + } + $sequence = join(" ", $keys); + } + + print "
  • "; + print "
    $sequence
    "; + print "
    $description
    "; + print "
  • "; + } + } + } + } + + print "
"; + } + + print "
"; + print ""; + print "
"; + + } +} diff --git a/classes/ccache.php b/classes/ccache.php new file mode 100644 index 0000000..2f19140 --- /dev/null +++ b/classes/ccache.php @@ -0,0 +1,211 @@ +prepare("UPDATE ttrss_counters_cache SET + value = 0 WHERE owner_uid = ?"); + $sth->execute([$owner_uid]); + + $sth = $pdo->prepare("UPDATE ttrss_cat_counters_cache SET + value = 0 WHERE owner_uid = ?"); + $sth->execute([$owner_uid]); + } + + static function remove($feed_id, $owner_uid, $is_cat = false) { + + $feed_id = (int) $feed_id; + + if (!$is_cat) { + $table = "ttrss_counters_cache"; + } else { + $table = "ttrss_cat_counters_cache"; + } + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("DELETE FROM $table WHERE + feed_id = ? AND owner_uid = ?"); + $sth->execute([$feed_id, $owner_uid]); + + } + + static function update_all($owner_uid) { + + $pdo = Db::pdo(); + + if (get_pref('ENABLE_FEED_CATS', $owner_uid)) { + + $sth = $pdo->prepare("SELECT feed_id FROM ttrss_cat_counters_cache + WHERE feed_id > 0 AND owner_uid = ?"); + $sth->execute([$owner_uid]); + + while ($line = $sth->fetch()) { + CCache::update($line["feed_id"], $owner_uid, true); + } + + /* We have to manually include category 0 */ + + CCache::update(0, $owner_uid, true); + + } else { + $sth = $pdo->prepare("SELECT feed_id FROM ttrss_counters_cache + WHERE feed_id > 0 AND owner_uid = ?"); + $sth->execute([$owner_uid]); + + while ($line = $sth->fetch()) { + print CCache::update($line["feed_id"], $owner_uid); + + } + + } + } + + static function find($feed_id, $owner_uid, $is_cat = false, + $no_update = false) { + + // "" (null) is valid and should be cast to 0 (uncategorized) + // everything else i.e. tags are not + if (!is_numeric($feed_id) && $feed_id) + return; + + $feed_id = (int) $feed_id; + + if (!$is_cat) { + $table = "ttrss_counters_cache"; + } else { + $table = "ttrss_cat_counters_cache"; + } + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT value FROM $table + WHERE owner_uid = ? AND feed_id = ? + LIMIT 1"); + + $sth->execute([$owner_uid, $feed_id]); + + if ($row = $sth->fetch()) { + return $row["value"]; + } else { + if ($no_update) { + return -1; + } else { + return CCache::update($feed_id, $owner_uid, $is_cat); + } + } + + } + + static function update($feed_id, $owner_uid, $is_cat = false, + $update_pcat = true, $pcat_fast = false) { + + // "" (null) is valid and should be cast to 0 (uncategorized) + // everything else i.e. tags are not + if (!is_numeric($feed_id) && $feed_id) + return; + + $feed_id = (int) $feed_id; + + $prev_unread = CCache::find($feed_id, $owner_uid, $is_cat, true); + + /* When updating a label, all we need to do is recalculate feed counters + * because labels are not cached */ + + if ($feed_id < 0) { + CCache::update_all($owner_uid); + return; + } + + if (!$is_cat) { + $table = "ttrss_counters_cache"; + } else { + $table = "ttrss_cat_counters_cache"; + } + + $pdo = Db::pdo(); + + if ($is_cat && $feed_id >= 0) { + /* Recalculate counters for child feeds */ + + if (!$pcat_fast) { + $sth = $pdo->prepare("SELECT id FROM ttrss_feeds + WHERE owner_uid = :uid AND + (cat_id = :cat OR (:cat = 0 AND cat_id IS NULL))"); + $sth->execute([":uid" => $owner_uid, ":cat" => $feed_id]); + + while ($line = $sth->fetch()) { + CCache::update((int)$line["id"], $owner_uid, false, false); + } + } + + $sth = $pdo->prepare("SELECT SUM(value) AS sv + FROM ttrss_counters_cache, ttrss_feeds + WHERE ttrss_feeds.id = feed_id AND + (cat_id = :cat OR (:cat = 0 AND cat_id IS NULL)) AND + ttrss_counters_cache.owner_uid = :uid AND + ttrss_feeds.owner_uid = :uid"); + $sth->execute([":uid" => $owner_uid, ":cat" => $feed_id]); + $row = $sth->fetch(); + + $unread = (int) $row["sv"]; + + } else { + $unread = (int) Feeds::getFeedArticles($feed_id, $is_cat, true, $owner_uid); + } + + $tr_in_progress = false; + + try { + $pdo->beginTransaction(); + } catch (Exception $e) { + $tr_in_progress = true; + } + + $sth = $pdo->prepare("SELECT feed_id FROM $table + WHERE owner_uid = ? AND feed_id = ? LIMIT 1"); + $sth->execute([$owner_uid, $feed_id]); + + if ($sth->fetch()) { + + $sth = $pdo->prepare("UPDATE $table SET + value = ?, updated = NOW() WHERE + feed_id = ? AND owner_uid = ?"); + + $sth->execute([$unread, $feed_id, $owner_uid]); + + } else { + $sth = $pdo->prepare("INSERT INTO $table + (feed_id, value, owner_uid, updated) + VALUES + (?, ?, ?, NOW())"); + $sth->execute([$feed_id, $unread, $owner_uid]); + } + + if (!$tr_in_progress) $pdo->commit(); + + if ($feed_id > 0 && $prev_unread != $unread) { + + if (!$is_cat) { + + /* Update parent category */ + + if ($update_pcat) { + + $sth = $pdo->prepare("SELECT cat_id FROM ttrss_feeds + WHERE owner_uid = ? AND id = ?"); + $sth->execute([$owner_uid, $feed_id]); + + if ($row = $sth->fetch()) { + CCache::update((int)$row["cat_id"], $owner_uid, true, true, true); + } + } + } + } else if ($feed_id < 0) { + CCache::update_all($owner_uid); + } + + return $unread; + } + +} \ No newline at end of file diff --git a/classes/counters.php b/classes/counters.php new file mode 100644 index 0000000..cee9013 --- /dev/null +++ b/classes/counters.php @@ -0,0 +1,216 @@ + -2, "kind" => "cat", + "counter" => Feeds::getCategoryUnread(-2)); + + array_push($ret_arr, $cv); + + $pdo = DB::pdo(); + + $sth = $pdo->prepare("SELECT ttrss_feed_categories.id AS cat_id, value AS unread, + (SELECT COUNT(id) FROM ttrss_feed_categories AS c2 + WHERE c2.parent_cat = ttrss_feed_categories.id) AS num_children + FROM ttrss_feed_categories, ttrss_cat_counters_cache + WHERE ttrss_cat_counters_cache.feed_id = ttrss_feed_categories.id AND + ttrss_cat_counters_cache.owner_uid = ttrss_feed_categories.owner_uid AND + ttrss_feed_categories.owner_uid = ?"); + $sth->execute([$_SESSION['uid']]); + + while ($line = $sth->fetch()) { + $line["cat_id"] = (int) $line["cat_id"]; + + if ($line["num_children"] > 0) { + $child_counter = Feeds::getCategoryChildrenUnread($line["cat_id"], $_SESSION["uid"]); + } else { + $child_counter = 0; + } + + $cv = array("id" => $line["cat_id"], "kind" => "cat", + "counter" => $line["unread"] + $child_counter); + + array_push($ret_arr, $cv); + } + + /* Special case: NULL category doesn't actually exist in the DB */ + + $cv = array("id" => 0, "kind" => "cat", + "counter" => (int) CCache::find(0, $_SESSION["uid"], true)); + + array_push($ret_arr, $cv); + + return $ret_arr; + } + + static function getGlobalCounters($global_unread = -1) { + $ret_arr = array(); + + if ($global_unread == -1) { + $global_unread = Feeds::getGlobalUnread(); + } + + $cv = array("id" => "global-unread", + "counter" => (int) $global_unread); + + array_push($ret_arr, $cv); + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT COUNT(id) AS fn FROM + ttrss_feeds WHERE owner_uid = ?"); + $sth->execute([$_SESSION['uid']]); + $row = $sth->fetch(); + + $subscribed_feeds = $row["fn"]; + + $cv = array("id" => "subscribed-feeds", + "counter" => (int) $subscribed_feeds); + + array_push($ret_arr, $cv); + + return $ret_arr; + } + + static function getVirtCounters() { + + $ret_arr = array(); + + for ($i = 0; $i >= -4; $i--) { + + $count = getFeedUnread($i); + + if ($i == 0 || $i == -1 || $i == -2) + $auxctr = Feeds::getFeedArticles($i, false); + else + $auxctr = 0; + + $cv = array("id" => $i, + "counter" => (int) $count, + "auxcounter" => (int) $auxctr); + +// if (get_pref('EXTENDED_FEEDLIST')) +// $cv["xmsg"] = getFeedArticles($i)." ".__("total"); + + array_push($ret_arr, $cv); + } + + $feeds = PluginHost::getInstance()->get_feeds(-1); + + if (is_array($feeds)) { + foreach ($feeds as $feed) { + $cv = array("id" => PluginHost::pfeed_to_feed_id($feed['id']), + "counter" => $feed['sender']->get_unread($feed['id'])); + + if (method_exists($feed['sender'], 'get_total')) + $cv["auxcounter"] = $feed['sender']->get_total($feed['id']); + + array_push($ret_arr, $cv); + } + } + + return $ret_arr; + } + + static function getLabelCounters($descriptions = false) { + + $ret_arr = array(); + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT id,caption,SUM(CASE WHEN u1.unread = true THEN 1 ELSE 0 END) AS unread, COUNT(u1.unread) AS total + FROM ttrss_labels2 LEFT JOIN ttrss_user_labels2 ON + (ttrss_labels2.id = label_id) + LEFT JOIN ttrss_user_entries AS u1 ON u1.ref_id = article_id + WHERE ttrss_labels2.owner_uid = :uid AND u1.owner_uid = :uid + GROUP BY ttrss_labels2.id, + ttrss_labels2.caption"); + $sth->execute([":uid" => $_SESSION['uid']]); + + while ($line = $sth->fetch()) { + + $id = Labels::label_to_feed_id($line["id"]); + + $cv = array("id" => $id, + "counter" => (int) $line["unread"], + "auxcounter" => (int) $line["total"]); + + if ($descriptions) + $cv["description"] = $line["caption"]; + + array_push($ret_arr, $cv); + } + + return $ret_arr; + } + + static function getFeedCounters($active_feed = false) { + + $ret_arr = array(); + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT ttrss_feeds.id, + ttrss_feeds.title, + ".SUBSTRING_FOR_DATE."(ttrss_feeds.last_updated,1,19) AS last_updated, + last_error, value AS count + FROM ttrss_feeds, ttrss_counters_cache + WHERE ttrss_feeds.owner_uid = ? + AND ttrss_counters_cache.owner_uid = ttrss_feeds.owner_uid + AND ttrss_counters_cache.feed_id = ttrss_feeds.id"); + $sth->execute([$_SESSION['uid']]); + + while ($line = $sth->fetch()) { + + $id = $line["id"]; + $count = $line["count"]; + $last_error = htmlspecialchars($line["last_error"]); + + $last_updated = make_local_datetime($line['last_updated'], false); + + if (Feeds::feedHasIcon($id)) { + $has_img = filemtime(Feeds::getIconFile($id)); + } else { + $has_img = false; + } + + if (date('Y') - date('Y', strtotime($line['last_updated'])) > 2) + $last_updated = ''; + + $cv = array("id" => $id, + "updated" => $last_updated, + "counter" => (int) $count, + "has_img" => (int) $has_img); + + if ($last_error) + $cv["error"] = $last_error; + +// if (get_pref('EXTENDED_FEEDLIST')) +// $cv["xmsg"] = getFeedArticles($id)." ".__("total"); + + if ($active_feed && $id == $active_feed) + $cv["title"] = truncate_string($line["title"], 30); + + array_push($ret_arr, $cv); + + } + + return $ret_arr; + } + +} \ No newline at end of file diff --git a/classes/db.php b/classes/db.php new file mode 100755 index 0000000..ac493f6 --- /dev/null +++ b/classes/db.php @@ -0,0 +1,116 @@ +adapter = new Db_Mysqli(); + break; + case "pgsql": + $this->adapter = new Db_Pgsql(); + break; + default: + die("Unknown DB_TYPE: " . DB_TYPE); + } + + if (!$this->adapter) { + print("Error initializing database adapter for " . DB_TYPE); + exit(100); + } + + $this->link = $this->adapter->connect(DB_HOST, DB_USER, DB_PASS, DB_NAME, defined('DB_PORT') ? DB_PORT : ""); + + if (!$this->link) { + print("Error connecting through adapter: " . $this->adapter->last_error()); + exit(101); + } + + error_reporting($er); + } + + // this really shouldn't be used unless a separate PDO connection is needed + // normal usage is Db::pdo()->prepare(...) etc + public function pdo_connect() { + + $db_port = defined('DB_PORT') && DB_PORT ? ';port=' . DB_PORT : ''; + $db_host = defined('DB_HOST') && DB_HOST ? ';host=' . DB_HOST : ''; + + try { + $pdo = new PDO(DB_TYPE . ':dbname=' . DB_NAME . $db_host . $db_port, + DB_USER, + DB_PASS); + } catch (Exception $e) { + print "
Exception while creating PDO object:" . $e->getMessage() . "
"; + exit(101); + } + + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + if (DB_TYPE == "pgsql") { + + $pdo->query("set client_encoding = 'UTF-8'"); + $pdo->query("set datestyle = 'ISO, european'"); + $pdo->query("set TIME ZONE 0"); + $pdo->query("set cpu_tuple_cost = 0.5"); + + } else if (DB_TYPE == "mysql") { + $pdo->query("SET time_zone = '+0:0'"); + + if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) { + $pdo->query("SET NAMES " . MYSQL_CHARSET); + } + } + + return $pdo; + } + + public static function instance() { + if (self::$instance == null) + self::$instance = new self(); + + return self::$instance; + } + + public static function get() { + if (self::$instance == null) + self::$instance = new self(); + + if (!self::$instance->adapter) { + self::$instance->legacy_connect(); + } + + return self::$instance->adapter; + } + + public static function pdo() { + if (self::$instance == null) + self::$instance = new self(); + + if (!self::$instance->pdo) { + self::$instance->pdo = self::$instance->pdo_connect(); + } + + return self::$instance->pdo; + } +} diff --git a/classes/db/mysqli.php b/classes/db/mysqli.php new file mode 100644 index 0000000..a05b121 --- /dev/null +++ b/classes/db/mysqli.php @@ -0,0 +1,85 @@ +link = mysqli_connect($host, $user, $pass, $db, $port); + else + $this->link = mysqli_connect($host, $user, $pass, $db); + + if ($this->link) { + $this->init(); + + return $this->link; + } else { + print("Unable to connect to database (as $user to $host, database $db): " . mysqli_connect_error()); + exit(102); + } + } + + function escape_string($s, $strip_tags = true) { + if ($strip_tags) $s = strip_tags($s); + + return mysqli_real_escape_string($this->link, $s); + } + + function query($query, $die_on_error = true) { + $result = @mysqli_query($this->link, $query); + if (!$result) { + $this->last_error = @mysqli_error($this->link); + + @mysqli_query($this->link, "ROLLBACK"); + user_error("Query $query failed: " . ($this->link ? $this->last_error : "No connection"), + $die_on_error ? E_USER_ERROR : E_USER_WARNING); + } + + return $result; + } + + function fetch_assoc($result) { + return mysqli_fetch_assoc($result); + } + + + function num_rows($result) { + return mysqli_num_rows($result); + } + + function fetch_result($result, $row, $param) { + if (mysqli_data_seek($result, $row)) { + $line = mysqli_fetch_assoc($result); + return $line[$param]; + } else { + return false; + } + } + + function close() { + return mysqli_close($this->link); + } + + function affected_rows($result) { + return mysqli_affected_rows($this->link); + } + + function last_error() { + return mysqli_error($this->link); + } + + function last_query_error() { + return $this->last_error; + } + + function init() { + $this->query("SET time_zone = '+0:0'"); + + if (defined('MYSQL_CHARSET') && MYSQL_CHARSET) { + mysqli_set_charset($this->link, MYSQL_CHARSET); + } + + return true; + } + +} diff --git a/classes/db/pgsql.php b/classes/db/pgsql.php new file mode 100644 index 0000000..98fab6b --- /dev/null +++ b/classes/db/pgsql.php @@ -0,0 +1,91 @@ + 0) { + $string = "$string port=" . $port; + } + + $this->link = pg_connect($string); + + if (!$this->link) { + print("Unable to connect to database (as $user to $host, database $db):" . pg_last_error()); + exit(102); + } + + $this->init(); + + return $this->link; + } + + function escape_string($s, $strip_tags = true) { + if ($strip_tags) $s = strip_tags($s); + + return pg_escape_string($s); + } + + function query($query, $die_on_error = true) { + $result = @pg_query($this->link, $query); + + if (!$result) { + $this->last_error = @pg_last_error($this->link); + + @pg_query($this->link, "ROLLBACK"); + $query = htmlspecialchars($query); // just in case + user_error("Query $query failed: " . ($this->link ? $this->last_error : "No connection"), + $die_on_error ? E_USER_ERROR : E_USER_WARNING); + } + return $result; + } + + function fetch_assoc($result) { + return pg_fetch_assoc($result); + } + + + function num_rows($result) { + return pg_num_rows($result); + } + + function fetch_result($result, $row, $param) { + return pg_fetch_result($result, $row, $param); + } + + function close() { + return pg_close($this->link); + } + + function affected_rows($result) { + return pg_affected_rows($result); + } + + function last_error() { + return pg_last_error($this->link); + } + + function last_query_error() { + return $this->last_error; + } + + function init() { + $this->query("set client_encoding = 'UTF-8'"); + pg_set_client_encoding("UNICODE"); + $this->query("set datestyle = 'ISO, european'"); + $this->query("set TIME ZONE 0"); + $this->query("set cpu_tuple_cost = 0.5"); + + return true; + } +} \ No newline at end of file diff --git a/classes/db/prefs.php b/classes/db/prefs.php new file mode 100644 index 0000000..1fddd27 --- /dev/null +++ b/classes/db/prefs.php @@ -0,0 +1,171 @@ +pdo = Db::pdo(); + $this->cache = array(); + + if ($_SESSION["uid"]) $this->cache(); + } + + private function __clone() { + // + } + + public static function get() { + if (self::$instance == null) + self::$instance = new self(); + + return self::$instance; + } + + function cache() { + $user_id = $_SESSION["uid"]; + @$profile = $_SESSION["profile"]; + + if (!is_numeric($profile) || !$profile || get_schema_version() < 63) $profile = null; + + $sth = $this->pdo->prepare("SELECT + value,ttrss_prefs_types.type_name as type_name,ttrss_prefs.pref_name AS pref_name + FROM + ttrss_user_prefs,ttrss_prefs,ttrss_prefs_types + WHERE + (profile = :profile OR (:profile IS NULL AND profile IS NULL)) AND + ttrss_prefs.pref_name NOT LIKE '_MOBILE%' AND + ttrss_prefs_types.id = type_id AND + owner_uid = :uid AND + ttrss_user_prefs.pref_name = ttrss_prefs.pref_name"); + + $sth->execute([":profile" => $profile, ":uid" => $user_id]); + + while ($line = $sth->fetch()) { + if ($user_id == $_SESSION["uid"]) { + $pref_name = $line["pref_name"]; + + $this->cache[$pref_name]["type"] = $line["type_name"]; + $this->cache[$pref_name]["value"] = $line["value"]; + } + } + } + + function read($pref_name, $user_id = false, $die_on_error = false) { + + if (!$user_id) { + $user_id = $_SESSION["uid"]; + @$profile = $_SESSION["profile"]; + } else { + $profile = false; + } + + if ($user_id == $_SESSION['uid'] && isset($this->cache[$pref_name])) { + $tuple = $this->cache[$pref_name]; + return $this->convert($tuple["value"], $tuple["type"]); + } + + if (!is_numeric($profile) || !$profile || get_schema_version() < 63) $profile = null; + + $sth = $this->pdo->prepare("SELECT + value,ttrss_prefs_types.type_name as type_name + FROM + ttrss_user_prefs,ttrss_prefs,ttrss_prefs_types + WHERE + (profile = :profile OR (:profile IS NULL AND profile IS NULL)) AND + ttrss_user_prefs.pref_name = :pref_name AND + ttrss_prefs_types.id = type_id AND + owner_uid = :uid AND + ttrss_user_prefs.pref_name = ttrss_prefs.pref_name"); + $sth->execute([":uid" => $user_id, ":profile" => $profile, ":pref_name" => $pref_name]); + + if ($row = $sth->fetch()) { + $value = $row["value"]; + $type_name = $row["type_name"]; + + if ($user_id == $_SESSION["uid"]) { + $this->cache[$pref_name]["type"] = $type_name; + $this->cache[$pref_name]["value"] = $value; + } + + return $this->convert($value, $type_name); + + } else { + user_error("Fatal error, unknown preferences key: $pref_name (owner: $user_id)", $die_on_error ? E_USER_ERROR : E_USER_WARNING); + return null; + } + } + + function convert($value, $type_name) { + if ($type_name == "bool") { + return $value == "true"; + } else if ($type_name == "integer") { + return (int)$value; + } else { + return $value; + } + } + + function write($pref_name, $value, $user_id = false, $strip_tags = true) { + if ($strip_tags) $value = strip_tags($value); + + if (!$user_id) { + $user_id = $_SESSION["uid"]; + @$profile = $_SESSION["profile"]; + } else { + $profile = null; + } + + if (!is_numeric($profile) || !$profile || get_schema_version() < 63) $profile = null; + + $type_name = ""; + $current_value = ""; + + if (isset($this->cache[$pref_name])) { + $type_name = $this->cache[$pref_name]["type"]; + $current_value = $this->cache[$pref_name]["value"]; + } + + if (!$type_name) { + $sth = $this->pdo->prepare("SELECT type_name + FROM ttrss_prefs,ttrss_prefs_types + WHERE pref_name = ? AND type_id = ttrss_prefs_types.id"); + $sth->execute([$pref_name]); + + if ($row = $sth->fetch()) + $type_name = $row["type_name"]; + + } else if ($current_value == $value) { + return; + } + + if ($type_name) { + if ($type_name == "bool") { + if ($value == "1" || $value == "true") { + $value = "true"; + } else { + $value = "false"; + } + } else if ($type_name == "integer") { + $value = (int)$value; + } + + if ($pref_name == 'USER_TIMEZONE' && $value == '') { + $value = 'UTC'; + } + + $sth = $this->pdo->prepare("UPDATE ttrss_user_prefs SET + value = :value WHERE pref_name = :pref_name + AND (profile = :profile OR (:profile IS NULL AND profile IS NULL)) + AND owner_uid = :uid"); + + $sth->execute([":pref_name" => $pref_name, ":value" => $value, ":uid" => $user_id, ":profile" => $profile]); + + if ($user_id == $_SESSION["uid"]) { + $this->cache[$pref_name]["type"] = $type_name; + $this->cache[$pref_name]["value"] = $value; + } + } + } + +} diff --git a/classes/dbupdater.php b/classes/dbupdater.php new file mode 100644 index 0000000..94307ae --- /dev/null +++ b/classes/dbupdater.php @@ -0,0 +1,83 @@ +pdo = Db::pdo(); //$pdo; + $this->db_type = $db_type; + $this->need_version = (int) $need_version; + } + + function getSchemaVersion() { + $row = $this->pdo->query("SELECT schema_version FROM ttrss_version")->fetch(); + return (int) $row['schema_version']; + } + + function isUpdateRequired() { + return $this->getSchemaVersion() < $this->need_version; + } + + function getSchemaLines($version) { + $filename = "schema/versions/".$this->db_type."/$version.sql"; + + if (file_exists($filename)) { + return explode(";", preg_replace("/[\r\n]/", "", file_get_contents($filename))); + } else { + user_error("DB Updater: schema file for version $version is not found."); + return false; + } + } + + function performUpdateTo($version, $html_output = true) { + if ($this->getSchemaVersion() == $version - 1) { + + $lines = $this->getSchemaLines($version); + + if (is_array($lines)) { + + $this->pdo->beginTransaction(); + + foreach ($lines as $line) { + if (strpos($line, "--") !== 0 && $line) { + + if ($html_output) + print "
$line
"; + else + Debug::log("> $line"); + + try { + $this->pdo->query($line); // PDO returns errors as exceptions now + } catch (PDOException $e) { + if ($html_output) { + print "
Error: " . $e->getMessage() . "
"; + } else { + Debug::log("Error: " . $e->getMessage()); + } + + $this->pdo->rollBack(); + return false; + } + } + } + + $db_version = $this->getSchemaVersion(); + + if ($db_version == $version) { + $this->pdo->commit(); + return true; + } else { + $this->pdo->rollBack(); + return false; + } + } else { + return false; + } + } else { + return false; + } + } + +} diff --git a/classes/debug.php b/classes/debug.php new file mode 100644 index 0000000..c62f0c9 --- /dev/null +++ b/classes/debug.php @@ -0,0 +1,86 @@ +query("SELECT id,email FROM ttrss_users + WHERE email != '' AND (last_digest_sent IS NULL OR $interval_qpart)"); + + while ($line = $res->fetch()) { + + if (@get_pref('DIGEST_ENABLE', $line['id'], false)) { + $preferred_ts = strtotime(get_pref('DIGEST_PREFERRED_TIME', $line['id'], '00:00')); + + // try to send digests within 2 hours of preferred time + if ($preferred_ts && time() >= $preferred_ts && + time() - $preferred_ts <= 7200 + ) { + + Debug::log("Sending digest for UID:" . $line['id'] . " - " . $line["email"]); + + $do_catchup = get_pref('DIGEST_CATCHUP', $line['id'], false); + + global $tz_offset; + + // reset tz_offset global to prevent tz cache clash between users + $tz_offset = -1; + + $tuple = Digest::prepare_headlines_digest($line["id"], 1, $limit); + $digest = $tuple[0]; + $headlines_count = $tuple[1]; + $affected_ids = $tuple[2]; + $digest_text = $tuple[3]; + + if ($headlines_count > 0) { + + $mailer = new Mailer(); + + //$rc = $mail->quickMail($line["email"], $line["login"], DIGEST_SUBJECT, $digest, $digest_text); + + $rc = $mailer->mail(["to_name" => $line["login"], + "to_address" => $line["email"], + "subject" => DIGEST_SUBJECT, + "message" => $digest_text, + "message_html" => $digest]); + + //if (!$rc && $debug) Debug::log("ERROR: " . $mailer->lastError()); + + Debug::log("RC=$rc"); + + if ($rc && $do_catchup) { + Debug::log("Marking affected articles as read..."); + Article::catchupArticlesById($affected_ids, 0, $line["id"]); + } + } else { + Debug::log("No headlines"); + } + + $sth = $pdo->prepare("UPDATE ttrss_users SET last_digest_sent = NOW() + WHERE id = ?"); + $sth->execute([$line["id"]]); + + } + } + } + + Debug::log("All done."); + + } + + static function prepare_headlines_digest($user_id, $days = 1, $limit = 1000) { + + require_once "lib/MiniTemplator.class.php"; + + $tpl = new MiniTemplator; + $tpl_t = new MiniTemplator; + + $tpl->readTemplateFromFile("templates/digest_template_html.txt"); + $tpl_t->readTemplateFromFile("templates/digest_template.txt"); + + $user_tz_string = get_pref('USER_TIMEZONE', $user_id); + $local_ts = convert_timestamp(time(), 'UTC', $user_tz_string); + + $tpl->setVariable('CUR_DATE', date('Y/m/d', $local_ts)); + $tpl->setVariable('CUR_TIME', date('G:i', $local_ts)); + + $tpl_t->setVariable('CUR_DATE', date('Y/m/d', $local_ts)); + $tpl_t->setVariable('CUR_TIME', date('G:i', $local_ts)); + + $affected_ids = array(); + + $days = (int) $days; + + if (DB_TYPE == "pgsql") { + $interval_qpart = "ttrss_entries.date_updated > NOW() - INTERVAL '$days days'"; + } else if (DB_TYPE == "mysql") { + $interval_qpart = "ttrss_entries.date_updated > DATE_SUB(NOW(), INTERVAL $days DAY)"; + } + + $pdo = Db::pdo(); + + $sth = $pdo->prepare("SELECT ttrss_entries.title, + ttrss_feeds.title AS feed_title, + COALESCE(ttrss_feed_categories.title, '" . __('Uncategorized') . "') AS cat_title, + date_updated, + ttrss_user_entries.ref_id, + link, + score, + content, + " . SUBSTRING_FOR_DATE . "(last_updated,1,19) AS last_updated + FROM + ttrss_user_entries,ttrss_entries,ttrss_feeds + LEFT JOIN + ttrss_feed_categories ON (cat_id = ttrss_feed_categories.id) + WHERE + ref_id = ttrss_entries.id AND feed_id = ttrss_feeds.id + AND include_in_digest = true + AND $interval_qpart + AND ttrss_user_entries.owner_uid = :user_id + AND unread = true + AND score >= 0 + ORDER BY ttrss_feed_categories.title, ttrss_feeds.title, score DESC, date_updated DESC + LIMIT :limit"); + $sth->bindParam(':user_id', intval($user_id, 10), PDO::PARAM_INT); + $sth->bindParam(':limit', intval($limit, 10), PDO::PARAM_INT); + $sth->execute(); + + $headlines_count = 0; + $headlines = array(); + + while ($line = $sth->fetch()) { + array_push($headlines, $line); + $headlines_count++; + } + + for ($i = 0; $i < sizeof($headlines); $i++) { + + $line = $headlines[$i]; + + array_push($affected_ids, $line["ref_id"]); + + $updated = make_local_datetime($line['last_updated'], false, + $user_id); + + if (get_pref('ENABLE_FEED_CATS', $user_id)) { + $line['feed_title'] = $line['cat_title'] . " / " . $line['feed_title']; + } + + $article_labels = Article::get_article_labels($line["ref_id"], $user_id); + $article_labels_formatted = ""; + + if (is_array($article_labels) && count($article_labels) > 0) { + $article_labels_formatted = implode(", ", array_map(function($a) { + return $a[1]; + }, $article_labels)); + } + + $tpl->setVariable('FEED_TITLE', $line["feed_title"]); + $tpl->setVariable('ARTICLE_TITLE', $line["title"]); + $tpl->setVariable('ARTICLE_LINK', $line["link"]); + $tpl->setVariable('ARTICLE_UPDATED', $updated); + $tpl->setVariable('ARTICLE_EXCERPT', + truncate_string(strip_tags($line["content"]), 300)); +// $tpl->setVariable('ARTICLE_CONTENT', +// strip_tags($article_content)); + $tpl->setVariable('ARTICLE_LABELS', $article_labels_formatted, true); + + $tpl->addBlock('article'); + + $tpl_t->setVariable('FEED_TITLE', $line["feed_title"]); + $tpl_t->setVariable('ARTICLE_TITLE', $line["title"]); + $tpl_t->setVariable('ARTICLE_LINK', $line["link"]); + $tpl_t->setVariable('ARTICLE_UPDATED', $updated); + $tpl_t->setVariable('ARTICLE_LABELS', $article_labels_formatted, true); + $tpl_t->setVariable('ARTICLE_EXCERPT', + truncate_string(strip_tags($line["excerpt"]), 300), true); + + $tpl_t->addBlock('article'); + + if ($headlines[$i]['feed_title'] != $headlines[$i + 1]['feed_title']) { + $tpl->addBlock('feed'); + $tpl_t->addBlock('feed'); + } + + } + + $tpl->addBlock('digest'); + $tpl->generateOutputToString($tmp); + + $tpl_t->addBlock('digest'); + $tpl_t->generateOutputToString($tmp_t); + + return array($tmp, $headlines_count, $affected_ids, $tmp_t); + } + +} diff --git a/classes/dlg.php b/classes/dlg.php new file mode 100644 index 0000000..4489af5 --- /dev/null +++ b/classes/dlg.php @@ -0,0 +1,206 @@ +param = $_REQUEST["param"]; + return true; + } + return false; + } + + function importOpml() { + print_notice("If you have imported labels and/or filters, you might need to reload preferences to see your new data."); + + print "
"; + + $opml = new Opml($_REQUEST); + + $opml->opml_import($_SESSION["uid"]); + + print "
"; + + print "
"; + print ""; + print "
"; + + print ""; + + //return; + } + + function pubOPMLUrl() { + $url_path = Opml::opml_publish_url(); + + print "
" . __("Your Public OPML URL is:") . "
"; + + print "
"; + + print "
"; + print "$url_path"; + print "
"; + + print "
"; + + print "
"; + + print " "; + + print ""; + + print "
"; + + //return; + } + + function explainError() { + print "
"; + + if ($this->param == 1) { + print __("Update daemon is enabled in configuration, but daemon process is not running, which prevents all feeds from updating. Please start the daemon process or contact instance owner."); + + $stamp = (int) file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp"); + + print "

" . __("Last update:") . " " . date("Y.m.d, G:i", $stamp); + + } + + if ($this->param == 3) { + print __("Update daemon is taking too long to perform a feed update. This could indicate a problem like crash or a hang. Please check the daemon process or contact instance owner."); + + $stamp = (int) file_get_contents(LOCK_DIRECTORY . "/update_daemon.stamp"); + + print "

" . __("Last update:") . " " . date("Y.m.d, G:i", $stamp); + + } + + print "

"; + + print "
"; + print ""; + print "
"; + + //return; + } + + function printTagCloud() { + print "
"; + + // from here: http://www.roscripts.com/Create_tag_cloud-71.html + + $sth = $this->pdo->prepare("SELECT tag_name, COUNT(post_int_id) AS count + FROM ttrss_tags WHERE owner_uid = ? + GROUP BY tag_name ORDER BY count DESC LIMIT 50"); + $sth->execute([$_SESSION['uid']]); + + $tags = array(); + + while ($line = $sth->fetch()) { + $tags[$line["tag_name"]] = $line["count"]; + } + + if(count($tags) == 0 ){ return; } + + ksort($tags); + + $max_size = 32; // max font size in pixels + $min_size = 11; // min font size in pixels + + // largest and smallest array values + $max_qty = max(array_values($tags)); + $min_qty = min(array_values($tags)); + + // find the range of values + $spread = $max_qty - $min_qty; + if ($spread == 0) { // we don't want to divide by zero + $spread = 1; + } + + // set the font-size increment + $step = ($max_size - $min_size) / ($spread); + + // loop through the tag array + foreach ($tags as $key => $value) { + // calculate font-size + // find the $value in excess of $min_qty + // multiply by the font-size increment ($size) + // and add the $min_size set above + $size = round($min_size + (($value - $min_qty) * $step)); + + $key_escaped = str_replace("'", "\\'", $key); + + echo "' . $key . ' '; + } + + + + print "
"; + + print "
"; + print ""; + print "
"; + + } + + function generatedFeed() { + + $this->params = explode(":", $this->param, 3); + $feed_id = $this->params[0]; + $is_cat = (bool) $this->params[1]; + + $key = get_feed_access_key($feed_id, $is_cat); + + $url_path = htmlspecialchars($this->params[2]) . "&key=" . $key; + + $feed_title = Feeds::getFeedTitle($feed_id, $is_cat); + + print "
".T_sprintf("%s can be accessed via the following secret URL:", $feed_title)."
"; + + print "
"; + print "
"; + print "$url_path"; + print "
"; + print "
"; + + print "
"; + + print ""; + + print " "; + + print ""; + + print "
"; + + //return; + } + + function defaultPasswordWarning() { + + print_warning(__("You are using default tt-rss password. Please change it in the Preferences (Personal data / Authentication).")); + + print "