Automated build for v0.01

This commit is contained in:
Fmstrat 2019-03-22 10:17:29 -04:00
commit 791b998489
2771 changed files with 222096 additions and 0 deletions

6
.editorconfig Normal file
View File

@ -0,0 +1,6 @@
[*]
end_of_line = lf
insert_final_newline = true
[*.php]
indent_style = tab

16
.gitignore vendored Normal file
View File

@ -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

44
.gitlab-ci.yml Normal file
View File

@ -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

12
CONTRIBUTING.md Normal file
View File

@ -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.

674
COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<http://www.gnu.org/licenses/>.
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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

117
PLUGINHOOKS.md Normal file
View File

@ -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<br>`$fetch_url` - URL of feed<br>`$owner_uid` - The user who owns the feed<br>`$feed` - Feed object<br>`$auth_login` - Auth user if requred<br>`$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<br> `$fetch_url` - URL of feed<br> `$owner_uid` - The user who owns the feed<br> `$feed` - Feed object<br> `0` - Unknown<br> `$auth_login` - Auth user if requred<br> `$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<br> `$fetch_url` - URL of feed<br> `$owner_uid` - The user who owns the feed<br> `$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<br> `$owner_uid` - The user who owns the feed<br> `$article` - Object containing an article<br> `$matched_filters` - Array of matched filters<br> `$matched_rules` - Array of matched rules<br> `$article_filters` - All filters | None |
| `HOOK_ARTICLE_FILTER_ACTION` | Used to update an article as filter actions are applied. | `$article` - Object containing an article<br> `$pfaction` - The filter action<br> `$matched_rules` - Array of matched rules<br> `$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<br> `$excerpt_length` - The length of content to display<br> `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<br> `$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<br> `$cat_view` - The category view<br> `$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.<br> `250` - Unknown (Character length?)<br> `false` - Unknown | `$line` |
| `HOOK_ARTICLE_EXPORT_FEED` | Runs after HOOK_QUERY_HEADLINES but only for public feeds. | `$line` - Array of lines of HTML code)<br> `$feed` - Object with feed info and the array of articles (populates each article after this runs)<br> `$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<br> `$line` - Object of article data.<br> `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<br> `$result` - Lines of entries<br> `$id` - Unknown<br> `$always_display_enclosures` - Unknown<br> `$article_content` - Content of the article<br> `$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<br> `$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<br> `$url` - URL of the feed<br> `$auth_login` - Auth user if requred<br> `$auth_pass` - Auth password if requred | `$content` |
| `HOOK_UNSUBSCRIBE_FEED` | Used to run code when a feed is unsubscribed. | `$id` - The feed id<br> `$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<br> `$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<br> `$site_url` - Unknown <br> `$allowed_elements` - HTML ellements allowed in fields<br> `$disallowed_attributes` - HTML elements not allowed in fields<br> `$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<br> `$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 |

89
README.md Normal file
View File

@ -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.
<div align="center">
<img src="https://raw.githubusercontent.com/Fmstrat/agriget/master/screenshots/1.png" width="250">
<img src="https://raw.githubusercontent.com/Fmstrat/agriget/master/screenshots/2.png" width="250">
<img src="https://raw.githubusercontent.com/Fmstrat/agriget/master/screenshots/3.png" width="250">
<br>
<img src="https://raw.githubusercontent.com/Fmstrat/agriget/master/screenshots/4.png" width="250">
<img src="https://raw.githubusercontent.com/Fmstrat/agriget/master/screenshots/5.png" width="250">
<img src="https://raw.githubusercontent.com/Fmstrat/agriget/master/screenshots/6.png" width="250">
<br>
</div>
**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 <http://www.gnu.org/licenses/>.
- 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

91
api/index.php Normal file
View File

@ -0,0 +1,91 @@
<?php
error_reporting(E_ERROR | E_PARSE);
require_once "../data/config.php";
set_include_path(dirname(__FILE__) . PATH_SEPARATOR .
dirname(dirname(__FILE__)) . PATH_SEPARATOR .
dirname(dirname(__FILE__)) . "/include" . PATH_SEPARATOR .
get_include_path());
chdir("..");
define('TTRSS_SESSION_NAME', 'ttrss_api_sid');
define('NO_SESSION_AUTOSTART', true);
require_once "autoload.php";
require_once "db.php";
require_once "db-prefs.php";
require_once "functions.php";
require_once "sessions.php";
ini_set('session.use_cookies', 0);
ini_set("session.gc_maxlifetime", 86400);
define('AUTH_DISABLE_OTP', true);
if (defined('ENABLE_GZIP_OUTPUT') && ENABLE_GZIP_OUTPUT &&
function_exists("ob_gzhandler")) {
ob_start("ob_gzhandler");
} else {
ob_start();
}
$input = file_get_contents("php://input");
if (defined('_API_DEBUG_HTTP_ENABLED') && _API_DEBUG_HTTP_ENABLED) {
// Override $_REQUEST with JSON-encoded data if available
// fallback on HTTP parameters
if ($input) {
$input = json_decode($input, true);
if ($input) $_REQUEST = $input;
}
} else {
// Accept JSON only
$input = json_decode($input, true);
$_REQUEST = $input;
}
if ($_REQUEST["sid"]) {
session_id($_REQUEST["sid"]);
@session_start();
} else if (defined('_API_DEBUG_HTTP_ENABLED')) {
@session_start();
}
startup_gettext();
if (!init_plugins()) return;
if ($_SESSION["uid"]) {
if (!validate_session()) {
header("Content-Type: text/json");
print json_encode(array("seq" => -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();

51
atom-to-html.xsl Normal file
View File

@ -0,0 +1,51 @@
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/atom:feed">
<html>
<head>
<title><xsl:value-of select="atom:title"/></title>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<script language="javascript" src="lib/xsl_mop-up.js"></script>
</head>
<body onload="go_decoding()" class="ttrss_utility">
<div id="cometestme" style="display:none;">
<xsl:text disable-output-escaping="yes">&amp;amp;</xsl:text>
</div>
<div class="rss">
<h1><xsl:value-of select="atom:title"/></h1>
<p class="description">This feed has been exported from
<a target="_new" class="extlink" href="http://tt-rss.org">Tiny Tiny RSS</a>.
It contains the following items:</p>
<xsl:for-each select="atom:entry">
<h2><a target="_new" href="{atom:link/@href}"><xsl:value-of select="atom:title"/></a></h2>
<div name="decodeme" class="content">
<xsl:value-of select="atom:content" disable-output-escaping="yes"/>
</div>
<xsl:if test="enclosure">
<p><a href="{enclosure/@url}">Extra...</a></p>
</xsl:if>
</xsl:for-each>
</div>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

147
backend.php Normal file
View File

@ -0,0 +1,147 @@
<?php
set_include_path(dirname(__FILE__) ."/include" . PATH_SEPARATOR .
get_include_path());
/* remove ill effects of magic quotes */
if (get_magic_quotes_gpc()) {
function stripslashes_deep($value) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value) : stripslashes($value);
return $value;
}
$_POST = array_map('stripslashes_deep', $_POST);
$_GET = array_map('stripslashes_deep', $_GET);
$_COOKIE = array_map('stripslashes_deep', $_COOKIE);
$_REQUEST = array_map('stripslashes_deep', $_REQUEST);
}
$op = $_REQUEST["op"];
@$method = $_REQUEST['subop'] ? $_REQUEST['subop'] : $_REQUEST["method"];
if (!$method)
$method = 'index';
else
$method = strtolower($method);
/* Public calls compatibility shim */
$public_calls = array("globalUpdateFeeds", "rss", "getUnread", "getProfiles", "share",
"fbexport", "logout", "pubsub");
if (array_search($op, $public_calls) !== false) {
header("Location: public.php?" . $_SERVER['QUERY_STRING']);
return;
}
@$csrf_token = $_REQUEST['csrf_token'];
require_once "autoload.php";
require_once "sessions.php";
require_once "functions.php";
require_once "data/config.php";
require_once "db.php";
require_once "db-prefs.php";
startup_gettext();
$script_started = microtime(true);
if (!init_plugins()) return;
header("Content-Type: text/json; charset=utf-8");
if (ENABLE_GZIP_OUTPUT && function_exists("ob_gzhandler")) {
ob_start("ob_gzhandler");
}
if (SINGLE_USER_MODE) {
authenticate_user( "admin", null);
}
if ($_SESSION["uid"]) {
if (!validate_session()) {
header("Content-Type: text/json");
print error_json(6);
return;
}
load_user_plugins( $_SESSION["uid"]);
}
$purge_intervals = array(
0 => __("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);
?>

0
cache/export/.empty vendored Executable file
View File

0
cache/feeds/.empty vendored Normal file
View File

0
cache/images/.empty vendored Executable file
View File

0
cache/upload/.empty vendored Normal file
View File

888
classes/api.php Executable file
View File

@ -0,0 +1,888 @@
<?php
class API extends Handler {
const API_LEVEL = 14;
const STATUS_OK = 0;
const STATUS_ERR = 1;
private $seq;
static function param_to_bool($p) {
return $p && ($p !== "f" && $p !== "false");
}
function before($method) {
if (parent::before($method)) {
header("Content-Type: text/json");
if (!$_SESSION["uid"] && $method != "login" && $method != "isloggedin") {
$this->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;
}
}

788
classes/article.php Executable file
View File

@ -0,0 +1,788 @@
<?php
class Article extends Handler_Protected {
function csrf_ignore($method) {
$csrf_ignored = array("redirect", "editarticletags");
return array_search($method, $csrf_ignored) !== false;
}
function redirect() {
$id = clean($_REQUEST['id']);
$sth = $this->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 '<link rel="stylesheet" type="text/css" href="css/default.css"/>';
}
$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 "<header class='horizontal'>" . __("Tags for this article (separated by commas):")."</header>";
print "<section>";
print "<textarea dojoType='dijit.form.SimpleTextarea' rows='4'
style='height : 100px; font-size : 12px; width : 98%' id='tags_str'
name='tags_str'>$tags_str</textarea>
<div class='autocomplete' id='tags_choices'
style='display:none'></div>";
print "</section>";
print "<footer>";
print "<button dojoType='dijit.form.Button'
type='submit' class='alt-primary' onclick=\"dijit.byId('editTagsDlg').execute()\">".__('Save')."</button> ";
print "<button dojoType='dijit.form.Button'
onclick=\"dijit.byId('editTagsDlg').hide()\">".__('Cancel')."</button>";
print "</footer>";
}
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 "<!-- $id : $int_id : $tag -->";
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 "<ul>";
while ($line = $sth->fetch()) {
print "<li>" . $line["tag_name"] . "</li>";
}
print "</ul>";
}
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 .= " <a target=\"_blank\" href=\"" . htmlspecialchars($url) . "\" rel=\"noopener noreferrer\">" .
# $filename . " (" . $ctype . ")" . "</a>";
$entry = "<div onclick=\"popupOpenUrl('".htmlspecialchars($url)."')\"
dojoType=\"dijit.MenuItem\">$filename ($ctype)</div>";
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("/<img/i", $article_content)) {
foreach ($entries as $entry) {
foreach (PluginHost::getInstance()->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 .= "<p><img
alt=\"".htmlspecialchars($entry["filename"])."\"
src=\"" .htmlspecialchars($entry["url"]) . "\"
" . $encsize . " /></p>";
} else {
$rv .= "<p><a target=\"_blank\" rel=\"noopener noreferrer\"
href=\"".htmlspecialchars($entry["url"])."\"
>" .htmlspecialchars($entry["url"]) . "</a></p>";
}
if ($entry['title']) {
$rv.= "<div class=\"enclosure_title\">${entry['title']}</div>";
}
}
}
}
}
}
if (count($entries_inline) > 0) {
//$rv .= "<hr clear='both'/>";
foreach ($entries_inline as $entry) { $rv .= $entry; };
$rv .= "<br clear='both'/>";
}
$rv .= "<div class=\"attachments\" dojoType=\"dijit.form.DropDownButton\">".
"<span>" . __('Attachments')."</span>";
$rv .= "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
foreach ($entries as $entry) {
if ($entry["title"])
$title = " &mdash; " . truncate_string($entry["title"], 30);
else
$title = "";
if ($entry["filename"])
$filename = truncate_middle(htmlspecialchars($entry["filename"]), 60);
else
$filename = "";
$rv .= "<div onclick='popupOpenUrl(\"".htmlspecialchars($entry["url"])."\")'
dojoType=\"dijit.MenuItem\">".$filename . $title."</div>";
};
$rv .= "</div>";
$rv .= "</div>";
}
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 .= "<a class=\"tag\" href=\"#\" onclick=\"Feeds.open({feed:'".$tags[$i]."'})\">" . $tags[$i] . "</a>, ";
}
$tags_str = mb_substr($tags_str, 0, mb_strlen($tags_str)-2);
if (count($tags) > $maxtags)
$tags_str .= ", &hellip;";
return $tags_str;
}
}
static function format_article_labels($labels) {
if (!is_array($labels)) return '';
$labels_str = "";
foreach ($labels as $l) {
$labels_str .= sprintf("<div class='label'
style='color : %s; background-color : %s'>%s</div>",
$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 "<div class='article-note $note_class'>
<i class='material-icons'>note</i>
<div $onclick class='body'>$note</div>
</div>";
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;
}
}

62
classes/auth/base.php Normal file
View File

@ -0,0 +1,62 @@
<?php
class Auth_Base {
private $pdo;
function __construct() {
$this->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;
}
}
}

163
classes/backend.php Normal file
View File

@ -0,0 +1,163 @@
<?php
class Backend extends Handler {
function loading() {
header("Content-type: text/html");
print __("Loading, please wait...") . " " .
"<img src='images/indicator_tiny.gif'>";
}
function digestTest() {
if (isset($_SESSION['uid'])) {
header("Content-type: text/html");
$rv = Digest::prepare_headlines_digest($_SESSION['uid'], 1, 1000);
print "<h1>HTML</h1>";
print $rv[0];
print "<h1>Plain text</h1>";
print "<pre>".$rv[3]."</pre>";
} 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 "<ul class='panel panel-scrollable hotkeys-help' style='height : 300px'>";
print "<h2>" . __("Keyboard Shortcuts") . "</h2>";
foreach ($info as $section => $hotkeys) {
print "<li><hr></li>";
print "<li><h3>" . $section . "</h3></li>";
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 "<li>";
print "<div class='hk'><code>$sequence</code></div>";
print "<div class='desc'>$description</div>";
print "</li>";
}
}
}
}
print "</ul>";
}
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 "<ul class='panel panel-scrollable hotkeys-help' style='height : 300px'>";
$cur_section = "";
foreach ($info as $section => $hotkeys) {
if ($cur_section) print "<li>&nbsp;</li>";
print "<li><h3>" . $section . "</h3></li>";
$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 "<li>";
print "<div class='hk'><code>$sequence</code></div>";
print "<div class='desc'>$description</div>";
print "</li>";
}
}
}
}
print "</ul>";
}
print "<footer class='text-center'>";
print "<button dojoType='dijit.form.Button'
onclick=\"return dijit.byId('helpDlg').hide()\">".__('Close this window')."</button>";
print "</footer>";
}
}

211
classes/ccache.php Normal file
View File

@ -0,0 +1,211 @@
<?php
class CCache {
static function zero_all($owner_uid) {
$pdo = Db::pdo();
$sth = $pdo->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;
}
}

216
classes/counters.php Normal file
View File

@ -0,0 +1,216 @@
<?php
class Counters {
static function getAllCounters() {
$data = Counters::getGlobalCounters();
$data = array_merge($data, Counters::getVirtCounters());
$data = array_merge($data, Counters::getLabelCounters());
$data = array_merge($data, Counters::getFeedCounters());
$data = array_merge($data, Counters::getCategoryCounters());
return $data;
}
static function getCategoryCounters() {
$ret_arr = array();
/* Labels category */
$cv = array("id" => -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;
}
}

116
classes/db.php Executable file
View File

@ -0,0 +1,116 @@
<?php
class Db
{
/* @var Db $instance */
private static $instance;
/* @var IDb $adapter */
private $adapter;
private $link;
/* @var PDO $pdo */
private $pdo;
private function __clone() {
//
}
private function legacy_connect() {
user_error("Legacy connect requested to " . DB_TYPE, E_USER_NOTICE);
$er = error_reporting(E_ALL);
switch (DB_TYPE) {
case "mysql":
$this->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 "<pre>Exception while creating PDO object:" . $e->getMessage() . "</pre>";
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;
}
}

85
classes/db/mysqli.php Normal file
View File

@ -0,0 +1,85 @@
<?php
class Db_Mysqli implements IDb {
private $link;
private $last_error;
function connect($host, $user, $pass, $db, $port) {
if ($port)
$this->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;
}
}

91
classes/db/pgsql.php Normal file
View File

@ -0,0 +1,91 @@
<?php
class Db_Pgsql implements IDb {
private $link;
private $last_error;
function connect($host, $user, $pass, $db, $port) {
$string = "dbname=$db user=$user";
if ($pass) {
$string .= " password=$pass";
}
if ($host) {
$string .= " host=$host";
}
if (is_numeric($port) && $port > 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;
}
}

171
classes/db/prefs.php Normal file
View File

@ -0,0 +1,171 @@
<?php
class Db_Prefs {
private $pdo;
private static $instance;
private $cache;
function __construct() {
$this->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;
}
}
}
}

83
classes/dbupdater.php Normal file
View File

@ -0,0 +1,83 @@
<?php
class DbUpdater {
private $pdo;
private $db_type;
private $need_version;
function __construct($pdo, $db_type, $need_version) {
$this->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 "<pre>$line</pre>";
else
Debug::log("> $line");
try {
$this->pdo->query($line); // PDO returns errors as exceptions now
} catch (PDOException $e) {
if ($html_output) {
print "<div class='text-error'>Error: " . $e->getMessage() . "</div>";
} 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;
}
}
}

86
classes/debug.php Normal file
View File

@ -0,0 +1,86 @@
<?php
class Debug {
public static $LOG_DISABLED = -1;
public static $LOG_NORMAL = 0;
public static $LOG_VERBOSE = 1;
public static $LOG_EXTENDED = 2;
private static $enabled = false;
private static $quiet = false;
private static $logfile = false;
private static $loglevel = 0;
public static function set_logfile($logfile) {
Debug::$logfile = $logfile;
}
public static function enabled() {
return Debug::$enabled;
}
public static function set_enabled($enable) {
Debug::$enabled = $enable;
}
public static function set_quiet($quiet) {
Debug::$quiet = $quiet;
}
public static function set_loglevel($level) {
Debug::$loglevel = $level;
}
public static function get_loglevel() {
return Debug::$loglevel;
}
public static function log($message, $level = 0) {
if (!Debug::$enabled || Debug::$loglevel < $level) return false;
$ts = strftime("%H:%M:%S", time());
if (function_exists('posix_getpid')) {
$ts = "$ts/" . posix_getpid();
}
if (Debug::$logfile) {
$fp = fopen(Debug::$logfile, 'a+');
if ($fp) {
$locked = false;
if (function_exists("flock")) {
$tries = 0;
// try to lock logfile for writing
while ($tries < 5 && !$locked = flock($fp, LOCK_EX | LOCK_NB)) {
sleep(1);
++$tries;
}
if (!$locked) {
fclose($fp);
user_error("Unable to lock debugging log file: " . Debug::$logfile, E_USER_WARNING);
return;
}
}
fputs($fp, "[$ts] $message\n");
if (function_exists("flock")) {
flock($fp, LOCK_UN);
}
fclose($fp);
if (Debug::$quiet)
return;
} else {
user_error("Unable to open debugging log file: " . Debug::$logfile, E_USER_WARNING);
}
}
print "[$ts] $message\n";
}
}

216
classes/digest.php Normal file
View File

@ -0,0 +1,216 @@
<?php
class Digest
{
/**
* Send by mail a digest of last articles.
*
* @param mixed $link The database connection.
* @param integer $limit The maximum number of articles by digest.
* @return boolean Return false if digests are not enabled.
*/
static function send_headlines_digests() {
$user_limit = 15; // amount of users to process (e.g. emails to send out)
$limit = 1000; // maximum amount of headlines to include
Debug::log("Sending digests, batch of max $user_limit users, headline limit = $limit");
if (DB_TYPE == "pgsql") {
$interval_qpart = "last_digest_sent < NOW() - INTERVAL '1 days'";
} else if (DB_TYPE == "mysql") {
$interval_qpart = "last_digest_sent < DATE_SUB(NOW(), INTERVAL 1 DAY)";
}
$pdo = Db::pdo();
$res = $pdo->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);
}
}

206
classes/dlg.php Normal file
View File

@ -0,0 +1,206 @@
<?php
class Dlg extends Handler_Protected {
private $param;
private $params;
function before($method) {
if (parent::before($method)) {
header("Content-Type: text/html"); # required for iframe
$this->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 "<div class='panel panel-scrollable'>";
$opml = new Opml($_REQUEST);
$opml->opml_import($_SESSION["uid"]);
print "</div>";
print "<footer class='text-center'>";
print "<button dojoType='dijit.form.Button'
onclick=\"dijit.byId('opmlImportDlg').execute()\">".
__('Close this window')."</button>";
print "</footer>";
print "</div>";
//return;
}
function pubOPMLUrl() {
$url_path = Opml::opml_publish_url();
print "<header>" . __("Your Public OPML URL is:") . "</header>";
print "<section>";
print "<div class='panel text-center'>";
print "<a id='pub_opml_url' href='$url_path' target='_blank'>$url_path</a>";
print "</div>";
print "</section>";
print "<footer class='text-center'>";
print "<button dojoType='dijit.form.Button' onclick=\"return Helpers.OPML.changeKey()\">".
__('Generate new URL')."</button> ";
print "<button dojoType='dijit.form.Button' onclick=\"return CommonDialogs.closeInfoBox()\">".
__('Close this window')."</button>";
print "</footer>";
//return;
}
function explainError() {
print "<div class=\"errorExplained\">";
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 "<p>" . __("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 "<p>" . __("Last update:") . " " . date("Y.m.d, G:i", $stamp);
}
print "</div>";
print "<footer class='text-center'>";
print "<button onclick=\"return CommonDialogs.closeInfoBox()\">".
__('Close this window')."</button>";
print "</footer>";
//return;
}
function printTagCloud() {
print "<div class='panel text-center'>";
// 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 "<a href=\"#\" onclick=\"Feeds.open({feed:'$key_escaped'}) \" style=\"font-size: " .
$size . "px\" title=\"$value articles tagged with " .
$key . '">' . $key . '</a> ';
}
print "</div>";
print "<footer class='text-center'>";
print "<button dojoType='dijit.form.Button'
onclick=\"return CommonDialogs.closeInfoBox()\">".
__('Close this window')."</button>";
print "</footer>";
}
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 "<header>".T_sprintf("%s can be accessed via the following secret URL:", $feed_title)."</header>";
print "<section>";
print "<div class='panel text-center'>";
print "<a id='gen_feed_url' href='$url_path' target='_blank'>$url_path</a>";
print "</div>";
print "</section>";
print "<footer>";
print "<button dojoType='dijit.form.Button' style='float : left' class='alt-info' onclick='window.open(\"https://tt-rss.org/wiki/GeneratedFeeds\")'>
<i class='material-icons'>help</i> ".__("More info...")."</button>";
print "<button dojoType='dijit.form.Button' onclick=\"return CommonDialogs.genUrlChangeKey('$feed_id', '$is_cat')\">".
__('Generate new URL')."</button> ";
print "<button dojoType='dijit.form.Button' onclick=\"return CommonDialogs.closeInfoBox()\">".
__('Close this window')."</button>";
print "</footer>";
//return;
}
function defaultPasswordWarning() {
print_warning(__("You are using default tt-rss password. Please change it in the Preferences (Personal data / Authentication)."));
print "<footer class='text-center'>";
print "<button dojoType='dijit.form.Button' onclick=\"document.location.href = 'prefs.php'\">".
__('Open Preferences')."</button> ";
print "<button dojoType='dijit.form.Button'
onclick=\"return CommonDialogs.closeInfoBox()\">".
__('Close this window')."</button>";
print "</footeer>";
}
}

10
classes/feedenclosure.php Normal file
View File

@ -0,0 +1,10 @@
<?php
class FeedEnclosure {
public $link;
public $type;
public $length;
public $title;
public $height;
public $width;
}

16
classes/feeditem.php Normal file
View File

@ -0,0 +1,16 @@
<?php
abstract class FeedItem {
abstract function get_id();
abstract function get_date();
abstract function get_link();
abstract function get_title();
abstract function get_description();
abstract function get_content();
abstract function get_comments_url();
abstract function get_comments_count();
abstract function get_categories();
abstract function get_enclosures();
abstract function get_author();
abstract function get_language();
}

160
classes/feeditem/atom.php Executable file
View File

@ -0,0 +1,160 @@
<?php
class FeedItem_Atom extends FeedItem_Common {
const NS_XML = "http://www.w3.org/XML/1998/namespace";
function get_id() {
$id = $this->elem->getElementsByTagName("id")->item(0);
if ($id) {
return $id->nodeValue;
} else {
return clean($this->get_link());
}
}
function get_date() {
$updated = $this->elem->getElementsByTagName("updated")->item(0);
if ($updated) {
return strtotime($updated->nodeValue);
}
$published = $this->elem->getElementsByTagName("published")->item(0);
if ($published) {
return strtotime($published->nodeValue);
}
$date = $this->xpath->query("dc:date", $this->elem)->item(0);
if ($date) {
return strtotime($date->nodeValue);
}
}
function get_link() {
$links = $this->elem->getElementsByTagName("link");
foreach ($links as $link) {
if ($link && $link->hasAttribute("href") &&
(!$link->hasAttribute("rel")
|| $link->getAttribute("rel") == "alternate"
|| $link->getAttribute("rel") == "standout")) {
$base = $this->xpath->evaluate("string(ancestor-or-self::*[@xml:base][1]/@xml:base)", $link);
if ($base)
return rewrite_relative_url($base, clean(trim($link->getAttribute("href"))));
else
return clean(trim($link->getAttribute("href")));
}
}
}
function get_title() {
$title = $this->elem->getElementsByTagName("title")->item(0);
if ($title) {
return clean(trim($title->nodeValue));
}
}
function get_content() {
$content = $this->elem->getElementsByTagName("content")->item(0);
if ($content) {
if ($content->hasAttribute('type')) {
if ($content->getAttribute('type') == 'xhtml') {
for ($i = 0; $i < $content->childNodes->length; $i++) {
$child = $content->childNodes->item($i);
if ($child->hasChildNodes()) {
return $this->doc->saveHTML($child);
}
}
}
}
return $this->subtree_or_text($content);
}
}
function get_description() {
$content = $this->elem->getElementsByTagName("summary")->item(0);
if ($content) {
if ($content->hasAttribute('type')) {
if ($content->getAttribute('type') == 'xhtml') {
for ($i = 0; $i < $content->childNodes->length; $i++) {
$child = $content->childNodes->item($i);
if ($child->hasChildNodes()) {
return $this->doc->saveHTML($child);
}
}
}
}
return $this->subtree_or_text($content);
}
}
function get_categories() {
$categories = $this->elem->getElementsByTagName("category");
$cats = array();
foreach ($categories as $cat) {
if ($cat->hasAttribute("term"))
array_push($cats, trim($cat->getAttribute("term")));
}
$categories = $this->xpath->query("dc:subject", $this->elem);
foreach ($categories as $cat) {
array_push($cats, clean(trim($cat->nodeValue)));
}
return $cats;
}
function get_enclosures() {
$links = $this->elem->getElementsByTagName("link");
$encs = array();
foreach ($links as $link) {
if ($link && $link->hasAttribute("href") && $link->hasAttribute("rel")) {
if ($link->getAttribute("rel") == "enclosure") {
$enc = new FeedEnclosure();
$enc->type = clean($link->getAttribute("type"));
$enc->link = clean($link->getAttribute("href"));
$enc->length = clean($link->getAttribute("length"));
array_push($encs, $enc);
}
}
}
$encs = array_merge($encs, parent::get_enclosures());
return $encs;
}
function get_language() {
$lang = $this->elem->getAttributeNS(self::NS_XML, "lang");
if (!empty($lang)) {
return clean($lang);
} else {
// Fall back to the language declared on the feed, if any.
foreach ($this->doc->childNodes as $child) {
if (method_exists($child, "getAttributeNS")) {
return clean($child->getAttributeNS(self::NS_XML, "lang"));
}
}
}
}
}

162
classes/feeditem/common.php Executable file
View File

@ -0,0 +1,162 @@
<?php
abstract class FeedItem_Common extends FeedItem {
protected $elem;
protected $xpath;
protected $doc;
function __construct($elem, $doc, $xpath) {
$this->elem = $elem;
$this->xpath = $xpath;
$this->doc = $doc;
try {
$source = $elem->getElementsByTagName("source")->item(0);
// we don't need <source> element
if ($source)
$elem->removeChild($source);
} catch (DOMException $e) {
//
}
}
function get_element() {
return $this->elem;
}
function get_author() {
$author = $this->elem->getElementsByTagName("author")->item(0);
if ($author) {
$name = $author->getElementsByTagName("name")->item(0);
if ($name) return clean($name->nodeValue);
$email = $author->getElementsByTagName("email")->item(0);
if ($email) return clean($email->nodeValue);
if ($author->nodeValue)
return clean($author->nodeValue);
}
$author = $this->xpath->query("dc:creator", $this->elem)->item(0);
if ($author) {
return clean($author->nodeValue);
}
}
function get_comments_url() {
//RSS only. Use a query here to avoid namespace clashes (e.g. with slash).
//might give a wrong result if a default namespace was declared (possible with XPath 2.0)
$com_url = $this->xpath->query("comments", $this->elem)->item(0);
if ($com_url)
return clean($com_url->nodeValue);
//Atom Threading Extension (RFC 4685) stuff. Could be used in RSS feeds, so it's in common.
//'text/html' for type is too restrictive?
$com_url = $this->xpath->query("atom:link[@rel='replies' and contains(@type,'text/html')]/@href", $this->elem)->item(0);
if ($com_url)
return clean($com_url->nodeValue);
}
function get_comments_count() {
//also query for ATE stuff here
$query = "slash:comments|thread:total|atom:link[@rel='replies']/@thread:count";
$comments = $this->xpath->query($query, $this->elem)->item(0);
if ($comments) {
return clean($comments->nodeValue);
}
}
// this is common for both Atom and RSS types and deals with various media: elements
function get_enclosures() {
$encs = [];
$enclosures = $this->xpath->query("media:content", $this->elem);
foreach ($enclosures as $enclosure) {
$enc = new FeedEnclosure();
$enc->type = clean($enclosure->getAttribute("type"));
$enc->link = clean($enclosure->getAttribute("url"));
$enc->length = clean($enclosure->getAttribute("length"));
$enc->height = clean($enclosure->getAttribute("height"));
$enc->width = clean($enclosure->getAttribute("width"));
$medium = clean($enclosure->getAttribute("medium"));
if (!$enc->type && $medium) {
$enc->type = strtolower("$medium/generic");
}
$desc = $this->xpath->query("media:description", $enclosure)->item(0);
if ($desc) $enc->title = clean($desc->nodeValue);
array_push($encs, $enc);
}
$enclosures = $this->xpath->query("media:group", $this->elem);
foreach ($enclosures as $enclosure) {
$enc = new FeedEnclosure();
$content = $this->xpath->query("media:content", $enclosure)->item(0);
if ($content) {
$enc->type = clean($content->getAttribute("type"));
$enc->link = clean($content->getAttribute("url"));
$enc->length = clean($content->getAttribute("length"));
$enc->height = clean($content->getAttribute("height"));
$enc->width = clean($content->getAttribute("width"));
$medium = clean($content->getAttribute("medium"));
if (!$enc->type && $medium) {
$enc->type = strtolower("$medium/generic");
}
$desc = $this->xpath->query("media:description", $content)->item(0);
if ($desc) {
$enc->title = clean($desc->nodeValue);
} else {
$desc = $this->xpath->query("media:description", $enclosure)->item(0);
if ($desc) $enc->title = clean($desc->nodeValue);
}
array_push($encs, $enc);
}
}
$enclosures = $this->xpath->query("media:thumbnail", $this->elem);
foreach ($enclosures as $enclosure) {
$enc = new FeedEnclosure();
$enc->type = "image/generic";
$enc->link = clean($enclosure->getAttribute("url"));
$enc->height = clean($enclosure->getAttribute("height"));
$enc->width = clean($enclosure->getAttribute("width"));
array_push($encs, $enc);
}
return $encs;
}
function count_children($node) {
return $node->getElementsByTagName("*")->length;
}
function subtree_or_text($node) {
if ($this->count_children($node) == 0) {
return $node->nodeValue;
} else {
return $node->c14n();
}
}
}

147
classes/feeditem/rss.php Executable file
View File

@ -0,0 +1,147 @@
<?php
class FeedItem_RSS extends FeedItem_Common {
function get_id() {
$id = $this->elem->getElementsByTagName("guid")->item(0);
if ($id) {
return clean($id->nodeValue);
} else {
return clean($this->get_link());
}
}
function get_date() {
$pubDate = $this->elem->getElementsByTagName("pubDate")->item(0);
if ($pubDate) {
return strtotime($pubDate->nodeValue);
}
$date = $this->xpath->query("dc:date", $this->elem)->item(0);
if ($date) {
return strtotime($date->nodeValue);
}
}
function get_link() {
$links = $this->xpath->query("atom:link", $this->elem);
foreach ($links as $link) {
if ($link && $link->hasAttribute("href") &&
(!$link->hasAttribute("rel")
|| $link->getAttribute("rel") == "alternate"
|| $link->getAttribute("rel") == "standout")) {
return clean(trim($link->getAttribute("href")));
}
}
$link = $this->elem->getElementsByTagName("guid")->item(0);
if ($link && $link->hasAttributes() && $link->getAttribute("isPermaLink") == "true") {
return clean(trim($link->nodeValue));
}
$link = $this->elem->getElementsByTagName("link")->item(0);
if ($link) {
return clean(trim($link->nodeValue));
}
}
function get_title() {
$title = $this->xpath->query("title", $this->elem)->item(0);
if ($title) {
return clean(trim($title->nodeValue));
}
// if the document has a default namespace then querying for
// title would fail because of reasons so let's try the old way
$title = $this->elem->getElementsByTagName("title")->item(0);
if ($title) {
return clean(trim($title->nodeValue));
}
}
function get_content() {
$contentA = $this->xpath->query("content:encoded", $this->elem)->item(0);
$contentB = $this->elem->getElementsByTagName("description")->item(0);
if ($contentA && !$contentB) {
return $this->subtree_or_text($contentA);
}
if ($contentB && !$contentA) {
return $this->subtree_or_text($contentB);
}
if ($contentA && $contentB) {
$resultA = $this->subtree_or_text($contentA);
$resultB = $this->subtree_or_text($contentB);
return mb_strlen($resultA) > mb_strlen($resultB) ? $resultA : $resultB;
}
}
function get_description() {
$summary = $this->elem->getElementsByTagName("description")->item(0);
if ($summary) {
return $summary->nodeValue;
}
}
function get_categories() {
$categories = $this->elem->getElementsByTagName("category");
$cats = array();
foreach ($categories as $cat) {
array_push($cats, trim($cat->nodeValue));
}
$categories = $this->xpath->query("dc:subject", $this->elem);
foreach ($categories as $cat) {
array_push($cats, clean(trim($cat->nodeValue)));
}
return $cats;
}
function get_enclosures() {
$enclosures = $this->elem->getElementsByTagName("enclosure");
$encs = array();
foreach ($enclosures as $enclosure) {
$enc = new FeedEnclosure();
$enc->type = clean($enclosure->getAttribute("type"));
$enc->link = clean($enclosure->getAttribute("url"));
$enc->length = clean($enclosure->getAttribute("length"));
$enc->height = clean($enclosure->getAttribute("height"));
$enc->width = clean($enclosure->getAttribute("width"));
array_push($encs, $enc);
}
$encs = array_merge($encs, parent::get_enclosures());
return $encs;
}
function get_language() {
$languages = $this->doc->getElementsByTagName('language');
if (count($languages) == 0) {
return "";
}
return clean($languages[0]->textContent);
}
}

286
classes/feedparser.php Normal file
View File

@ -0,0 +1,286 @@
<?php
class FeedParser {
private $doc;
private $error;
private $libxml_errors = array();
private $items;
private $link;
private $title;
private $type;
private $xpath;
const FEED_RDF = 0;
const FEED_RSS = 1;
const FEED_ATOM = 2;
function normalize_encoding($data) {
if (preg_match('/^(<\?xml[\t\n\r ].*?encoding[\t\n\r ]*=[\t\n\r ]*["\'])(.+?)(["\'].*?\?>)/s', $data, $matches) === 1) {
$encoding = strtolower($matches[2]);
if (in_array($encoding, array_map('strtolower', mb_list_encodings())))
$data = mb_convert_encoding($data, 'UTF-8', $encoding);
$data = preg_replace('/^<\?xml[\t\n\r ].*?\?>/s', $matches[1] . "UTF-8" . $matches[3] , $data);
}
return $data;
}
function __construct($data) {
libxml_use_internal_errors(true);
libxml_clear_errors();
$this->doc = new DOMDocument();
$this->doc->loadXML($data);
mb_substitute_character("none");
$error = libxml_get_last_error();
// libxml compiled without iconv?
if ($error && $error->code == 32) {
$data = $this->normalize_encoding($data);
if ($data) {
libxml_clear_errors();
$this->doc = new DOMDocument();
$this->doc->loadXML($data);
$error = libxml_get_last_error();
}
}
// some terrible invalid unicode entity?
if ($error) {
foreach (libxml_get_errors() as $err) {
if ($err->code == 9) {
// if the source feed is not in utf8, next conversion will fail
$data = $this->normalize_encoding($data);
// remove dangling bytes
$data = mb_convert_encoding($data, 'UTF-8', 'UTF-8');
// apparently not all UTF-8 characters are valid for XML
$data = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', ' ', $data);
if ($data) {
libxml_clear_errors();
$this->doc = new DOMDocument();
$this->doc->loadXML($data);
$error = libxml_get_last_error();
}
break;
}
}
}
if ($error) {
foreach (libxml_get_errors() as $error) {
if ($error->level == LIBXML_ERR_FATAL) {
if(!isset($this->error)) //currently only the first error is reported
$this->error = $this->format_error($error);
$this->libxml_errors [] = $this->format_error($error);
}
}
}
libxml_clear_errors();
$this->items = array();
}
function init() {
$root = $this->doc->firstChild;
$xpath = new DOMXPath($this->doc);
$xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
$xpath->registerNamespace('atom03', 'http://purl.org/atom/ns#');
$xpath->registerNamespace('media', 'http://search.yahoo.com/mrss/');
$xpath->registerNamespace('rdf', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#');
$xpath->registerNamespace('slash', 'http://purl.org/rss/1.0/modules/slash/');
$xpath->registerNamespace('dc', 'http://purl.org/dc/elements/1.1/');
$xpath->registerNamespace('content', 'http://purl.org/rss/1.0/modules/content/');
$xpath->registerNamespace('thread', 'http://purl.org/syndication/thread/1.0');
$this->xpath = $xpath;
$root = $xpath->query("(//atom03:feed|//atom:feed|//channel|//rdf:rdf|//rdf:RDF)");
if ($root && $root->length > 0) {
$root = $root->item(0);
if ($root) {
switch (mb_strtolower($root->tagName)) {
case "rdf:rdf":
$this->type = $this::FEED_RDF;
break;
case "channel":
$this->type = $this::FEED_RSS;
break;
case "feed":
case "atom:feed":
$this->type = $this::FEED_ATOM;
break;
default:
if( !isset($this->error) ){
$this->error = "Unknown/unsupported feed type";
}
return;
}
}
switch ($this->type) {
case $this::FEED_ATOM:
$title = $xpath->query("//atom:feed/atom:title")->item(0);
if (!$title)
$title = $xpath->query("//atom03:feed/atom03:title")->item(0);
if ($title) {
$this->title = $title->nodeValue;
}
$link = $xpath->query("//atom:feed/atom:link[not(@rel)]")->item(0);
if (!$link)
$link = $xpath->query("//atom:feed/atom:link[@rel='alternate']")->item(0);
if (!$link)
$link = $xpath->query("//atom03:feed/atom03:link[not(@rel)]")->item(0);
if (!$link)
$link = $xpath->query("//atom03:feed/atom03:link[@rel='alternate']")->item(0);
if ($link && $link->hasAttributes()) {
$this->link = $link->getAttribute("href");
}
$articles = $xpath->query("//atom:entry");
if (!$articles || $articles->length == 0)
$articles = $xpath->query("//atom03:entry");
foreach ($articles as $article) {
array_push($this->items, new FeedItem_Atom($article, $this->doc, $this->xpath));
}
break;
case $this::FEED_RSS:
$title = $xpath->query("//channel/title")->item(0);
if ($title) {
$this->title = $title->nodeValue;
}
$link = $xpath->query("//channel/link")->item(0);
if ($link) {
if ($link->getAttribute("href"))
$this->link = $link->getAttribute("href");
else if ($link->nodeValue)
$this->link = $link->nodeValue;
}
$articles = $xpath->query("//channel/item");
foreach ($articles as $article) {
array_push($this->items, new FeedItem_RSS($article, $this->doc, $this->xpath));
}
break;
case $this::FEED_RDF:
$xpath->registerNamespace('rssfake', 'http://purl.org/rss/1.0/');
$title = $xpath->query("//rssfake:channel/rssfake:title")->item(0);
if ($title) {
$this->title = $title->nodeValue;
}
$link = $xpath->query("//rssfake:channel/rssfake:link")->item(0);
if ($link) {
$this->link = $link->nodeValue;
}
$articles = $xpath->query("//rssfake:item");
foreach ($articles as $article) {
array_push($this->items, new FeedItem_RSS($article, $this->doc, $this->xpath));
}
break;
}
if ($this->title) $this->title = trim($this->title);
if ($this->link) $this->link = trim($this->link);
} else {
if( !isset($this->error) ){
$this->error = "Unknown/unsupported feed type";
}
return;
}
}
function format_error($error) {
if ($error) {
return sprintf("LibXML error %s at line %d (column %d): %s",
$error->code, $error->line, $error->column,
$error->message);
} else {
return "";
}
}
function error() {
return $this->error;
}
function errors() {
return $this->libxml_errors;
}
function get_link() {
return clean($this->link);
}
function get_title() {
return clean($this->title);
}
function get_items() {
return $this->items;
}
function get_links($rel) {
$rv = array();
switch ($this->type) {
case $this::FEED_ATOM:
$links = $this->xpath->query("//atom:feed/atom:link");
foreach ($links as $link) {
if (!$rel || $link->hasAttribute('rel') && $link->getAttribute('rel') == $rel) {
array_push($rv, clean(trim($link->getAttribute('href'))));
}
}
break;
case $this::FEED_RSS:
$links = $this->xpath->query("//atom:link");
foreach ($links as $link) {
if (!$rel || $link->hasAttribute('rel') && $link->getAttribute('rel') == $rel) {
array_push($rv, clean(trim($link->getAttribute('href'))));
}
}
break;
}
return $rv;
}
}

1887
classes/feeds.php Executable file

File diff suppressed because it is too large Load Diff

23
classes/handler.php Normal file
View File

@ -0,0 +1,23 @@
<?php
class Handler implements IHandler {
protected $pdo;
protected $args;
function __construct($args) {
$this->pdo = Db::pdo();
$this->args = $args;
}
function csrf_ignore($method) {
return true;
}
function before($method) {
return true;
}
function after() {
return true;
}
}

View File

@ -0,0 +1,7 @@
<?php
class Handler_Protected extends Handler {
function before($method) {
return parent::before($method) && $_SESSION['uid'];
}
}

1275
classes/handler/public.php Executable file

File diff suppressed because it is too large Load Diff

4
classes/iauthmodule.php Normal file
View File

@ -0,0 +1,4 @@
<?php
interface IAuthModule {
function authenticate($login, $password);
}

13
classes/idb.php Normal file
View File

@ -0,0 +1,13 @@
<?php
interface IDb {
function connect($host, $user, $pass, $db, $port);
function escape_string($s, $strip_tags = true);
function query($query, $die_on_error = true);
function fetch_assoc($result);
function num_rows($result);
function fetch_result($result, $row, $param);
function close();
function affected_rows($result);
function last_error();
function last_query_error();
}

6
classes/ihandler.php Normal file
View File

@ -0,0 +1,6 @@
<?php
interface IHandler {
function csrf_ignore($method);
function before($method);
function after();
}

205
classes/labels.php Normal file
View File

@ -0,0 +1,205 @@
<?php
class Labels
{
static function label_to_feed_id($label) {
return LABEL_BASE_INDEX - 1 - abs($label);
}
static function feed_to_label_id($feed) {
return LABEL_BASE_INDEX - 1 + abs($feed);
}
static function find_id($label, $owner_uid) {
$pdo = Db::pdo();
$sth = $pdo->prepare("SELECT id FROM ttrss_labels2 WHERE caption = ?
AND owner_uid = ? LIMIT 1");
$sth->execute([$label, $owner_uid]);
if ($row = $sth->fetch()) {
return $row['id'];
} else {
return 0;
}
}
static function find_caption($label, $owner_uid) {
$pdo = Db::pdo();
$sth = $pdo->prepare("SELECT caption FROM ttrss_labels2 WHERE id = ?
AND owner_uid = ? LIMIT 1");
$sth->execute([$label, $owner_uid]);
if ($row = $sth->fetch()) {
return $row['caption'];
} else {
return "";
}
}
static function get_all_labels($owner_uid) {
$rv = array();
$pdo = Db::pdo();
$sth = $pdo->prepare("SELECT id, fg_color, bg_color, caption FROM ttrss_labels2
WHERE owner_uid = ? ORDER BY caption");
$sth->execute([$owner_uid]);
while ($line = $sth->fetch()) {
array_push($rv, $line);
}
return $rv;
}
static function update_cache($owner_uid, $id, $labels = false, $force = false) {
$pdo = Db::pdo();
if ($force)
Labels::clear_cache($id);
if (!$labels)
$labels = Article::get_article_labels($id);
$labels = json_encode($labels);
$sth = $pdo->prepare("UPDATE ttrss_user_entries SET
label_cache = ? WHERE ref_id = ? AND owner_uid = ?");
$sth->execute([$labels, $id, $owner_uid]);
}
static function clear_cache($id) {
$pdo = Db::pdo();
$sth = $pdo->prepare("UPDATE ttrss_user_entries SET
label_cache = '' WHERE ref_id = ?");
$sth->execute([$id]);
}
static function remove_article($id, $label, $owner_uid) {
$label_id = Labels::find_id($label, $owner_uid);
if (!$label_id) return;
$pdo = Db::pdo();
$sth = $pdo->prepare("DELETE FROM ttrss_user_labels2
WHERE
label_id = ? AND
article_id = ?");
$sth->execute([$label_id, $id]);
Labels::clear_cache($id);
}
static function add_article($id, $label, $owner_uid) {
$label_id = Labels::find_id($label, $owner_uid);
if (!$label_id) return;
$pdo = Db::pdo();
$sth = $pdo->prepare("SELECT
article_id FROM ttrss_labels2, ttrss_user_labels2
WHERE
label_id = id AND
label_id = ? AND
article_id = ? AND owner_uid = ?
LIMIT 1");
$sth->execute([$label_id, $id, $owner_uid]);
if (!$sth->fetch()) {
$sth = $pdo->prepare("INSERT INTO ttrss_user_labels2
(label_id, article_id) VALUES (?, ?)");
$sth->execute([$label_id, $id]);
}
Labels::clear_cache($id);
}
static function remove($id, $owner_uid) {
if (!$owner_uid) $owner_uid = $_SESSION["uid"];
$pdo = Db::pdo();
$tr_in_progress = false;
try {
$pdo->beginTransaction();
} catch (Exception $e) {
$tr_in_progress = true;
}
$sth = $pdo->prepare("SELECT caption FROM ttrss_labels2
WHERE id = ?");
$sth->execute([$id]);
$row = $sth->fetch();
$caption = $row['caption'];
$sth = $pdo->prepare("DELETE FROM ttrss_labels2 WHERE id = ?
AND owner_uid = ?");
$sth->execute([$id, $owner_uid]);
if ($sth->rowCount() != 0 && $caption) {
/* Remove access key for the label */
$ext_id = LABEL_BASE_INDEX - 1 - $id;
$sth = $pdo->prepare("DELETE FROM ttrss_access_keys WHERE
feed_id = ? AND owner_uid = ?");
$sth->execute([$ext_id, $owner_uid]);
/* Remove cached data */
$sth = $pdo->prepare("UPDATE ttrss_user_entries SET label_cache = ''
WHERE owner_uid = ?");
$sth->execute([$owner_uid]);
}
if (!$tr_in_progress) $pdo->commit();
}
static function create($caption, $fg_color = '', $bg_color = '', $owner_uid = false) {
if (!$owner_uid) $owner_uid = $_SESSION['uid'];
$pdo = Db::pdo();
$tr_in_progress = false;
try {
$pdo->beginTransaction();
} catch (Exception $e) {
$tr_in_progress = true;
}
$sth = $pdo->prepare("SELECT id FROM ttrss_labels2
WHERE caption = ? AND owner_uid = ?");
$sth->execute([$caption, $owner_uid]);
if (!$sth->fetch()) {
$sth = $pdo->prepare("INSERT INTO ttrss_labels2
(caption,owner_uid,fg_color,bg_color) VALUES (?, ?, ?, ?)");
$sth->execute([$caption, $owner_uid, $fg_color, $bg_color]);
$result = $sth->rowCount();
}
if (!$tr_in_progress) $pdo->commit();
return $result;
}
}

67
classes/logger.php Executable file
View File

@ -0,0 +1,67 @@
<?php
class Logger {
private static $instance;
private $adapter;
public static $errornames = array(
1 => 'E_ERROR',
2 => 'E_WARNING',
4 => 'E_PARSE',
8 => 'E_NOTICE',
16 => 'E_CORE_ERROR',
32 => 'E_CORE_WARNING',
64 => 'E_COMPILE_ERROR',
128 => 'E_COMPILE_WARNING',
256 => 'E_USER_ERROR',
512 => 'E_USER_WARNING',
1024 => 'E_USER_NOTICE',
2048 => 'E_STRICT',
4096 => 'E_RECOVERABLE_ERROR',
8192 => 'E_DEPRECATED',
16384 => 'E_USER_DEPRECATED',
32767 => 'E_ALL');
function log_error($errno, $errstr, $file, $line, $context) {
if ($errno == E_NOTICE) return false;
if ($this->adapter)
return $this->adapter->log_error($errno, $errstr, $file, $line, $context);
else
return false;
}
function log($string, $context = "") {
if ($this->adapter)
return $this->adapter->log_error(E_USER_NOTICE, $string, '', 0, $context);
else
return false;
}
private function __clone() {
//
}
function __construct() {
switch (LOG_DESTINATION) {
case "sql":
$this->adapter = new Logger_SQL();
break;
case "syslog":
$this->adapter = new Logger_Syslog();
break;
case "stdout":
$this->adapter = new Logger_Stdout();
break;
default:
$this->adapter = false;
}
}
public static function get() {
if (self::$instance == null)
self::$instance = new self();
return self::$instance;
}
}

29
classes/logger/sql.php Executable file
View File

@ -0,0 +1,29 @@
<?php
class Logger_SQL {
private $pdo;
function log_error($errno, $errstr, $file, $line, $context) {
// separate PDO connection object is used for logging
if (!$this->pdo) $this->pdo = Db::instance()->pdo_connect();
if ($this->pdo && get_schema_version() > 117) {
$owner_uid = $_SESSION["uid"] ? $_SESSION["uid"] : null;
if (DB_TYPE == "mysql")
$context = substr($context, 0, 65534);
$sth = $this->pdo->prepare("INSERT INTO ttrss_error_log
(errno, errstr, filename, lineno, context, owner_uid, created_at) VALUES
(?, ?, ?, ?, ?, ?, NOW())");
$sth->execute([$errno, $errstr, $file, $line, $context, $owner_uid]);
return $sth->rowCount();
}
return false;
}
}

33
classes/logger/stdout.php Normal file
View File

@ -0,0 +1,33 @@
<?php
class Logger_Stdout {
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
function log_error($errno, $errstr, $file, $line, $context) {
switch ($errno) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$priority = LOG_ERR;
break;
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
$priority = LOG_WARNING;
break;
default:
$priority = LOG_INFO;
}
$errname = Logger::$errornames[$errno] . " ($errno)";
print "[EEE] $priority $errname ($file:$line) $errstr\n";
}
}

33
classes/logger/syslog.php Normal file
View File

@ -0,0 +1,33 @@
<?php
class Logger_Syslog {
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
function log_error($errno, $errstr, $file, $line, $context) {
switch ($errno) {
case E_ERROR:
case E_PARSE:
case E_CORE_ERROR:
case E_COMPILE_ERROR:
case E_USER_ERROR:
$priority = LOG_ERR;
break;
case E_WARNING:
case E_CORE_WARNING:
case E_COMPILE_WARNING:
case E_USER_WARNING:
$priority = LOG_WARNING;
break;
default:
$priority = LOG_INFO;
}
$errname = Logger::$errornames[$errno] . " ($errno)";
syslog($priority, "[tt-rss] $errname ($file:$line) $errstr");
}
}

53
classes/mailer.php Normal file
View File

@ -0,0 +1,53 @@
<?php
class Mailer {
// TODO: support HTML mail (i.e. MIME messages)
private $last_error = "Unable to send mail: check local configuration.";
function mail($params) {
$to_name = $params["to_name"];
$to_address = $params["to_address"];
$subject = $params["subject"];
$message = $params["message"];
$message_html = $params["message_html"];
$from_name = $params["from_name"] ? $params["from_name"] : SMTP_FROM_NAME;
$from_address = $params["from_address"] ? $params["from_address"] : SMTP_FROM_ADDRESS;
$additional_headers = $params["headers"] ? $params["headers"] : [];
$from_combined = $from_name ? "$from_name <$from_address>" : $from_address;
$to_combined = $to_name ? "$to_name <$to_address>" : $to_address;
if (defined('_LOG_SENT_MAIL') && _LOG_SENT_MAIL)
Logger::get()->log("Sending mail from $from_combined to $to_combined [$subject]: $message");
// HOOK_SEND_MAIL plugin instructions:
// 1. return 1 or true if mail is handled
// 2. return -1 if there's been a fatal error and no further action is allowed
// 3. any other return value will allow cycling to the next handler and, eventually, to default mail() function
// 4. set error message if needed via passed Mailer instance function set_error()
foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_SEND_MAIL) as $p) {
$rc = $p->hook_send_mail($this, $params);
if ($rc == 1)
return $rc;
if ($rc == -1)
return 0;
}
$headers = [ "From: $from_combined", "Content-Type: text/plain; charset=UTF-8" ];
return mail($to_combined, $subject, $message, implode("\r\n", array_merge($headers, $additional_headers)));
}
function set_error($message) {
$this->last_error = $message;
}
function error() {
return $this->last_error;
}
}

654
classes/opml.php Normal file
View File

@ -0,0 +1,654 @@
<?php
class Opml extends Handler_Protected {
function csrf_ignore($method) {
$csrf_ignored = array("export", "import");
return array_search($method, $csrf_ignored) !== false;
}
function export() {
$output_name = "tt-rss_".date("Y-m-d").".opml";
$include_settings = $_REQUEST["include_settings"] == "1";
$owner_uid = $_SESSION["uid"];
$rc = $this->opml_export($output_name, $owner_uid, false, $include_settings);
return $rc;
}
function import() {
$owner_uid = $_SESSION["uid"];
header('Content-Type: text/html; charset=utf-8');
print "<html>
<head>
".stylesheet_tag("css/default.css")."
<title>".__("OPML Utility")."</title>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\"/>
</head>
<body class='claro ttrss_utility'>
<h1>".__('OPML Utility')."</h1><div class='content'>";
add_feed_category("Imported feeds");
$this->opml_notice(__("Importing OPML..."));
$this->opml_import($owner_uid);
print "<br><form method=\"GET\" action=\"prefs.php\">
<input type=\"submit\" value=\"".__("Return to preferences")."\">
</form>";
print "</div></body></html>";
}
// Export
private function opml_export_category($owner_uid, $cat_id, $hide_private_feeds = false, $include_settings = true) {
$cat_id = (int) $cat_id;
if ($hide_private_feeds)
$hide_qpart = "(private IS false AND auth_login = '' AND auth_pass = '')";
else
$hide_qpart = "true";
$out = "";
$ttrss_specific_qpart = "";
if ($cat_id) {
$sth = $this->pdo->prepare("SELECT title,order_id
FROM ttrss_feed_categories WHERE id = ?
AND owner_uid = ?");
$sth->execute([$cat_id, $owner_uid]);
$row = $sth->fetch();
$cat_title = htmlspecialchars($row['title']);
if ($include_settings) {
$order_id = (int)$row["order_id"];
$ttrss_specific_qpart = "ttrssSortOrder=\"$order_id\"";
}
} else {
$cat_title = "";
}
if ($cat_title) $out .= "<outline text=\"$cat_title\" $ttrss_specific_qpart>\n";
$sth = $this->pdo->prepare("SELECT id,title
FROM ttrss_feed_categories WHERE
(parent_cat = :cat OR (:cat = 0 AND parent_cat IS NULL)) AND
owner_uid = :uid ORDER BY order_id, title");
$sth->execute([':cat' => $cat_id, ':uid' => $owner_uid]);
while ($line = $sth->fetch()) {
$out .= $this->opml_export_category($owner_uid, $line["id"], $hide_private_feeds, $include_settings);
}
$fsth = $this->pdo->prepare("select title, feed_url, site_url, update_interval, order_id
FROM ttrss_feeds WHERE
(cat_id = :cat OR (:cat = 0 AND cat_id IS NULL)) AND owner_uid = :uid AND $hide_qpart
ORDER BY order_id, title");
$fsth->execute([':cat' => $cat_id, ':uid' => $owner_uid]);
while ($fline = $fsth->fetch()) {
$title = htmlspecialchars($fline["title"]);
$url = htmlspecialchars($fline["feed_url"]);
$site_url = htmlspecialchars($fline["site_url"]);
if ($include_settings) {
$update_interval = (int)$fline["update_interval"];
$order_id = (int)$fline["order_id"];
$ttrss_specific_qpart = "ttrssSortOrder=\"$order_id\" ttrssUpdateInterval=\"$update_interval\"";
} else {
$ttrss_specific_qpart = "";
}
if ($site_url) {
$html_url_qpart = "htmlUrl=\"$site_url\"";
} else {
$html_url_qpart = "";
}
$out .= "<outline type=\"rss\" text=\"$title\" xmlUrl=\"$url\" $ttrss_specific_qpart $html_url_qpart/>\n";
}
if ($cat_title) $out .= "</outline>\n";
return $out;
}
function opml_export($name, $owner_uid, $hide_private_feeds = false, $include_settings = true) {
if (!$owner_uid) return;
if (!isset($_REQUEST["debug"])) {
header("Content-type: application/xml+opml");
header("Content-Disposition: attachment; filename=" . $name );
} else {
header("Content-type: text/xml");
}
$out = "<?xml version=\"1.0\" encoding=\"utf-8\"?".">";
$out .= "<opml version=\"1.0\">";
$out .= "<head>
<dateCreated>" . date("r", time()) . "</dateCreated>
<title>Tiny Tiny RSS Feed Export</title>
</head>";
$out .= "<body>";
$out .= $this->opml_export_category($owner_uid, 0, $hide_private_feeds, $include_settings);
# export tt-rss settings
if ($include_settings) {
$out .= "<outline text=\"tt-rss-prefs\" schema-version=\"".SCHEMA_VERSION."\">";
$sth = $this->pdo->prepare("SELECT pref_name, value FROM ttrss_user_prefs WHERE
profile IS NULL AND owner_uid = ? ORDER BY pref_name");
$sth->execute([$owner_uid]);
while ($line = $sth->fetch()) {
$name = $line["pref_name"];
$value = htmlspecialchars($line["value"]);
$out .= "<outline pref-name=\"$name\" value=\"$value\"/>";
}
$out .= "</outline>";
$out .= "<outline text=\"tt-rss-labels\" schema-version=\"".SCHEMA_VERSION."\">";
$sth = $this->pdo->prepare("SELECT * FROM ttrss_labels2 WHERE
owner_uid = ?");
$sth->execute([$owner_uid]);
while ($line = $sth->fetch()) {
$name = htmlspecialchars($line['caption']);
$fg_color = htmlspecialchars($line['fg_color']);
$bg_color = htmlspecialchars($line['bg_color']);
$out .= "<outline label-name=\"$name\" label-fg-color=\"$fg_color\" label-bg-color=\"$bg_color\"/>";
}
$out .= "</outline>";
$out .= "<outline text=\"tt-rss-filters\" schema-version=\"".SCHEMA_VERSION."\">";
$sth = $this->pdo->prepare("SELECT * FROM ttrss_filters2
WHERE owner_uid = ? ORDER BY id");
$sth->execute([$owner_uid]);
while ($line = $sth->fetch()) {
$line["rules"] = array();
$line["actions"] = array();
$tmph = $this->pdo->prepare("SELECT * FROM ttrss_filters2_rules
WHERE filter_id = ?");
$tmph->execute([$line['id']]);
while ($tmp_line = $tmph->fetch(PDO::FETCH_ASSOC)) {
unset($tmp_line["id"]);
unset($tmp_line["filter_id"]);
$cat_filter = $tmp_line["cat_filter"];
if (!$tmp_line["match_on"]) {
if ($cat_filter && $tmp_line["cat_id"] || $tmp_line["feed_id"]) {
$tmp_line["feed"] = Feeds::getFeedTitle(
$cat_filter ? $tmp_line["cat_id"] : $tmp_line["feed_id"],
$cat_filter);
} else {
$tmp_line["feed"] = "";
}
} else {
$match = [];
foreach (json_decode($tmp_line["match_on"], true) as $feed_id) {
if (strpos($feed_id, "CAT:") === 0) {
$feed_id = (int)substr($feed_id, 4);
if ($feed_id) {
array_push($match, [Feeds::getCategoryTitle($feed_id), true, false]);
} else {
array_push($match, [0, true, true]);
}
} else {
if ($feed_id) {
array_push($match, [Feeds::getFeedTitle((int)$feed_id), false, false]);
} else {
array_push($match, [0, false, true]);
}
}
}
$tmp_line["match"] = $match;
unset($tmp_line["match_on"]);
}
unset($tmp_line["feed_id"]);
unset($tmp_line["cat_id"]);
array_push($line["rules"], $tmp_line);
}
$tmph = $this->pdo->prepare("SELECT * FROM ttrss_filters2_actions
WHERE filter_id = ?");
$tmph->execute([$line['id']]);
while ($tmp_line = $tmph->fetch(PDO::FETCH_ASSOC)) {
unset($tmp_line["id"]);
unset($tmp_line["filter_id"]);
array_push($line["actions"], $tmp_line);
}
unset($line["id"]);
unset($line["owner_uid"]);
$filter = json_encode($line);
$out .= "<outline filter-type=\"2\"><![CDATA[$filter]]></outline>";
}
$out .= "</outline>";
}
$out .= "</body></opml>";
// Format output.
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;
$doc->loadXML($out);
$xpath = new DOMXpath($doc);
$outlines = $xpath->query("//outline[@title]");
// cleanup empty categories
foreach ($outlines as $node) {
if ($node->getElementsByTagName('outline')->length == 0)
$node->parentNode->removeChild($node);
}
$res = $doc->saveXML();
/* // saveXML uses a two-space indent. Change to tabs.
$res = preg_replace_callback('/^(?: )+/mu',
create_function(
'$matches',
'return str_repeat("\t", intval(strlen($matches[0])/2));'),
$res); */
print $res;
}
// Import
private function opml_import_feed($node, $cat_id, $owner_uid) {
$attrs = $node->attributes;
$feed_title = mb_substr($attrs->getNamedItem('text')->nodeValue, 0, 250);
if (!$feed_title) $feed_title = mb_substr($attrs->getNamedItem('title')->nodeValue, 0, 250);
$feed_url = $attrs->getNamedItem('xmlUrl')->nodeValue;
if (!$feed_url) $feed_url = $attrs->getNamedItem('xmlURL')->nodeValue;
$site_url = mb_substr($attrs->getNamedItem('htmlUrl')->nodeValue, 0, 250);
if ($feed_url) {
$sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
feed_url = ? AND owner_uid = ?");
$sth->execute([$feed_url, $owner_uid]);
if (!$feed_title) $feed_title = '[Unknown]';
if (!$sth->fetch()) {
#$this->opml_notice("[FEED] [$feed_title/$feed_url] dst_CAT=$cat_id");
$this->opml_notice(T_sprintf("Adding feed: %s", $feed_title == '[Unknown]' ? $feed_url : $feed_title));
if (!$cat_id) $cat_id = null;
$update_interval = (int) $attrs->getNamedItem('ttrssUpdateInterval')->nodeValue;
if (!$update_interval) $update_interval = 0;
$order_id = (int) $attrs->getNamedItem('ttrssSortOrder')->nodeValue;
if (!$order_id) $order_id = 0;
$sth = $this->pdo->prepare("INSERT INTO ttrss_feeds
(title, feed_url, owner_uid, cat_id, site_url, order_id, update_interval) VALUES
(?, ?, ?, ?, ?, ?, ?)");
$sth->execute([$feed_title, $feed_url, $owner_uid, $cat_id, $site_url, $order_id, $update_interval]);
} else {
$this->opml_notice(T_sprintf("Duplicate feed: %s", $feed_title == '[Unknown]' ? $feed_url : $feed_title));
}
}
}
private function opml_import_label($node, $owner_uid) {
$attrs = $node->attributes;
$label_name = $attrs->getNamedItem('label-name')->nodeValue;
if ($label_name) {
$fg_color = $attrs->getNamedItem('label-fg-color')->nodeValue;
$bg_color = $attrs->getNamedItem('label-bg-color')->nodeValue;
if (!Labels::find_id($label_name, $_SESSION['uid'])) {
$this->opml_notice(T_sprintf("Adding label %s", htmlspecialchars($label_name)));
Labels::create($label_name, $fg_color, $bg_color, $owner_uid);
} else {
$this->opml_notice(T_sprintf("Duplicate label: %s", htmlspecialchars($label_name)));
}
}
}
private function opml_import_preference($node) {
$attrs = $node->attributes;
$pref_name = $attrs->getNamedItem('pref-name')->nodeValue;
if ($pref_name) {
$pref_value = $attrs->getNamedItem('value')->nodeValue;
$this->opml_notice(T_sprintf("Setting preference key %s to %s",
$pref_name, $pref_value));
set_pref($pref_name, $pref_value);
}
}
private function opml_import_filter($node) {
$attrs = $node->attributes;
$filter_type = $attrs->getNamedItem('filter-type')->nodeValue;
if ($filter_type == '2') {
$filter = json_decode($node->nodeValue, true);
if ($filter) {
$match_any_rule = bool_to_sql_bool($filter["match_any_rule"]);
$enabled = bool_to_sql_bool($filter["enabled"]);
$inverse = bool_to_sql_bool($filter["inverse"]);
$title = $filter["title"];
//print "F: $title, $inverse, $enabled, $match_any_rule";
$sth = $this->pdo->prepare("INSERT INTO ttrss_filters2 (match_any_rule,enabled,inverse,title,owner_uid)
VALUES (?, ?, ?, ?, ?)");
$sth->execute([$match_any_rule, $enabled, $inverse, $title, $_SESSION['uid']]);
$sth = $this->pdo->prepare("SELECT MAX(id) AS id FROM ttrss_filters2 WHERE
owner_uid = ?");
$sth->execute([$_SESSION['uid']]);
$row = $sth->fetch();
$filter_id = $row['id'];
if ($filter_id) {
$this->opml_notice(T_sprintf("Adding filter %s...", $title));
foreach ($filter["rules"] as $rule) {
$feed_id = null;
$cat_id = null;
if ($rule["match"]) {
$match_on = [];
foreach ($rule["match"] as $match) {
list ($name, $is_cat, $is_id) = $match;
if ($is_id) {
array_push($match_on, ($is_cat ? "CAT:" : "") . $name);
} else {
if (!$is_cat) {
$tsth = $this->pdo->prepare("SELECT id FROM ttrss_feeds
WHERE title = ? AND owner_uid = ?");
$tsth->execute([$name, $_SESSION['uid']]);
if ($row = $tsth->fetch()) {
$match_id = $row['id'];
array_push($match_on, $match_id);
}
} else {
$tsth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
WHERE title = ? AND owner_uid = ?");
$tsth->execute([$name, $_SESSION['uid']]);
if ($row = $tsth->fetch()) {
$match_id = $row['id'];
array_push($match_on, "CAT:$match_id");
}
}
}
}
$reg_exp = $rule["reg_exp"];
$filter_type = (int)$rule["filter_type"];
$inverse = bool_to_sql_bool($rule["inverse"]);
$match_on = json_encode($match_on);
$usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_rules
(feed_id,cat_id,match_on,filter_id,filter_type,reg_exp,cat_filter,inverse)
VALUES
(NULL, NULL, ?, ?, ?, ?, false, ?)");
$usth->execute([$match_on, $filter_id, $filter_type, $reg_exp, $inverse]);
} else {
if (!$rule["cat_filter"]) {
$tsth = $this->pdo->prepare("SELECT id FROM ttrss_feeds
WHERE title = ? AND owner_uid = ?");
$tsth->execute([$rule['feed'], $_SESSION['uid']]);
if ($row = $tsth->fetch()) {
$feed_id = $row['id'];
}
} else {
$tsth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
WHERE title = ? AND owner_uid = ?");
$tsth->execute([$rule['feed'], $_SESSION['uid']]);
if ($row = $tsth->fetch()) {
$feed_id = $row['id'];
}
}
$cat_filter = bool_to_sql_bool($rule["cat_filter"]);
$reg_exp = $rule["reg_exp"];
$filter_type = (int)$rule["filter_type"];
$inverse = bool_to_sql_bool($rule["inverse"]);
$usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_rules
(feed_id,cat_id,filter_id,filter_type,reg_exp,cat_filter,inverse)
VALUES
(?, ?, ?, ?, ?, ?, ?)");
$usth->execute([$feed_id, $cat_id, $filter_id, $filter_type, $reg_exp, $cat_filter, $inverse]);
}
}
foreach ($filter["actions"] as $action) {
$action_id = (int)$action["action_id"];
$action_param = $action["action_param"];
$usth = $this->pdo->prepare("INSERT INTO ttrss_filters2_actions
(filter_id,action_id,action_param)
VALUES
(?, ?, ?)");
$usth->execute([$filter_id, $action_id, $action_param]);
}
}
}
}
}
private function opml_import_category($doc, $root_node, $owner_uid, $parent_id) {
$default_cat_id = (int) $this->get_feed_category('Imported feeds', false);
if ($root_node) {
$cat_title = mb_substr($root_node->attributes->getNamedItem('text')->nodeValue, 0, 250);
if (!$cat_title)
$cat_title = mb_substr($root_node->attributes->getNamedItem('title')->nodeValue, 0, 250);
if (!in_array($cat_title, array("tt-rss-filters", "tt-rss-labels", "tt-rss-prefs"))) {
$cat_id = $this->get_feed_category($cat_title, $parent_id);
if ($cat_id === false) {
$order_id = (int) $root_node->attributes->getNamedItem('ttrssSortOrder')->nodeValue;
if (!$order_id) $order_id = 0;
add_feed_category($cat_title, $parent_id, $order_id);
$cat_id = $this->get_feed_category($cat_title, $parent_id);
}
} else {
$cat_id = 0;
}
$outlines = $root_node->childNodes;
} else {
$xpath = new DOMXpath($doc);
$outlines = $xpath->query("//opml/body/outline");
$cat_id = 0;
}
#$this->opml_notice("[CAT] $cat_title id: $cat_id P_id: $parent_id");
$this->opml_notice(T_sprintf("Processing category: %s", $cat_title ? $cat_title : __("Uncategorized")));
foreach ($outlines as $node) {
if ($node->hasAttributes() && strtolower($node->tagName) == "outline") {
$attrs = $node->attributes;
$node_cat_title = $attrs->getNamedItem('text')->nodeValue;
if (!$node_cat_title)
$node_cat_title = $attrs->getNamedItem('title')->nodeValue;
$node_feed_url = $attrs->getNamedItem('xmlUrl')->nodeValue;
if ($node_cat_title && !$node_feed_url) {
$this->opml_import_category($doc, $node, $owner_uid, $cat_id);
} else {
if (!$cat_id) {
$dst_cat_id = $default_cat_id;
} else {
$dst_cat_id = $cat_id;
}
switch ($cat_title) {
case "tt-rss-prefs":
$this->opml_import_preference($node);
break;
case "tt-rss-labels":
$this->opml_import_label($node, $owner_uid);
break;
case "tt-rss-filters":
$this->opml_import_filter($node);
break;
default:
$this->opml_import_feed($node, $dst_cat_id, $owner_uid);
}
}
}
}
}
function opml_import($owner_uid) {
if (!$owner_uid) return;
$doc = false;
if ($_FILES['opml_file']['error'] != 0) {
print_error(T_sprintf("Upload failed with error code %d",
$_FILES['opml_file']['error']));
return;
}
if (is_uploaded_file($_FILES['opml_file']['tmp_name'])) {
$tmp_file = tempnam(CACHE_DIR . '/upload', 'opml');
$result = move_uploaded_file($_FILES['opml_file']['tmp_name'],
$tmp_file);
if (!$result) {
print_error(__("Unable to move uploaded file."));
return;
}
} else {
print_error(__('Error: please upload OPML file.'));
return;
}
if (is_file($tmp_file)) {
$doc = new DOMDocument();
libxml_disable_entity_loader(false);
$doc->load($tmp_file);
libxml_disable_entity_loader(true);
unlink($tmp_file);
} else if (!$doc) {
print_error(__('Error: unable to find moved OPML file.'));
return;
}
if ($doc) {
$this->pdo->beginTransaction();
$this->opml_import_category($doc, false, $owner_uid, false);
$this->pdo->commit();
} else {
print_error(__('Error while parsing document.'));
}
}
private function opml_notice($msg) {
print "$msg<br/>";
}
static function opml_publish_url(){
$url_path = get_self_url_prefix();
$url_path .= "/opml.php?op=publish&key=" .
get_feed_access_key('OPML:Publish', false, $_SESSION["uid"]);
return $url_path;
}
function get_feed_category($feed_cat, $parent_cat_id = false) {
$parent_cat_id = (int) $parent_cat_id;
$sth = $this->pdo->prepare("SELECT id FROM ttrss_feed_categories
WHERE title = :title
AND (parent_cat = :parent OR (:parent = 0 AND parent_cat IS NULL))
AND owner_uid = :uid");
$sth->execute([':title' => $feed_cat, ':parent' => $parent_cat_id, ':uid' => $_SESSION['uid']]);
if ($row = $sth->fetch()) {
return $row['id'];
} else {
return false;
}
}
}

60
classes/plugin.php Normal file
View File

@ -0,0 +1,60 @@
<?php
abstract class Plugin {
const API_VERSION_COMPAT = 1;
/** @var PDO */
protected $pdo;
/* @var PluginHost $host */
abstract function init($host);
abstract function about();
// return array(1.0, "plugin", "No description", "No author", false);
function __construct() {
$this->pdo = Db::pdo();
}
function flags() {
/* associative array, possible keys:
needs_curl = boolean
*/
return array();
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
function is_public_method($method) {
return false;
}
function get_js() {
return "";
}
function get_prefs_js() {
return "";
}
function api_version() {
return Plugin::API_VERSION_COMPAT;
}
/* gettext-related helpers */
function __($msgid) {
return _dgettext(PluginHost::object_to_domain($this), $msgid);
}
function _ngettext($singular, $plural, $number) {
return _dngettext(PluginHost::object_to_domain($this), $singular, $plural, $number);
}
function T_sprintf() {
$args = func_get_args();
$msgid = array_shift($args);
return vsprintf($this->__($msgid), $args);
}
}

20
classes/pluginhandler.php Normal file
View File

@ -0,0 +1,20 @@
<?php
class PluginHandler extends Handler_Protected {
function csrf_ignore($method) {
return true;
}
function catchall($method) {
$plugin = PluginHost::getInstance()->get_plugin(clean($_REQUEST["plugin"]));
if ($plugin) {
if (method_exists($plugin, $method)) {
$plugin->$method();
} else {
print error_json(13);
}
} else {
print error_json(14);
}
}
}

472
classes/pluginhost.php Executable file
View File

@ -0,0 +1,472 @@
<?php
class PluginHost {
private $pdo;
private $hooks = array();
private $plugins = array();
private $handlers = array();
private $commands = array();
private $storage = array();
private $feeds = array();
private $api_methods = array();
private $plugin_actions = array();
private $owner_uid;
private $last_registered;
private static $instance;
const API_VERSION = 2;
// Hooks marked with *1 are run in global context and available
// to plugins loaded in config.php only
const HOOK_ARTICLE_BUTTON = 1;
const HOOK_ARTICLE_FILTER = 2;
const HOOK_PREFS_TAB = 3;
const HOOK_PREFS_TAB_SECTION = 4;
const HOOK_PREFS_TABS = 5;
const HOOK_FEED_PARSED = 6;
const HOOK_UPDATE_TASK = 7; // *1
const HOOK_AUTH_USER = 8;
const HOOK_HOTKEY_MAP = 9;
const HOOK_RENDER_ARTICLE = 10;
const HOOK_RENDER_ARTICLE_CDM = 11;
const HOOK_FEED_FETCHED = 12;
const HOOK_SANITIZE = 13;
const HOOK_RENDER_ARTICLE_API = 14;
const HOOK_TOOLBAR_BUTTON = 15;
const HOOK_ACTION_ITEM = 16;
const HOOK_HEADLINE_TOOLBAR_BUTTON = 17;
const HOOK_HOTKEY_INFO = 18;
const HOOK_ARTICLE_LEFT_BUTTON = 19;
const HOOK_PREFS_EDIT_FEED = 20;
const HOOK_PREFS_SAVE_FEED = 21;
const HOOK_FETCH_FEED = 22;
const HOOK_QUERY_HEADLINES = 23;
const HOOK_HOUSE_KEEPING = 24; // *1
const HOOK_SEARCH = 25;
const HOOK_FORMAT_ENCLOSURES = 26;
const HOOK_SUBSCRIBE_FEED = 27;
const HOOK_HEADLINES_BEFORE = 28;
const HOOK_RENDER_ENCLOSURE = 29;
const HOOK_ARTICLE_FILTER_ACTION = 30;
const HOOK_ARTICLE_EXPORT_FEED = 31;
const HOOK_MAIN_TOOLBAR_BUTTON = 32;
const HOOK_ENCLOSURE_ENTRY = 33;
const HOOK_FORMAT_ARTICLE = 34;
const HOOK_FORMAT_ARTICLE_CDM = 35; /* RIP */
const HOOK_FEED_BASIC_INFO = 36;
const HOOK_SEND_LOCAL_FILE = 37;
const HOOK_UNSUBSCRIBE_FEED = 38;
const HOOK_SEND_MAIL = 39;
const HOOK_FILTER_TRIGGERED = 40;
const KIND_ALL = 1;
const KIND_SYSTEM = 2;
const KIND_USER = 3;
static function object_to_domain($plugin) {
return strtolower(get_class($plugin));
}
function __construct() {
$this->pdo = Db::pdo();
$this->storage = array();
}
private function __clone() {
//
}
public static function getInstance() {
if (self::$instance == null)
self::$instance = new self();
return self::$instance;
}
private function register_plugin($name, $plugin) {
//array_push($this->plugins, $plugin);
$this->plugins[$name] = $plugin;
}
// needed for compatibility with API 1
function get_link() {
return false;
}
function get_dbh() {
return Db::get();
}
function get_pdo() {
return $this->pdo;
}
function get_plugin_names() {
$names = array();
foreach ($this->plugins as $p) {
array_push($names, get_class($p));
}
return $names;
}
function get_plugins() {
return $this->plugins;
}
function get_plugin($name) {
return $this->plugins[strtolower($name)];
}
function run_hooks($type, $method, $args) {
foreach ($this->get_hooks($type) as $hook) {
$hook->$method($args);
}
}
function add_hook($type, $sender) {
if (!is_array($this->hooks[$type])) {
$this->hooks[$type] = array();
}
array_push($this->hooks[$type], $sender);
}
function del_hook($type, $sender) {
if (is_array($this->hooks[$type])) {
$key = array_Search($sender, $this->hooks[$type]);
if ($key !== FALSE) {
unset($this->hooks[$type][$key]);
}
}
}
function get_hooks($type) {
if (isset($this->hooks[$type])) {
return $this->hooks[$type];
} else {
return array();
}
}
function load_all($kind, $owner_uid = false, $skip_init = false) {
$plugins = array_merge(glob("plugins/*"), glob("data/plugins.local/*"));
$plugins = array_filter($plugins, "is_dir");
$plugins = array_map("basename", $plugins);
asort($plugins);
$this->load(join(",", $plugins), $kind, $owner_uid, $skip_init);
}
function load($classlist, $kind, $owner_uid = false, $skip_init = false) {
$plugins = explode(",", $classlist);
$this->owner_uid = (int) $owner_uid;
foreach ($plugins as $class) {
$class = trim($class);
$class_file = strtolower(basename($class));
if (!is_dir(__DIR__."/../plugins/$class_file") &&
!is_dir(__DIR__."/../data/plugins.local/$class_file")) continue;
// try system plugin directory first
$file = __DIR__ . "/../plugins/$class_file/init.php";
$vendor_dir = __DIR__ . "/../plugins/$class_file/vendor";
if (!file_exists($file)) {
$file = __DIR__ . "/../data/plugins.local/$class_file/init.php";
$vendor_dir = __DIR__ . "/../data/plugins.local/$class_file/vendor";
}
if (!isset($this->plugins[$class])) {
if (file_exists($file)) require_once $file;
if (class_exists($class) && is_subclass_of($class, "Plugin")) {
// register plugin autoloader if necessary, for namespaced classes ONLY
// layout corresponds to tt-rss main /vendor/author/Package/Class.php
if (file_exists($vendor_dir)) {
spl_autoload_register(function($class) use ($vendor_dir) {
if (strpos($class, '\\') !== FALSE) {
list ($namespace, $class_name) = explode('\\', $class, 2);
if ($namespace && $class_name) {
$class_file = "$vendor_dir/$namespace/" . str_replace('\\', '/', $class_name) . ".php";
if (file_exists($class_file))
require_once $class_file;
}
}
});
}
$plugin = new $class($this);
$plugin_api = $plugin->api_version();
if ($plugin_api < PluginHost::API_VERSION) {
user_error("Plugin $class is not compatible with current API version (need: " . PluginHost::API_VERSION . ", got: $plugin_api)", E_USER_WARNING);
continue;
}
if (file_exists(dirname($file) . "/locale")) {
_bindtextdomain($class, dirname($file) . "/locale");
_bind_textdomain_codeset($class, "UTF-8");
}
$this->last_registered = $class;
switch ($kind) {
case $this::KIND_SYSTEM:
if ($this->is_system($plugin)) {
if (!$skip_init) $plugin->init($this);
$this->register_plugin($class, $plugin);
}
break;
case $this::KIND_USER:
if (!$this->is_system($plugin)) {
if (!$skip_init) $plugin->init($this);
$this->register_plugin($class, $plugin);
}
break;
case $this::KIND_ALL:
if (!$skip_init) $plugin->init($this);
$this->register_plugin($class, $plugin);
break;
}
}
}
}
}
function is_system($plugin) {
$about = $plugin->about();
return @$about[3];
}
// only system plugins are allowed to modify routing
function add_handler($handler, $method, $sender) {
$handler = str_replace("-", "_", strtolower($handler));
$method = strtolower($method);
if ($this->is_system($sender)) {
if (!is_array($this->handlers[$handler])) {
$this->handlers[$handler] = array();
}
$this->handlers[$handler][$method] = $sender;
}
}
function del_handler($handler, $method, $sender) {
$handler = str_replace("-", "_", strtolower($handler));
$method = strtolower($method);
if ($this->is_system($sender)) {
unset($this->handlers[$handler][$method]);
}
}
function lookup_handler($handler, $method) {
$handler = str_replace("-", "_", strtolower($handler));
$method = strtolower($method);
if (is_array($this->handlers[$handler])) {
if (isset($this->handlers[$handler]["*"])) {
return $this->handlers[$handler]["*"];
} else {
return $this->handlers[$handler][$method];
}
}
return false;
}
function add_command($command, $description, $sender, $suffix = "", $arghelp = "") {
$command = str_replace("-", "_", strtolower($command));
$this->commands[$command] = array("description" => $description,
"suffix" => $suffix,
"arghelp" => $arghelp,
"class" => $sender);
}
function del_command($command) {
$command = "-" . strtolower($command);
unset($this->commands[$command]);
}
function lookup_command($command) {
$command = "-" . strtolower($command);
if (is_array($this->commands[$command])) {
return $this->commands[$command]["class"];
} else {
return false;
}
}
function get_commands() {
return $this->commands;
}
function run_commands($args) {
foreach ($this->get_commands() as $command => $data) {
if (isset($args[$command])) {
$command = str_replace("-", "", $command);
$data["class"]->$command($args);
}
}
}
function load_data() {
if ($this->owner_uid) {
$sth = $this->pdo->prepare("SELECT name, content FROM ttrss_plugin_storage
WHERE owner_uid = ?");
$sth->execute([$this->owner_uid]);
while ($line = $sth->fetch()) {
$this->storage[$line["name"]] = unserialize($line["content"]);
}
}
}
private function save_data($plugin) {
if ($this->owner_uid) {
$this->pdo->beginTransaction();
$sth = $this->pdo->prepare("SELECT id FROM ttrss_plugin_storage WHERE
owner_uid= ? AND name = ?");
$sth->execute([$this->owner_uid, $plugin]);
if (!isset($this->storage[$plugin]))
$this->storage[$plugin] = array();
$content = serialize($this->storage[$plugin]);
if ($sth->fetch()) {
$sth = $this->pdo->prepare("UPDATE ttrss_plugin_storage SET content = ?
WHERE owner_uid= ? AND name = ?");
$sth->execute([(string)$content, $this->owner_uid, $plugin]);
} else {
$sth = $this->pdo->prepare("INSERT INTO ttrss_plugin_storage
(name,owner_uid,content) VALUES
(?, ?, ?)");
$sth->execute([$plugin, $this->owner_uid, (string)$content]);
}
$this->pdo->commit();
}
}
function set($sender, $name, $value, $sync = true) {
$idx = get_class($sender);
if (!isset($this->storage[$idx]))
$this->storage[$idx] = array();
$this->storage[$idx][$name] = $value;
if ($sync) $this->save_data(get_class($sender));
}
function get($sender, $name, $default_value = false) {
$idx = get_class($sender);
if (isset($this->storage[$idx][$name])) {
return $this->storage[$idx][$name];
} else {
return $default_value;
}
}
function get_all($sender) {
$idx = get_class($sender);
$data = $this->storage[$idx];
return $data ? $data : [];
}
function clear_data($sender) {
if ($this->owner_uid) {
$idx = get_class($sender);
unset($this->storage[$idx]);
$sth = $this->pdo->prepare("DELETE FROM ttrss_plugin_storage WHERE name = ?
AND owner_uid = ?");
$sth->execute([$idx, $this->owner_uid]);
}
}
// Plugin feed functions are *EXPERIMENTAL*!
// cat_id: only -1 is supported (Special)
function add_feed($cat_id, $title, $icon, $sender) {
if (!$this->feeds[$cat_id]) $this->feeds[$cat_id] = array();
$id = count($this->feeds[$cat_id]);
array_push($this->feeds[$cat_id],
array('id' => $id, 'title' => $title, 'sender' => $sender, 'icon' => $icon));
return $id;
}
function get_feeds($cat_id) {
return $this->feeds[$cat_id];
}
// convert feed_id (e.g. -129) to pfeed_id first
function get_feed_handler($pfeed_id) {
foreach ($this->feeds as $cat) {
foreach ($cat as $feed) {
if ($feed['id'] == $pfeed_id) {
return $feed['sender'];
}
}
}
}
static function pfeed_to_feed_id($label) {
return PLUGIN_FEED_BASE_INDEX - 1 - abs($label);
}
static function feed_to_pfeed_id($feed) {
return PLUGIN_FEED_BASE_INDEX - 1 + abs($feed);
}
function add_api_method($name, $sender) {
if ($this->is_system($sender)) {
$this->api_methods[strtolower($name)] = $sender;
}
}
function get_api_method($name) {
return $this->api_methods[$name];
}
function add_filter_action($sender, $action_name, $action_desc) {
$sender_class = get_class($sender);
if (!isset($this->plugin_actions[$sender_class]))
$this->plugin_actions[$sender_class] = array();
array_push($this->plugin_actions[$sender_class],
array("action" => $action_name, "description" => $action_desc, "sender" => $sender));
}
function get_filter_actions() {
return $this->plugin_actions;
}
}

1799
classes/pref/feeds.php Executable file

File diff suppressed because it is too large Load Diff

1251
classes/pref/filters.php Executable file

File diff suppressed because it is too large Load Diff

313
classes/pref/labels.php Normal file
View File

@ -0,0 +1,313 @@
<?php
class Pref_Labels extends Handler_Protected {
function csrf_ignore($method) {
$csrf_ignored = array("index", "getlabeltree", "edit");
return array_search($method, $csrf_ignored) !== false;
}
function edit() {
$label_id = clean($_REQUEST['id']);
$sth = $this->pdo->prepare("SELECT * FROM ttrss_labels2 WHERE
id = ? AND owner_uid = ?");
$sth->execute([$label_id, $_SESSION['uid']]);
if ($line = $sth->fetch()) {
print_hidden("id", "$label_id");
print_hidden("op", "pref-labels");
print_hidden("method", "save");
print "<form onsubmit='return false;'>";
print "<header>".__("Caption")."</header>";
print "<section>";
$fg_color = $line['fg_color'];
$bg_color = $line['bg_color'] ? $line['bg_color'] : '#fff7d5';
print "<input style='font-size : 16px; color : $fg_color; background : $bg_color; transition : background 0.1s linear'
id='labelEdit_caption' name='caption' dojoType='dijit.form.ValidationTextBox'
required='true' value=\"".htmlspecialchars($line['caption'])."\">";
print "</section>";
print "<header>" . __("Colors") . "</header>";
print "<section>";
print "<table>";
print "<tr><th style='text-align : left'>".__("Foreground:")."</th><th style='text-align : left'>".__("Background:")."</th></tr>";
print "<tr><td style='padding-right : 10px'>";
print "<input dojoType='dijit.form.TextBox'
style='display : none' id='labelEdit_fgColor'
name='fg_color' value='$fg_color'>";
print "<input dojoType='dijit.form.TextBox'
style='display : none' id='labelEdit_bgColor'
name='bg_color' value='$bg_color'>";
print "<div dojoType='dijit.ColorPalette'>
<script type='dojo/method' event='onChange' args='fg_color'>
dijit.byId('labelEdit_fgColor').attr('value', fg_color);
dijit.byId('labelEdit_caption').domNode.setStyle({color: fg_color});
</script>
</div>";
print "</td><td>";
print "<div dojoType='dijit.ColorPalette'>
<script type='dojo/method' event='onChange' args='bg_color'>
dijit.byId('labelEdit_bgColor').attr('value', bg_color);
dijit.byId('labelEdit_caption').domNode.setStyle({backgroundColor: bg_color});
</script>
</div>";
print "</td></tr></table>";
print "</section>";
print "<footer>";
print "<button dojoType='dijit.form.Button' type='submit' class='alt-primary' onclick=\"dijit.byId('labelEditDlg').execute()\">".
__('Save')."</button>";
print "<button dojoType='dijit.form.Button' onclick=\"dijit.byId('labelEditDlg').hide()\">".
__('Cancel')."</button>";
print "</footer>";
print "</form>";
}
}
function getlabeltree() {
$root = array();
$root['id'] = 'root';
$root['name'] = __('Labels');
$root['items'] = array();
$sth = $this->pdo->prepare("SELECT *
FROM ttrss_labels2
WHERE owner_uid = ?
ORDER BY caption");
$sth->execute([$_SESSION['uid']]);
while ($line = $sth->fetch()) {
$label = array();
$label['id'] = 'LABEL:' . $line['id'];
$label['bare_id'] = $line['id'];
$label['name'] = $line['caption'];
$label['fg_color'] = $line['fg_color'];
$label['bg_color'] = $line['bg_color'];
$label['type'] = 'label';
$label['checkbox'] = false;
array_push($root['items'], $label);
}
$fl = array();
$fl['identifier'] = 'id';
$fl['label'] = 'name';
$fl['items'] = array($root);
print json_encode($fl);
return;
}
function colorset() {
$kind = clean($_REQUEST["kind"]);
$ids = explode(',', clean($_REQUEST["ids"]));
$color = clean($_REQUEST["color"]);
$fg = clean($_REQUEST["fg"]);
$bg = clean($_REQUEST["bg"]);
foreach ($ids as $id) {
if ($kind == "fg" || $kind == "bg") {
$sth = $this->pdo->prepare("UPDATE ttrss_labels2 SET
${kind}_color = ? WHERE id = ?
AND owner_uid = ?");
$sth->execute([$color, $id, $_SESSION['uid']]);
} else {
$sth = $this->pdo->prepare("UPDATE ttrss_labels2 SET
fg_color = ?, bg_color = ? WHERE id = ?
AND owner_uid = ?");
$sth->execute([$fg, $bg, $id, $_SESSION['uid']]);
}
/* Remove cached data */
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET label_cache = ''
WHERE owner_uid = ?");
$sth->execute([$_SESSION['uid']]);
}
}
function colorreset() {
$ids = explode(',', clean($_REQUEST["ids"]));
foreach ($ids as $id) {
$sth = $this->pdo->prepare("UPDATE ttrss_labels2 SET
fg_color = '', bg_color = '' WHERE id = ?
AND owner_uid = ?");
$sth->execute([$id, $_SESSION['uid']]);
/* Remove cached data */
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET label_cache = ''
WHERE owner_uid = ?");
$sth->execute([$_SESSION['uid']]);
}
}
function save() {
$id = clean($_REQUEST["id"]);
$caption = trim(clean($_REQUEST["caption"]));
$this->pdo->beginTransaction();
$sth = $this->pdo->prepare("SELECT caption FROM ttrss_labels2
WHERE id = ? AND owner_uid = ?");
$sth->execute([$id, $_SESSION['uid']]);
if ($row = $sth->fetch()) {
$old_caption = $row["caption"];
$sth = $this->pdo->prepare("SELECT id FROM ttrss_labels2
WHERE caption = ? AND owner_uid = ?");
$sth->execute([$caption, $_SESSION['uid']]);
if (!$sth->fetch()) {
if ($caption) {
$sth = $this->pdo->prepare("UPDATE ttrss_labels2 SET
caption = ? WHERE id = ? AND
owner_uid = ?");
$sth->execute([$caption, $id, $_SESSION['uid']]);
/* Update filters that reference label being renamed */
$sth = $this->pdo->prepare("UPDATE ttrss_filters2_actions SET
action_param = ? WHERE action_param = ?
AND action_id = 7
AND filter_id IN (SELECT id FROM ttrss_filters2 WHERE owner_uid = ?)");
$sth->execute([$caption, $old_caption, $_SESSION['uid']]);
print clean($_REQUEST["value"]);
} else {
print $old_caption;
}
} else {
print $old_caption;
}
}
$this->pdo->commit();
}
function remove() {
$ids = explode(",", clean($_REQUEST["ids"]));
foreach ($ids as $id) {
Labels::remove($id, $_SESSION["uid"]);
}
}
function add() {
$caption = clean($_REQUEST["caption"]);
$output = clean($_REQUEST["output"]);
if ($caption) {
if (Labels::create($caption)) {
if (!$output) {
print T_sprintf("Created label <b>%s</b>", htmlspecialchars($caption));
}
}
if ($output == "select") {
header("Content-Type: text/xml");
print "<rpc-reply><payload>";
print_label_select("select_label",
$caption, "");
print "</payload></rpc-reply>";
}
}
return;
}
function index() {
print "<div dojoType='dijit.layout.BorderContainer' gutters='false'>";
print "<div style='padding : 0px' dojoType='dijit.layout.ContentPane' region='top'>";
print "<div dojoType='dijit.Toolbar'>";
print "<div dojoType='dijit.form.DropDownButton'>".
"<span>" . __('Select')."</span>";
print "<div dojoType=\"dijit.Menu\" style=\"display: none;\">";
print "<div onclick=\"dijit.byId('labelTree').model.setAllChecked(true)\"
dojoType=\"dijit.MenuItem\">".__('All')."</div>";
print "<div onclick=\"dijit.byId('labelTree').model.setAllChecked(false)\"
dojoType=\"dijit.MenuItem\">".__('None')."</div>";
print "</div></div>";
print"<button dojoType=\"dijit.form.Button\" onclick=\"CommonDialogs.addLabel()\">".
__('Create label')."</button dojoType=\"dijit.form.Button\"> ";
print "<button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('labelTree').removeSelected()\">".
__('Remove')."</button dojoType=\"dijit.form.Button\"> ";
print "<button dojoType=\"dijit.form.Button\" onclick=\"dijit.byId('labelTree').resetColors()\">".
__('Clear colors')."</button dojoType=\"dijit.form.Button\">";
print "</div>"; #toolbar
print "</div>"; #pane
print "<div style='padding : 0px' dojoType=\"dijit.layout.ContentPane\" region=\"center\">";
print "<div id=\"labellistLoading\">
<img src='images/indicator_tiny.gif'>".
__("Loading, please wait...")."</div>";
print "<div dojoType=\"dojo.data.ItemFileWriteStore\" jsId=\"labelStore\"
url=\"backend.php?op=pref-labels&method=getlabeltree\">
</div>
<div dojoType=\"lib.CheckBoxStoreModel\" jsId=\"labelModel\" store=\"labelStore\"
query=\"{id:'root'}\" rootId=\"root\"
childrenAttrs=\"items\" checkboxStrict=\"false\" checkboxAll=\"false\">
</div>
<div dojoType=\"fox.PrefLabelTree\" id=\"labelTree\"
model=\"labelModel\" openOnClick=\"true\">
<script type=\"dojo/method\" event=\"onLoad\" args=\"item\">
Element.hide(\"labellistLoading\");
</script>
<script type=\"dojo/method\" event=\"onClick\" args=\"item\">
var id = String(item.id);
var bare_id = id.substr(id.indexOf(':')+1);
if (id.match('LABEL:')) {
dijit.byId('labelTree').editLabel(bare_id);
}
</script>
</div>";
print "</div>"; #pane
PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB,
"hook_prefs_tab", "prefLabels");
print "</div>"; #container
}
}

1120
classes/pref/prefs.php Normal file

File diff suppressed because it is too large Load Diff

104
classes/pref/system.php Normal file
View File

@ -0,0 +1,104 @@
<?php
class Pref_System extends Handler_Protected {
function before($method) {
if (parent::before($method)) {
if ($_SESSION["access_level"] < 10) {
print __("Your access level is insufficient to open this tab.");
return false;
}
return true;
}
return false;
}
function csrf_ignore($method) {
$csrf_ignored = array("index");
return array_search($method, $csrf_ignored) !== false;
}
function clearLog() {
$this->pdo->query("DELETE FROM ttrss_error_log");
}
function index() {
print "<div dojoType=\"dijit.layout.AccordionContainer\" region=\"center\">";
print "<div dojoType=\"dijit.layout.AccordionPane\"
title=\"<i class='material-icons'>report</i> ".__('Event Log')."\">";
if (LOG_DESTINATION == "sql") {
$res = $this->pdo->query("SELECT errno, errstr, filename, lineno,
created_at, login, context FROM ttrss_error_log
LEFT JOIN ttrss_users ON (owner_uid = ttrss_users.id)
ORDER BY ttrss_error_log.id DESC
LIMIT 100");
print "<button dojoType=\"dijit.form.Button\"
onclick=\"Helpers.updateEventLog()\">".__('Refresh')."</button> ";
print "&nbsp;<button dojoType=\"dijit.form.Button\"
class=\"alt-danger\" onclick=\"Helpers.clearEventLog()\">".__('Clear')."</button> ";
print "<p><table width=\"100%\" cellspacing=\"10\" class=\"prefErrorLog\">";
print "<tr class=\"title\">
<td width='5%'>".__("Error")."</td>
<td>".__("Filename")."</td>
<td>".__("Message")."</td>
<td width='5%'>".__("User")."</td>
<td width='5%'>".__("Date")."</td>
</tr>";
while ($line = $res->fetch()) {
print "<tr class=\"errrow\">";
foreach ($line as $k => $v) {
$line[$k] = htmlspecialchars($v);
}
print "<td class='errno'>" . Logger::$errornames[$line["errno"]] . " (" . $line["errno"] . ")</td>";
print "<td class='filename'>" . $line["filename"] . ":" . $line["lineno"] . "</td>";
print "<td class='errstr'>" . $line["errstr"] . "<hr/>" . nl2br($line["context"]) . "</td>";
print "<td class='login'>" . $line["login"] . "</td>";
print "<td class='timestamp'>" .
make_local_datetime(
$line["created_at"], false) . "</td>";
print "</tr>";
}
print "</table>";
} else {
print_notice("Please set LOG_DESTINATION to 'sql' in config.php to enable database logging.");
}
print "</div>";
print "<div dojoType=\"dijit.layout.AccordionPane\"
title=\"<i class='material-icons'>info</i> ".__('PHP Information')."\">";
ob_start();
phpinfo();
$info = ob_get_contents();
ob_end_clean();
print "<div class='phpinfo'>";
print preg_replace( '%^.*<body>(.*)</body>.*$%ms','$1', $info);
print "</div>";
print "</div>";
PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB,
"hook_prefs_tab", "prefSystem");
print "</div>"; #container
}
}

438
classes/pref/users.php Normal file
View File

@ -0,0 +1,438 @@
<?php
class Pref_Users extends Handler_Protected {
function before($method) {
if (parent::before($method)) {
if ($_SESSION["access_level"] < 10) {
print __("Your access level is insufficient to open this tab.");
return false;
}
return true;
}
return false;
}
function csrf_ignore($method) {
$csrf_ignored = array("index", "edit", "userdetails");
return array_search($method, $csrf_ignored) !== false;
}
function edit() {
global $access_level_names;
print "<form id='user_edit_form' onsubmit='return false' dojoType='dijit.form.Form'>";
print '<div dojoType="dijit.layout.TabContainer" style="height : 400px">
<div dojoType="dijit.layout.ContentPane" title="'.__('Edit user').'">';
//print "<form id=\"user_edit_form\" onsubmit='return false' dojoType=\"dijit.form.Form\">";
$id = (int) clean($_REQUEST["id"]);
print_hidden("id", "$id");
print_hidden("op", "pref-users");
print_hidden("method", "editSave");
$sth = $this->pdo->prepare("SELECT * FROM ttrss_users WHERE id = ?");
$sth->execute([$id]);
if ($row = $sth->fetch()) {
$login = $row["login"];
$access_level = $row["access_level"];
$email = $row["email"];
$sel_disabled = ($id == $_SESSION["uid"] || $login == "admin") ? "disabled" : "";
print "<header>".__("User")."</header>";
print "<section>";
if ($sel_disabled) {
print_hidden("login", "$login");
}
print "<fieldset>";
print "<label>" . __("Login:") . "</label>";
print "<input style='font-size : 16px'
dojoType='dijit.form.ValidationTextBox' required='1'
$sel_disabled name='login' value=\"$login\">";
print "</fieldset>";
print "</section>";
print "<header>".__("Authentication")."</header>";
print "<section>";
print "<fieldset>";
print "<label>" . __('Access level: ') . "</label> ";
if (!$sel_disabled) {
print_select_hash("access_level", $access_level, $access_level_names,
"dojoType=\"dijit.form.Select\" $sel_disabled");
} else {
print_select_hash("", $access_level, $access_level_names,
"dojoType=\"dijit.form.Select\" $sel_disabled");
print_hidden("access_level", "$access_level");
}
print "</fieldset>";
print "<fieldset>";
print "<label>" . __("New password:") . "</label> ";
print "<input dojoType='dijit.form.TextBox' type='password' size='20' placeholder='Change password'
name='password'>";
print "</fieldset>";
print "</section>";
print "<header>".__("Options")."</header>";
print "<section>";
print "<fieldset>";
print "<label>" . __("E-mail:") . "</label> ";
print "<input dojoType='dijit.form.TextBox' size='30' name='email'
value=\"$email\">";
print "</fieldset>";
print "</section>";
print "</table>";
}
print '</div>'; #tab
print "<div href=\"backend.php?op=pref-users&method=userdetails&id=$id\"
dojoType=\"dijit.layout.ContentPane\" title=\"".__('User details')."\">";
print '</div>';
print '</div>';
print "<footer>
<button dojoType='dijit.form.Button' class='alt-primary' type='submit' onclick=\"dijit.byId('userEditDlg').execute()\">".
__('Save')."</button>
<button dojoType='dijit.form.Button' onclick=\"dijit.byId('userEditDlg').hide()\">".
__('Cancel')."</button>
</footer>";
print "</form>";
return;
}
function userdetails() {
$id = (int) clean($_REQUEST["id"]);
$sth = $this->pdo->prepare("SELECT login,
".SUBSTRING_FOR_DATE."(last_login,1,16) AS last_login,
access_level,
(SELECT COUNT(int_id) FROM ttrss_user_entries
WHERE owner_uid = id) AS stored_articles,
".SUBSTRING_FOR_DATE."(created,1,16) AS created
FROM ttrss_users
WHERE id = ?");
$sth->execute([$id]);
if ($row = $sth->fetch()) {
print "<table width='100%'>";
$last_login = make_local_datetime(
$row["last_login"], true);
$created = make_local_datetime(
$row["created"], true);
$stored_articles = $row["stored_articles"];
print "<tr><td>".__('Registered')."</td><td>$created</td></tr>";
print "<tr><td>".__('Last logged in')."</td><td>$last_login</td></tr>";
$sth = $this->pdo->prepare("SELECT COUNT(id) as num_feeds FROM ttrss_feeds
WHERE owner_uid = ?");
$sth->execute([$id]);
$row = $sth->fetch();
$num_feeds = $row["num_feeds"];
print "<tr><td>".__('Subscribed feeds count')."</td><td>$num_feeds</td></tr>";
print "<tr><td>".__('Stored articles')."</td><td>$stored_articles</td></tr>";
print "</table>";
print "<h1>".__('Subscribed feeds')."</h1>";
$sth = $this->pdo->prepare("SELECT id,title,site_url FROM ttrss_feeds
WHERE owner_uid = ? ORDER BY title");
$sth->execute([$id]);
print "<ul class=\"panel panel-scrollable list list-unstyled\">";
while ($line = $sth->fetch()) {
$icon_file = ICONS_URL."/".$line["id"].".ico";
if (file_exists($icon_file) && filesize($icon_file) > 0) {
$feed_icon = "<img class=\"icon\" src=\"$icon_file\">";
} else {
$feed_icon = "<img class=\"icon\" src=\"images/blank_icon.gif\">";
}
print "<li>$feed_icon&nbsp;<a href=\"".$line["site_url"]."\">".$line["title"]."</a></li>";
}
print "</ul>";
} else {
print "<h1>".__('User not found')."</h1>";
}
}
function editSave() {
$login = trim(clean($_REQUEST["login"]));
$uid = clean($_REQUEST["id"]);
$access_level = (int) clean($_REQUEST["access_level"]);
$email = trim(clean($_REQUEST["email"]));
$password = clean($_REQUEST["password"]);
if ($password) {
$salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
$pwd_hash = encrypt_password($password, $salt, true);
$pass_query_part = "pwd_hash = ".$this->pdo->quote($pwd_hash).",
salt = ".$this->pdo->quote($salt).",";
} else {
$pass_query_part = "";
}
$sth = $this->pdo->prepare("UPDATE ttrss_users SET $pass_query_part login = ?,
access_level = ?, email = ?, otp_enabled = false WHERE id = ?");
$sth->execute([$login, $access_level, $email, $uid]);
}
function remove() {
$ids = explode(",", clean($_REQUEST["ids"]));
foreach ($ids as $id) {
if ($id != $_SESSION["uid"] && $id != 1) {
$sth = $this->pdo->prepare("DELETE FROM ttrss_tags WHERE owner_uid = ?");
$sth->execute([$id]);
$sth = $this->pdo->prepare("DELETE FROM ttrss_feeds WHERE owner_uid = ?");
$sth->execute([$id]);
$sth = $this->pdo->prepare("DELETE FROM ttrss_users WHERE id = ?");
$sth->execute([$id]);
}
}
}
function add() {
$login = trim(clean($_REQUEST["login"]));
$tmp_user_pwd = make_password();
$salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
$pwd_hash = encrypt_password($tmp_user_pwd, $salt, true);
if (!$login) return; // no blank usernames
$sth = $this->pdo->prepare("SELECT id FROM ttrss_users WHERE
login = ?");
$sth->execute([$login]);
if (!$sth->fetch()) {
$sth = $this->pdo->prepare("INSERT INTO ttrss_users
(login,pwd_hash,access_level,last_login,created, salt)
VALUES (?, ?, 0, null, NOW(), ?)");
$sth->execute([$login, $pwd_hash, $salt]);
$sth = $this->pdo->prepare("SELECT id FROM ttrss_users WHERE
login = ? AND pwd_hash = ?");
$sth->execute([$login, $pwd_hash]);
if ($row = $sth->fetch()) {
$new_uid = $row['id'];
print T_sprintf("Added user %s with password %s",
$login, $tmp_user_pwd);
initialize_user($new_uid);
} else {
print T_sprintf("Could not create user %s", $login);
}
} else {
print T_sprintf("User %s already exists.", $login);
}
}
static function resetUserPassword($uid, $format_output = false) {
$pdo = Db::pdo();
$sth = $pdo->prepare("SELECT login FROM ttrss_users WHERE id = ?");
$sth->execute([$uid]);
if ($row = $sth->fetch()) {
$login = $row["login"];
$new_salt = substr(bin2hex(get_random_bytes(125)), 0, 250);
$tmp_user_pwd = make_password();
$pwd_hash = encrypt_password($tmp_user_pwd, $new_salt, true);
$sth = $pdo->prepare("UPDATE ttrss_users
SET pwd_hash = ?, salt = ?, otp_enabled = false
WHERE id = ?");
$sth->execute([$pwd_hash, $new_salt, $uid]);
$message = T_sprintf("Changed password of user %s to %s", "<strong>$login</strong>", "<strong>$tmp_user_pwd</strong>");
if ($format_output)
print_notice($message);
else
print $message;
}
}
function resetPass() {
$uid = clean($_REQUEST["id"]);
Pref_Users::resetUserPassword($uid);
}
function index() {
global $access_level_names;
print "<div dojoType='dijit.layout.BorderContainer' gutters='false'>";
print "<div style='padding : 0px' dojoType='dijit.layout.ContentPane' region='top'>";
print "<div dojoType='dijit.Toolbar'>";
$user_search = trim(clean($_REQUEST["search"]));
if (array_key_exists("search", $_REQUEST)) {
$_SESSION["prefs_user_search"] = $user_search;
} else {
$user_search = $_SESSION["prefs_user_search"];
}
print "<div style='float : right; padding-right : 4px;'>
<input dojoType='dijit.form.TextBox' id='user_search' size='20' type='search'
value=\"$user_search\">
<button dojoType='dijit.form.Button' onclick='Users.reload()'>".
__('Search')."</button>
</div>";
$sort = clean($_REQUEST["sort"]);
if (!$sort || $sort == "undefined") {
$sort = "login";
}
print "<div dojoType='dijit.form.DropDownButton'>".
"<span>" . __('Select')."</span>";
print "<div dojoType='dijit.Menu' style='display: none'>";
print "<div onclick=\"Tables.select('prefUserList', true)\"
dojoType='dijit.MenuItem'>".__('All')."</div>";
print "<div onclick=\"Tables.select('prefUserList', false)\"
dojoType='dijit.MenuItem'>".__('None')."</div>";
print "</div></div>";
print "<button dojoType='dijit.form.Button' onclick='Users.add()'>".__('Create user')."</button>";
print "
<button dojoType='dijit.form.Button' onclick='Users.editSelected()'>".
__('Edit')."</button dojoType=\"dijit.form.Button\">
<button dojoType='dijit.form.Button' onclick='Users.removeSelected()'>".
__('Remove')."</button dojoType=\"dijit.form.Button\">
<button dojoType='dijit.form.Button' onclick='Users.resetSelected()'>".
__('Reset password')."</button dojoType=\"dijit.form.Button\">";
PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB_SECTION,
"hook_prefs_tab_section", "prefUsersToolbar");
print "</div>"; #toolbar
print "</div>"; #pane
print "<div style='padding : 0px' dojoType='dijit.layout.ContentPane' region='center'>";
$sort = validate_field($sort,
["login", "access_level", "created", "num_feeds", "created", "last_login"], "login");
if ($sort != "login") $sort = "$sort DESC";
$sth = $this->pdo->prepare("SELECT
tu.id,
login,access_level,email,
".SUBSTRING_FOR_DATE."(last_login,1,16) as last_login,
".SUBSTRING_FOR_DATE."(created,1,16) as created,
(SELECT COUNT(id) FROM ttrss_feeds WHERE owner_uid = tu.id) AS num_feeds
FROM
ttrss_users tu
WHERE
(:search = '' OR login LIKE :search) AND tu.id > 0
ORDER BY $sort");
$sth->execute([":search" => $user_search ? "%$user_search%" : ""]);
print "<p><table width='100%' cellspacing='0' class='prefUserList' id='prefUserList'>";
print "<tr class='title'>
<td align='center' width='5%'>&nbsp;</td>
<td width='20%'><a href='#' onclick=\"Users.reload('login')\">".__('Login')."</a></td>
<td width='20%'><a href='#' onclick=\"Users.reload('access_level')\">".__('Access Level')."</a></td>
<td width='10%'><a href='#' onclick=\"Users.reload('num_feeds')\">".__('Subscribed feeds')."</a></td>
<td width='20%'><a href='#' onclick=\"Users.reload('created')\">".__('Registered')."</a></td>
<td width='20%'><a href='#' onclick=\"Users.reload('last_login')\">".__('Last login')."</a></td></tr>";
$lnum = 0;
while ($line = $sth->fetch()) {
$uid = $line["id"];
print "<tr data-row-id='$uid' onclick='Users.edit($uid)'>";
$line["login"] = htmlspecialchars($line["login"]);
$line["created"] = make_local_datetime($line["created"], false);
$line["last_login"] = make_local_datetime($line["last_login"], false);
print "<td align='center'><input onclick='Tables.onRowChecked(this); event.stopPropagation();'
dojoType='dijit.form.CheckBox' type='checkbox'></td>";
print "<td title='".__('Click to edit')."'><i class='material-icons'>person</i> " . $line["login"] . "</td>";
print "<td>" . $access_level_names[$line["access_level"]] . "</td>";
print "<td>" . $line["num_feeds"] . "</td>";
print "<td>" . $line["created"] . "</td>";
print "<td>" . $line["last_login"] . "</td>";
print "</tr>";
++$lnum;
}
print "</table>";
if ($lnum == 0) {
if (!$user_search) {
print_warning(__('No users defined.'));
} else {
print_warning(__('No matching users found.'));
}
}
print "</div>"; #pane
PluginHost::getInstance()->run_hooks(PluginHost::HOOK_PREFS_TAB,
"hook_prefs_tab", "prefUsers");
print "</div>"; #container
}
}

605
classes/rpc.php Executable file
View File

@ -0,0 +1,605 @@
<?php
class RPC extends Handler_Protected {
function csrf_ignore($method) {
$csrf_ignored = array("sanitycheck", "completelabels", "saveprofile");
return array_search($method, $csrf_ignored) !== false;
}
function setprofile() {
$_SESSION["profile"] = (int) clean($_REQUEST["id"]);
// default value
if (!$_SESSION["profile"]) $_SESSION["profile"] = null;
}
function remprofiles() {
$ids = explode(",", trim(clean($_REQUEST["ids"])));
foreach ($ids as $id) {
if ($_SESSION["profile"] != $id) {
$sth = $this->pdo->prepare("DELETE FROM ttrss_settings_profiles WHERE id = ? AND
owner_uid = ?");
$sth->execute([$id, $_SESSION['uid']]);
}
}
}
// Silent
function addprofile() {
$title = trim(clean($_REQUEST["title"]));
if ($title) {
$this->pdo->beginTransaction();
$sth = $this->pdo->prepare("SELECT id FROM ttrss_settings_profiles
WHERE title = ? AND owner_uid = ?");
$sth->execute([$title, $_SESSION['uid']]);
if (!$sth->fetch()) {
$sth = $this->pdo->prepare("INSERT INTO ttrss_settings_profiles (title, owner_uid)
VALUES (?, ?)");
$sth->execute([$title, $_SESSION['uid']]);
$sth = $this->pdo->prepare("SELECT id FROM ttrss_settings_profiles WHERE
title = ? AND owner_uid = ?");
$sth->execute([$title, $_SESSION['uid']]);
if ($row = $sth->fetch()) {
$profile_id = $row['id'];
if ($profile_id) {
initialize_user_prefs($_SESSION["uid"], $profile_id);
}
}
}
$this->pdo->commit();
}
}
function saveprofile() {
$id = clean($_REQUEST["id"]);
$title = trim(clean($_REQUEST["value"]));
if ($id == 0) {
print __("Default profile");
return;
}
if ($title) {
$sth = $this->pdo->prepare("UPDATE ttrss_settings_profiles
SET title = ? WHERE id = ? AND
owner_uid = ?");
$sth->execute([$title, $id, $_SESSION['uid']]);
print $title;
}
}
// Silent
function remarchive() {
$ids = explode(",", clean($_REQUEST["ids"]));
$sth = $this->pdo->prepare("DELETE FROM ttrss_archived_feeds WHERE
(SELECT COUNT(*) FROM ttrss_user_entries
WHERE orig_feed_id = :id) = 0 AND
id = :id AND owner_uid = :uid");
foreach ($ids as $id) {
$sth->execute([":id" => $id, ":uid" => $_SESSION['uid']]);
}
}
function addfeed() {
$feed = clean($_REQUEST['feed']);
$cat = clean($_REQUEST['cat']);
$need_auth = isset($_REQUEST['need_auth']);
$login = $need_auth ? clean($_REQUEST['login']) : '';
$pass = $need_auth ? trim(clean($_REQUEST['pass'])) : '';
$rc = Feeds::subscribe_to_feed($feed, $cat, $login, $pass);
print json_encode(array("result" => $rc));
}
function togglepref() {
$key = clean($_REQUEST["key"]);
set_pref($key, !get_pref($key));
$value = get_pref($key);
print json_encode(array("param" =>$key, "value" => $value));
}
function setpref() {
// set_pref escapes input, so no need to double escape it here
$key = clean($_REQUEST['key']);
$value = $_REQUEST['value'];
set_pref($key, $value, false, $key != 'USER_STYLESHEET');
print json_encode(array("param" =>$key, "value" => $value));
}
function mark() {
$mark = clean($_REQUEST["mark"]);
$id = clean($_REQUEST["id"]);
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET marked = ?,
last_marked = NOW()
WHERE ref_id = ? AND owner_uid = ?");
$sth->execute([$mark, $id, $_SESSION['uid']]);
print json_encode(array("message" => "UPDATE_COUNTERS"));
}
function delete() {
$ids = explode(",", clean($_REQUEST["ids"]));
$ids_qmarks = arr_qmarks($ids);
$sth = $this->pdo->prepare("DELETE FROM ttrss_user_entries
WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?");
$sth->execute(array_merge($ids, [$_SESSION['uid']]));
Article::purge_orphans();
print json_encode(array("message" => "UPDATE_COUNTERS"));
}
function unarchive() {
$ids = explode(",", clean($_REQUEST["ids"]));
foreach ($ids as $id) {
$this->pdo->beginTransaction();
$sth = $this->pdo->prepare("SELECT feed_url,site_url,title FROM ttrss_archived_feeds
WHERE id = (SELECT orig_feed_id FROM ttrss_user_entries WHERE ref_id = :id
AND owner_uid = :uid) AND owner_uid = :uid");
$sth->execute([":uid" => $_SESSION['uid'], ":id" => $id]);
if ($row = $sth->fetch()) {
$feed_url = $row['feed_url'];
$site_url = $row['site_url'];
$title = $row['title'];
$sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE feed_url = ?
AND owner_uid = ?");
$sth->execute([$feed_url, $_SESSION['uid']]);
if ($row = $sth->fetch()) {
$feed_id = $row["id"];
} else {
if (!$title) $title = '[Unknown]';
$sth = $this->pdo->prepare("INSERT INTO ttrss_feeds
(owner_uid,feed_url,site_url,title,cat_id,auth_login,auth_pass,update_method)
VALUES (?, ?, ?, ?, NULL, '', '', 0)");
$sth->execute([$_SESSION['uid'], $feed_url, $site_url, $title]);
$sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE feed_url = ?
AND owner_uid = ?");
$sth->execute([$feed_url, $_SESSION['uid']]);
if ($row = $sth->fetch()) {
$feed_id = $row['id'];
}
}
if ($feed_id) {
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries
SET feed_id = ?, orig_feed_id = NULL
WHERE ref_id = ? AND owner_uid = ?");
$sth->execute([$feed_id, $id, $_SESSION['uid']]);
}
}
$this->pdo->commit();
}
print json_encode(array("message" => "UPDATE_COUNTERS"));
}
function archive() {
$ids = explode(",", clean($_REQUEST["ids"]));
foreach ($ids as $id) {
$this->archive_article($id, $_SESSION["uid"]);
}
print json_encode(array("message" => "UPDATE_COUNTERS"));
}
private function archive_article($id, $owner_uid) {
$this->pdo->beginTransaction();
if (!$owner_uid) $owner_uid = $_SESSION['uid'];
$sth = $this->pdo->prepare("SELECT feed_id FROM ttrss_user_entries
WHERE ref_id = ? AND owner_uid = ?");
$sth->execute([$id, $owner_uid]);
if ($row = $sth->fetch()) {
/* prepare the archived table */
$feed_id = (int) $row['feed_id'];
if ($feed_id) {
$sth = $this->pdo->prepare("SELECT id FROM ttrss_archived_feeds
WHERE id = ? AND owner_uid = ?");
$sth->execute([$feed_id, $owner_uid]);
if ($row = $sth->fetch()) {
$new_feed_id = $row['id'];
} else {
$row = $this->pdo->query("SELECT MAX(id) AS id FROM ttrss_archived_feeds")->fetch();
$new_feed_id = (int)$row['id'] + 1;
$sth = $this->pdo->prepare("INSERT INTO ttrss_archived_feeds
(id, owner_uid, title, feed_url, site_url, created)
SELECT ?, owner_uid, title, feed_url, site_url, NOW() from ttrss_feeds
WHERE id = ?");
$sth->execute([$new_feed_id, $feed_id]);
}
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries
SET orig_feed_id = ?, feed_id = NULL
WHERE ref_id = ? AND owner_uid = ?");
$sth->execute([$new_feed_id, $id, $owner_uid]);
}
}
$this->pdo->commit();
}
function publ() {
$pub = clean($_REQUEST["pub"]);
$id = clean($_REQUEST["id"]);
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
published = ?, last_published = NOW()
WHERE ref_id = ? AND owner_uid = ?");
$sth->execute([$pub, $id, $_SESSION['uid']]);
print json_encode(array("message" => "UPDATE_COUNTERS"));
}
function getAllCounters() {
@$seq = (int) $_REQUEST['seq'];
$reply = [
'counters' => Counters::getAllCounters(),
'seq' => $seq
];
if ($seq % 2 == 0)
$reply['runtime-info'] = make_runtime_info();
print json_encode($reply);
}
/* GET["cmode"] = 0 - mark as read, 1 - as unread, 2 - toggle */
function catchupSelected() {
$ids = explode(",", clean($_REQUEST["ids"]));
$cmode = (int)clean($_REQUEST["cmode"]);
Article::catchupArticlesById($ids, $cmode);
print json_encode(array("message" => "UPDATE_COUNTERS", "ids" => $ids));
}
function markSelected() {
$ids = explode(",", clean($_REQUEST["ids"]));
$cmode = (int)clean($_REQUEST["cmode"]);
$this->markArticlesById($ids, $cmode);
print json_encode(array("message" => "UPDATE_COUNTERS"));
}
function publishSelected() {
$ids = explode(",", clean($_REQUEST["ids"]));
$cmode = (int)clean($_REQUEST["cmode"]);
$this->publishArticlesById($ids, $cmode);
print json_encode(array("message" => "UPDATE_COUNTERS"));
}
function sanityCheck() {
$_SESSION["hasAudio"] = clean($_REQUEST["hasAudio"]) === "true";
$_SESSION["hasSandbox"] = clean($_REQUEST["hasSandbox"]) === "true";
$_SESSION["hasMp3"] = clean($_REQUEST["hasMp3"]) === "true";
$_SESSION["clientTzOffset"] = clean($_REQUEST["clientTzOffset"]);
$reply = array();
$reply['error'] = sanity_check();
if ($reply['error']['code'] == 0) {
$reply['init-params'] = make_init_params();
$reply['runtime-info'] = make_runtime_info();
}
print json_encode($reply);
}
function completeLabels() {
$search = clean($_REQUEST["search"]);
$sth = $this->pdo->prepare("SELECT DISTINCT caption FROM
ttrss_labels2
WHERE owner_uid = ? AND
LOWER(caption) LIKE LOWER(?) ORDER BY caption
LIMIT 5");
$sth->execute([$_SESSION['uid'], "%$search%"]);
print "<ul>";
while ($line = $sth->fetch()) {
print "<li>" . $line["caption"] . "</li>";
}
print "</ul>";
}
// Silent
function massSubscribe() {
$payload = json_decode(clean($_REQUEST["payload"]), false);
$mode = clean($_REQUEST["mode"]);
if (!$payload || !is_array($payload)) return;
if ($mode == 1) {
foreach ($payload as $feed) {
$title = $feed[0];
$feed_url = $feed[1];
$sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
feed_url = ? AND owner_uid = ?");
$sth->execute([$feed_url, $_SESSION['uid']]);
if (!$sth->fetch()) {
$sth = $this->pdo->prepare("INSERT INTO ttrss_feeds
(owner_uid,feed_url,title,cat_id,site_url)
VALUES (?, ?, ?, NULL, '')");
$sth->execute([$_SESSION['uid'], $feed_url, $title]);
}
}
} else if ($mode == 2) {
// feed archive
foreach ($payload as $id) {
$sth = $this->pdo->prepare("SELECT * FROM ttrss_archived_feeds
WHERE id = ? AND owner_uid = ?");
$sth->execute([$id, $_SESSION['uid']]);
if ($row = $sth->fetch()) {
$site_url = $row['site_url'];
$feed_url = $row['feed_url'];
$title = $row['title'];
$sth = $this->pdo->prepare("SELECT id FROM ttrss_feeds WHERE
feed_url = ? AND owner_uid = ?");
$sth->execute([$feed_url, $_SESSION['uid']]);
if (!$sth->fetch()) {
$sth = $this->pdo->prepare("INSERT INTO ttrss_feeds
(owner_uid,feed_url,title,cat_id,site_url)
VALUES (?, ?, ?, NULL, ?)");
$sth->execute([$_SESSION['uid'], $feed_url, $title, $site_url]);
}
}
}
}
}
function catchupFeed() {
$feed_id = clean($_REQUEST['feed_id']);
$is_cat = clean($_REQUEST['is_cat']) == "true";
$mode = clean($_REQUEST['mode']);
$search_query = clean($_REQUEST['search_query']);
$search_lang = clean($_REQUEST['search_lang']);
Feeds::catchup_feed($feed_id, $is_cat, false, $mode, [$search_query, $search_lang]);
// return counters here synchronously so that frontend can figure out next unread feed properly
print json_encode(['counters' => Counters::getAllCounters()]);
//print json_encode(array("message" => "UPDATE_COUNTERS"));
}
function setpanelmode() {
$wide = (int) clean($_REQUEST["wide"]);
setcookie("ttrss_widescreen", $wide,
time() + COOKIE_LIFETIME_LONG);
print json_encode(array("wide" => $wide));
}
static function updaterandomfeed_real() {
// Test if the feed need a update (update interval exceded).
if (DB_TYPE == "pgsql") {
$update_limit_qpart = "AND ((
ttrss_feeds.update_interval = 0
AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_user_prefs.value || ' minutes') AS INTERVAL)
) OR (
ttrss_feeds.update_interval > 0
AND ttrss_feeds.last_updated < NOW() - CAST((ttrss_feeds.update_interval || ' minutes') AS INTERVAL)
) OR ttrss_feeds.last_updated IS NULL
OR last_updated = '1970-01-01 00:00:00')";
} else {
$update_limit_qpart = "AND ((
ttrss_feeds.update_interval = 0
AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL CONVERT(ttrss_user_prefs.value, SIGNED INTEGER) MINUTE)
) OR (
ttrss_feeds.update_interval > 0
AND ttrss_feeds.last_updated < DATE_SUB(NOW(), INTERVAL ttrss_feeds.update_interval MINUTE)
) OR ttrss_feeds.last_updated IS NULL
OR last_updated = '1970-01-01 00:00:00')";
}
// Test if feed is currently being updated by another process.
if (DB_TYPE == "pgsql") {
$updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < NOW() - INTERVAL '5 minutes')";
} else {
$updstart_thresh_qpart = "AND (ttrss_feeds.last_update_started IS NULL OR ttrss_feeds.last_update_started < DATE_SUB(NOW(), INTERVAL 5 MINUTE))";
}
$random_qpart = sql_random_function();
$pdo = Db::pdo();
// we could be invoked from public.php with no active session
if ($_SESSION["uid"]) {
$owner_check_qpart = "AND ttrss_feeds.owner_uid = ".$pdo->quote($_SESSION["uid"]);
} else {
$owner_check_qpart = "";
}
// We search for feed needing update.
$res = $pdo->query("SELECT ttrss_feeds.feed_url,ttrss_feeds.id
FROM
ttrss_feeds, ttrss_users, ttrss_user_prefs
WHERE
ttrss_feeds.owner_uid = ttrss_users.id
AND ttrss_users.id = ttrss_user_prefs.owner_uid
AND ttrss_user_prefs.pref_name = 'DEFAULT_UPDATE_INTERVAL'
$owner_check_qpart
$update_limit_qpart
$updstart_thresh_qpart
ORDER BY $random_qpart LIMIT 30");
$num_updated = 0;
$tstart = time();
while ($line = $res->fetch()) {
$feed_id = $line["id"];
if (time() - $tstart < ini_get("max_execution_time") * 0.7) {
RSSUtils::update_rss_feed($feed_id, true);
++$num_updated;
} else {
break;
}
}
// Purge orphans and cleanup tags
Article::purge_orphans();
//cleanup_tags(14, 50000);
if ($num_updated > 0) {
print json_encode(array("message" => "UPDATE_COUNTERS",
"num_updated" => $num_updated));
} else {
print json_encode(array("message" => "NOTHING_TO_UPDATE"));
}
}
function updaterandomfeed() {
RPC::updaterandomfeed_real();
}
private function markArticlesById($ids, $cmode) {
$ids_qmarks = arr_qmarks($ids);
if ($cmode == 0) {
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
marked = false, last_marked = NOW()
WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?");
} else if ($cmode == 1) {
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
marked = true, last_marked = NOW()
WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?");
} else {
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
marked = NOT marked,last_marked = NOW()
WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?");
}
$sth->execute(array_merge($ids, [$_SESSION['uid']]));
}
private function publishArticlesById($ids, $cmode) {
$ids_qmarks = arr_qmarks($ids);
if ($cmode == 0) {
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
published = false, last_published = NOW()
WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?");
} else if ($cmode == 1) {
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
published = true, last_published = NOW()
WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?");
} else {
$sth = $this->pdo->prepare("UPDATE ttrss_user_entries SET
published = NOT published,last_published = NOW()
WHERE ref_id IN ($ids_qmarks) AND owner_uid = ?");
}
$sth->execute(array_merge($ids, [$_SESSION['uid']]));
}
function getlinktitlebyid() {
$id = clean($_REQUEST['id']);
$sth = $this->pdo->prepare("SELECT link, title FROM ttrss_entries, ttrss_user_entries
WHERE ref_id = ? AND ref_id = id AND owner_uid = ?");
$sth->execute([$id, $_SESSION['uid']]);
if ($row = $sth->fetch()) {
$link = $row['link'];
$title = $row['title'];
echo json_encode(array("link" => $link, "title" => $title));
} else {
echo json_encode(array("error" => "ARTICLE_NOT_FOUND"));
}
}
function log() {
$msg = clean($_REQUEST['msg']);
$file = basename(clean($_REQUEST['file']));
$line = (int) clean($_REQUEST['line']);
$context = clean($_REQUEST['context']);
if ($msg) {
Logger::get()->log_error(E_USER_WARNING,
$msg, 'client-js:' . $file, $line, $context);
echo json_encode(array("message" => "HOST_ERROR_LOGGED"));
} else {
echo json_encode(array("error" => "MESSAGE_NOT_FOUND"));
}
}
function checkforupdates() {
$rv = [];
if (CHECK_FOR_UPDATES && $_SESSION["access_level"] >= 10) {
$newversion = trim(@fetch_file_contents(["url" => "https://raw.githubusercontent.com/Fmstrat/agriget/master/version"]));
$oldversion = trim(file_get_contents('version'));
if ($newversion != $oldversion) {
$rv["id"] = $newversion;
$rv["newversion"] = $newversion;
$rv["oldversion"] = $oldversion;
$rv["docker"] = file_exists('docker');
}
}
print json_encode($rv);
}
}

1566
classes/rssutils.php Executable file

File diff suppressed because it is too large Load Diff

184
config.php-dist Executable file
View File

@ -0,0 +1,184 @@
<?php
// *******************************************
// *** Database configuration (important!) ***
// *******************************************
define('DB_TYPE', "pgsql"); // or mysql
define('DB_HOST', "localhost");
define('DB_USER', "fox");
define('DB_NAME', "fox");
define('DB_PASS', "XXXXXX");
define('DB_PORT', ''); // usually 5432 for PostgreSQL, 3306 for MySQL
define('MYSQL_CHARSET', 'UTF8');
// Connection charset for MySQL. If you have a legacy database and/or experience
// garbage unicode characters with this option, try setting it to a blank string.
// ***********************************
// *** Basic settings (important!) ***
// ***********************************
define('SELF_URL_PATH', 'http://example.org/tt-rss/');
// Full URL of your tt-rss installation. This should be set to the
// location of tt-rss directory, e.g. http://example.org/tt-rss/
// You need to set this option correctly otherwise several features
// including PUSH, bookmarklets and browser integration will not work properly.
define('SINGLE_USER_MODE', false);
// Operate in single user mode, disables all functionality related to
// multiple users and authentication. Enabling this assumes you have
// your tt-rss directory protected by other means (e.g. http auth).
define('SIMPLE_UPDATE_MODE', false);
// Enables fallback update mode where tt-rss tries to update feeds in
// background while tt-rss is open in your browser.
// If you don't have a lot of feeds and don't want to or can't run
// background processes while not running tt-rss, this method is generally
// viable to keep your feeds up to date.
// Still, there are more robust (and recommended) updating methods
// available, you can read about them here: http://tt-rss.org/wiki/UpdatingFeeds
// *****************************
// *** Files and directories ***
// *****************************
define('PHP_EXECUTABLE', '/usr/bin/php');
// Path to PHP *COMMAND LINE* executable, used for various command-line tt-rss
// programs and update daemon. Do not try to use CGI binary here, it won't work.
// If you see HTTP headers being displayed while running tt-rss scripts,
// then most probably you are using the CGI binary. If you are unsure what to
// put in here, ask your hosting provider.
define('DATA_DIR', 'data');
// Directory for user data, must be writable to the user you run
// daemon process or cronjobs under.
define('LOCK_DIRECTORY', 'data/lock');
// Directory for lockfiles, must be writable to the user you run
// daemon process or cronjobs under.
define('CACHE_DIR', 'data/cache');
// Local cache directory for RSS feed content.
define('ICONS_DIR', "data/feed-icons");
define('ICONS_URL', "data/feed-icons");
// Local and URL path to the directory, where feed favicons are stored.
// Unless you really know what you're doing, please keep those relative
// to tt-rss main directory.
// **********************
// *** Authentication ***
// **********************
// Please see PLUGINS below to configure various authentication modules.
define('AUTH_AUTO_CREATE', true);
// Allow authentication modules to auto-create users in tt-rss internal
// database when authenticated successfully.
define('AUTH_AUTO_LOGIN', true);
// Automatically login user on remote or other kind of externally supplied
// authentication, otherwise redirect to login form as normal.
// If set to true, users won't be able to set application language
// and settings profile.
// *********************
// *** Feed settings ***
// *********************
define('FORCE_ARTICLE_PURGE', 0);
// When this option is not 0, users ability to control feed purging
// intervals is disabled and all articles (which are not starred)
// older than this amount of days are purged.
// ****************************
// *** Sphinx search plugin ***
// ****************************
define('SPHINX_SERVER', 'localhost:9312');
// Hostname:port combination for the Sphinx server.
define('SPHINX_INDEX', 'ttrss, delta');
// Index name in Sphinx configuration. You can specify multiple indexes
// as a comma-separated string.
// Example configuration files are available on tt-rss wiki.
// ***********************************
// *** Self-registrations by users ***
// ***********************************
define('ENABLE_REGISTRATION', false);
// Allow users to register themselves. Please be aware that allowing
// random people to access your tt-rss installation is a security risk
// and potentially might lead to data loss or server exploit. Disabled
// by default.
define('REG_NOTIFY_ADDRESS', 'user@your.domain.dom');
// Email address to send new user notifications to.
define('REG_MAX_USERS', 10);
// Maximum amount of users which will be allowed to register on this
// system. 0 - no limit.
// **********************************
// *** Cookies and login sessions ***
// **********************************
define('SESSION_COOKIE_LIFETIME', 86400);
// Default lifetime of a session (e.g. login) cookie. In seconds,
// 0 means cookie will be deleted when browser closes.
// *********************************
// *** Email and digest settings ***
// *********************************
// Tiny Tiny RSS sends mail via PHP mail() function, unless handled
// by a plugin.
// If you need SMTP support, take a look here:
// https://git.tt-rss.org/fox/ttrss-mailer-smtp
define('SMTP_FROM_NAME', 'Tiny Tiny RSS');
define('SMTP_FROM_ADDRESS', 'noreply@your.domain.dom');
// Name, address and subject for sending outgoing mail. This applies
// to password reset notifications, digest emails and any other mail.
define('DIGEST_SUBJECT', '[tt-rss] New headlines for last 24 hours');
// Subject line for email digests
// ***************************************
// *** Other settings (less important) ***
// ***************************************
define('CHECK_FOR_UPDATES', true);
// Check for updates automatically if running Git version
define('ENABLE_GZIP_OUTPUT', false);
// Selectively gzip output to improve wire performance. This requires
// PHP Zlib extension on the server.
// Enabling this can break tt-rss in several httpd/php configurations,
// if you experience weird errors and tt-rss failing to start, blank pages
// after login, or content encoding errors, disable it.
define('PLUGINS', 'auth_internal, note, toggle_sidebar, bookmarklets, close_button');
// Comma-separated list of plugins to load automatically for all users.
// System plugins have to be specified here. Please enable at least one
// authentication plugin here (auth_*).
// Users may enable other user plugins from Preferences/Plugins but may not
// disable plugins specified in this list.
// Disabling auth_internal in this list would automatically disable
// reset password link on the login form.
define('LOG_DESTINATION', 'sql');
// Error log destination to use. Possible values: sql (uses internal logging
// you can read in Preferences -> System), syslog - logs to system log.
// Setting this to blank uses PHP logging (usually to http server
// error.log).
// Note that feed updating daemons don't use this logging facility
// for normal output.
define('CONFIG_VERSION', 26);
// Expected config version. Please update this option in config.php
// if necessary (after migrating all new options from this file).
// vim:ft=php

180
config.test Normal file
View File

@ -0,0 +1,180 @@
<?php
// *******************************************
// *** Database configuration (important!) ***
// *******************************************
define('DB_TYPE', "pgsql"); // or mysql
define('DB_HOST', "localhost");
define('DB_USER', "fox");
define('DB_NAME', "fox");
define('DB_PASS', "XXXXXX");
define('DB_PORT', ''); // usually 5432 for PostgreSQL, 3306 for MySQL
define('MYSQL_CHARSET', 'UTF8');
// Connection charset for MySQL. If you have a legacy database and/or experience
// garbage unicode characters with this option, try setting it to a blank string.
// ***********************************
// *** Basic settings (important!) ***
// ***********************************
define('SELF_URL_PATH', 'http://example.org/tt-rss/');
// Full URL of your tt-rss installation. This should be set to the
// location of tt-rss directory, e.g. http://example.org/tt-rss/
// You need to set this option correctly otherwise several features
// including PUSH, bookmarklets and browser integration will not work properly.
define('SINGLE_USER_MODE', false);
// Operate in single user mode, disables all functionality related to
// multiple users and authentication. Enabling this assumes you have
// your tt-rss directory protected by other means (e.g. http auth).
define('SIMPLE_UPDATE_MODE', false);
// Enables fallback update mode where tt-rss tries to update feeds in
// background while tt-rss is open in your browser.
// If you don't have a lot of feeds and don't want to or can't run
// background processes while not running tt-rss, this method is generally
// viable to keep your feeds up to date.
// Still, there are more robust (and recommended) updating methods
// available, you can read about them here: http://tt-rss.org/wiki/UpdatingFeeds
// *****************************
// *** Files and directories ***
// *****************************
define('PHP_EXECUTABLE', '/usr/bin/php');
// Path to PHP *COMMAND LINE* executable, used for various command-line tt-rss
// programs and update daemon. Do not try to use CGI binary here, it won't work.
// If you see HTTP headers being displayed while running tt-rss scripts,
// then most probably you are using the CGI binary. If you are unsure what to
// put in here, ask your hosting provider.
define('LOCK_DIRECTORY', 'lock');
// Directory for lockfiles, must be writable to the user you run
// daemon process or cronjobs under.
define('CACHE_DIR', 'cache');
// Local cache directory for RSS feed content.
define('ICONS_DIR', "feed-icons");
define('ICONS_URL', "feed-icons");
// Local and URL path to the directory, where feed favicons are stored.
// Unless you really know what you're doing, please keep those relative
// to tt-rss main directory.
// **********************
// *** Authentication ***
// **********************
// Please see PLUGINS below to configure various authentication modules.
define('AUTH_AUTO_CREATE', true);
// Allow authentication modules to auto-create users in tt-rss internal
// database when authenticated successfully.
define('AUTH_AUTO_LOGIN', true);
// Automatically login user on remote or other kind of externally supplied
// authentication, otherwise redirect to login form as normal.
// If set to true, users won't be able to set application language
// and settings profile.
// *********************
// *** Feed settings ***
// *********************
define('FORCE_ARTICLE_PURGE', 0);
// When this option is not 0, users ability to control feed purging
// intervals is disabled and all articles (which are not starred)
// older than this amount of days are purged.
// ****************************
// *** Sphinx search plugin ***
// ****************************
define('SPHINX_SERVER', 'localhost:9312');
// Hostname:port combination for the Sphinx server.
define('SPHINX_INDEX', 'ttrss, delta');
// Index name in Sphinx configuration. You can specify multiple indexes
// as a comma-separated string.
// Example configuration files are available on tt-rss wiki.
// ***********************************
// *** Self-registrations by users ***
// ***********************************
define('ENABLE_REGISTRATION', false);
// Allow users to register themselves. Please be aware that allowing
// random people to access your tt-rss installation is a security risk
// and potentially might lead to data loss or server exploit. Disabled
// by default.
define('REG_NOTIFY_ADDRESS', 'user@your.domain.dom');
// Email address to send new user notifications to.
define('REG_MAX_USERS', 10);
// Maximum amount of users which will be allowed to register on this
// system. 0 - no limit.
// **********************************
// *** Cookies and login sessions ***
// **********************************
define('SESSION_COOKIE_LIFETIME', 86400);
// Default lifetime of a session (e.g. login) cookie. In seconds,
// 0 means cookie will be deleted when browser closes.
// *********************************
// *** Email and digest settings ***
// *********************************
// Tiny Tiny RSS sends mail via PHP mail() function, unless handled
// by a plugin.
// If you need SMTP support, take a look here:
// https://git.tt-rss.org/fox/ttrss-mailer-smtp
define('SMTP_FROM_NAME', 'Tiny Tiny RSS');
define('SMTP_FROM_ADDRESS', 'noreply@your.domain.dom');
// Name, address and subject for sending outgoing mail. This applies
// to password reset notifications, digest emails and any other mail.
define('DIGEST_SUBJECT', '[tt-rss] New headlines for last 24 hours');
// Subject line for email digests
// ***************************************
// *** Other settings (less important) ***
// ***************************************
define('CHECK_FOR_UPDATES', true);
// Check for updates automatically if running Git version
define('ENABLE_GZIP_OUTPUT', false);
// Selectively gzip output to improve wire performance. This requires
// PHP Zlib extension on the server.
// Enabling this can break tt-rss in several httpd/php configurations,
// if you experience weird errors and tt-rss failing to start, blank pages
// after login, or content encoding errors, disable it.
define('PLUGINS', 'auth_internal, note');
// Comma-separated list of plugins to load automatically for all users.
// System plugins have to be specified here. Please enable at least one
// authentication plugin here (auth_*).
// Users may enable other user plugins from Preferences/Plugins but may not
// disable plugins specified in this list.
// Disabling auth_internal in this list would automatically disable
// reset password link on the login form.
define('LOG_DESTINATION', 'sql');
// Error log destination to use. Possible values: sql (uses internal logging
// you can read in Preferences -> System), syslog - logs to system log.
// Setting this to blank uses PHP logging (usually to http server
// error.log).
// Note that feed updating daemons don't use this logging facility
// for normal output.
define('CONFIG_VERSION', 26);
// Expected config version. Please update this option in config.php
// if necessary (after migrating all new options from this file).
// vim:ft=php

434
css/cdm.less Executable file
View File

@ -0,0 +1,434 @@
.cdm {
i.material-icons {
color : @color-icon;
}
.header, .footer {
display : flex;
flex-direction : row;
flex-wrap : nowrap;
}
.header img, .footer img,
.footer i.material-icons {
margin : 0px 4px;
vertical-align: middle;
}
.header {
align-items : center;
> * {
padding : 4px;
white-space : nowrap;
}
.left, .right {
display : flex;
align-items : center;
i.material-icons {
margin-left : 2px;
padding : 2px;
transition : color 0.2s linear;
user-select: none;
font-size : 21px;
}
}
.titleWrap {
flex-grow : 2;
}
span.updated {
color : @default-text;
font-weight : normal;
font-size : 11px;
white-space : nowrap;
}
input {
margin : 0px 4px;
}
}
.footer {
height : 30px;
padding-left : 5px;
font-weight : normal;
color : @default-text;
clear : both;
align-items : center;
.left {
flex-grow : 2;
}
}
.intermediate {
margin-top : 10px;
margin-left : 10px;
}
.content-inner {
margin : 10px;
line-height : 1.5;
font-size : 16px;
}
.intermediate img,
.intermediate video,
.content-inner img,
.content-inner video {
border-width : 0px;
max-width : 98%;
height : auto;
}
}
.cdm.expanded {
/*margin-top : 4px;
margin-bottom : 4px;*/
.collapse, .excerpt {
display : none;
}
.titleWrap {
white-space : normal;
}
.footer {
border: 0px solid @border-default;
border-bottom-width: 1px;
}
> hr {
margin-top : 0px;
margin-bottom : 0px;
}
}
div.cdm.expanded div.header {
background : transparent ! important;
}
div.cdm.expanded div.header a.title {
font-size : 16px;
color : #999;
font-weight : 600;
transition : color 0.2s, background 0.2s;
text-rendering: optimizelegibility;
font-family : @fonts-ui-bold;
}
div.cdm.expanded.active {
background : white;
}
div.cdm.expanded.active div.header a.title {
color : @color-link;
}
div.cdm.expanded.Unread div.header a.title {
color : black;
}
div.cdm.expanded div.content {
color : @default-text;
}
div.cdm.expanded.Unread div.content {
color : black;
}
div.cdm.active div.content {
color : black;
}
div.cdm.vgrlf .feed {
display : none;
}
.cdm {
div.feed-title {
border: 0px solid @color-link;
border-bottom-width: 1px;
padding: 5px 3px 5px 5px;
}
div.feed-title a.title {
color: @default-text;
font-weight: bold;
}
div.feed-title a {
color: @default-text;
}
div.feed-title a:hover {
color: @color-link;
}
div.header span.feed {
float: right;
font-weight: normal;
font-style: italic;
}
div.header div.feed, div.header div.feed a {
vertical-align: middle;
color: @default-text;
font-weight: normal;
font-style: italic;
font-size: 11px;
}
div.content-inner p {
/*max-width : 650px;*/
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}
div.content-inner iframe {
min-width : 50%;
max-width : 98%;
}
div.header span.author {
white-space : nowrap;
color : @default-text;
font-size : 11px;
font-weight : normal;
}
.feed a {
border-radius : 4px;
display : inline-block;
padding : 1px 4px 1px 4px;
}
}
#main:not(.expandable) div#floatingTitle {
.collapse {
display : none;
}
}
div#floatingTitle {
position : absolute;
z-index : 5;
top : 0px;
right : 0px;
left : 0px;
border: 0px solid @border-default;
border-bottom-width: 1px;
background : white;
color : @default-text;
display : flex;
flex-direction : row;
flex-wrap : nowrap;
box-shadow : 0px 1px 1px -1px rgba(0,0,0,0.1);
align-items: center;
> * {
white-space : nowrap;
padding : 4px;
}
.left, .right {
display : flex;
align-items : center;
i.material-icons {
margin-left : 2px;
font-size : 21px;
padding : 2px;
user-select: none;
}
i.icon-anchor {
margin-left : 0px;
margin-right : 1px; // replaces checkbox which is a bit wider
padding : 0px;
color : #ccc;
cursor : pointer;
}
}
.excerpt {
display : none;
}
.collapse i.material-icons {
color : @color-accent;
cursor : pointer;
}
span.author {
color : @default-text;
font-size : 11px;
font-weight : normal;
}
a.title {
font-size : 16px;
color : #999;
transition : color 0.2s, background 0.2s;
font-weight : 600;
text-rendering: optimizelegibility;
font-family : @fonts-ui-bold;
}
div.feed {
padding-right : 10px;
color : @default-text;
font-weight : normal;
font-style : italic;
font-size : 11px;
white-space : nowrap;
}
div.feed a {
border-radius : 4px;
display : inline-block;
padding : 1px 4px 1px 4px;
}
span.updated {
padding-right : 10px;
white-space : nowrap;
color : @default-text;
font-size : 11px;
}
div.feed a {
color : @default-text;
}
span.titleWrap {
width : 100%;
white-space : normal;
}
.feed-title {
> * {
display : table-cell;
vertical-align : middle;
}
a.title {
width : 100%;
}
a.catchup {
text-align : right;
color : @default-text;
padding-right : 10px;
font-size : 11px;
white-space : nowrap;
}
a.catchup:hover {
color : @color-link;
}
}
}
div#floatingTitle.Unread a.title {
color : black;
}
.cdm.expandable {
background-color : @color-panel-bg;
border: 0px solid @border-default;
border-bottom-width: 1px;
> hr {
display : none;
}
div.header span.titleWrap {
white-space : nowrap;
text-overflow : ellipsis;
overflow : hidden;
}
.excerpt {
white-space : nowrap;
font-size : 11px;
color : #999;
font-weight : normal;
cursor : pointer;
}
}
.cdm.expandable:not(.active) {
user-select : none;
}
.cdm.expandable.Unread {
background : white;
}
.cdm.expandable.Selected:not(.active) {
background : desaturate(@color-accent, 25%);
a,
.header a.title,
span {
color : white;
}
}
.cdm.expandable.active {
background : white ! important;
}
div.cdm.expandable.active div.header span.titleWrap {
white-space : normal;
}
div.cdm.expandable div.header a.title {
font-weight : 600;
color : @default-text;
font-size : 14px;
transition : color 0.2s, background 0.2s;
text-rendering: optimizelegibility;
font-family : @fonts-ui-bold;
}
div.cdm.expandable.Unread div.header a.title {
color : black;
}
div.cdm.expandable.active {
.collapse i.material-icons {
color : @color-accent;
cursor : pointer;
}
.excerpt {
display: none;
}
div.header a.title {
color: @color-link;
font-size: 16px;
font-weight: 600;
text-rendering: optimizelegibility;
font-family: @fonts-ui-bold;
}
}
div.cdm.expandable:not(.active) {
cursor : pointer;
.content, .collapse {
display : none;
}
}

1890
css/default.css Normal file

File diff suppressed because it is too large Load Diff

1
css/default.css.map Normal file

File diff suppressed because one or more lines are too long

4
css/default.less Normal file
View File

@ -0,0 +1,4 @@
@import "defines.less";
@import "dijit_light.less";
@import "zoom.less";
@import "../lib/flat-ttrss/flat_combined.css";

71
css/defines.less Normal file
View File

@ -0,0 +1,71 @@
@fonts-ui-bold: "Segoe WP Semibold", "Segoe UI Semibold", "Segoe UI Web Semibold", "Segoe UI", Ubuntu, "Helvetica Neue", Helvetica, Arial, sans-serif;
@fonts-ui: "Segoe UI", Ubuntu, "Helvetica Neue", Helvetica, Arial, sans-serif;
@default-fg: black;
@default-bg: white;
@color-accent: #257aa7;
@color-accent-light: lighten(@color-accent, 50%);
@color-link: @color-accent;
@color-published: lighten(#ff5718, 10%);
@color-marked: #ffc069;
@color-panel-bg: #f5f5f5;
@color-checked: #69C671;
@border-default : #ddd;
@default-text: #555;
@color-icon: #777;
body.ttrss_main,
body.ttrss_prefs,
#main {
position : absolute;
width: 100%;
height: 100%;
border: 0;
padding: 0;
margin: 0;
}
@import "tt-rss.less";
@import "cdm.less";
@import "prefs.less";
@import "utility.less";
@import "dijit_basic.less";
@font-face {
font-family: 'Material Icons';
font-style: normal;
font-weight: 400;
src: url(../lib/iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
src: local('Material Icons'),
local('MaterialIcons-Regular'),
url(../lib/iconfont/MaterialIcons-Regular.woff2) format('woff2'),
url(../lib/iconfont/MaterialIcons-Regular.woff) format('woff'),
url(../lib/iconfont/MaterialIcons-Regular.ttf) format('truetype');
}
.material-icons {
font-family: 'Material Icons';
font-weight: normal;
font-style: normal;
font-size: 18px; /* Preferred icon size */
display: inline-block;
line-height: 1;
//color : #777;
text-transform: none;
letter-spacing: normal;
word-wrap: normal;
white-space: nowrap;
direction: ltr;
vertical-align: middle;
/* Support for all WebKit browsers. */
-webkit-font-smoothing: antialiased;
/* Support for Safari and Chrome. */
text-rendering: optimizeLegibility;
/* Support for Firefox. */
-moz-osx-font-smoothing: grayscale;
/* Support for IE. */
font-feature-settings: 'liga';
}

161
css/dijit_basic.less Normal file
View File

@ -0,0 +1,161 @@
.flat {
li {
padding: 2px;
}
#feedTree {
.dijitTreeContent .dijitInline {
vertical-align : baseline;
}
}
.dijitButton i.material-icons {
position: relative;
top : -1px;
}
.tabLabel > i.material-icons {
position : relative;
top : -1px;
}
#filterDlg_Matches span.filterRule {
color: green;
}
#filterTree .filterRules li.inverse,
#filterDlg_Matches span.filterRule.inverse {
color: red;
}
.dijitToolbar {
font-size: 13px;
padding: 0px;
}
.dijitAccordionContainer {
box-shadow : 0px 0px 8px rgba(0,0,0,0.1);
}
.dijitCheckBox.dijitCheckBoxChecked {
background-color : @color-checked;
border-color : darken(@color-checked, 10%);
}
.dijitMenu .dijitMenuItem .dijitMenuItemLabel {
padding: 4px 8px;
font-size: 13px;
}
.dijitMenu .dijitMenuItem.dijitDisabled:not(.dijitMenuItemSelected) .dijitMenuItemLabel {
color : lighten(@color-accent, 10%);
}
.dijitMenu .dijitMenuItem td {
padding: 0px;
}
.dijitCheckBox {
margin : 1px;
}
.dijitCheckBox:before {
font-family: "flat-icon";
content: "\f00c";
color: white;
}
.dijitTab,
.dijitAccordionInnerContainer:not(.dijitSelected) {
i.material-icons {
color: @color-accent;
}
}
.dijitTree {
.dijitFolderClosed,
.dijitFolderOpened {
display : none;
}
.dijitTreeRowSelected {
.filterRules li {
color : white;
}
.dijitTreeExpando {
color : @color-accent;
}
}
.dijitTreeNode .dijitTreeRow.dijitTreeRowSelected {
color : white;
}
.dijitTreeRow .dijitTreeExpando {
position : relative;
top : -2px;
}
.labelParam {
float: right;
margin-right: 16px;
}
.dijitTreeRow.filterDisabled {
opacity : 0.5;
.filterRules {
filter : saturate(0%);
}
}
.feedParam {
float: right;
}
.filterRules {
font-size: 12px;
line-height : normal;
white-space: normal;
margin-left : 28px;
li {
color : green;
}
}
.dijitTreeContainer {
max-width : 100%;
}
.dijitTreeRow {
overflow: hidden;
text-overflow: ellipsis;
}
}
label.dijitButton {
border : 1px solid #ccc;
padding : 6px;
border-radius : 4px;
cursor : pointer;
position: relative;
top : 1px;
}
label.dijitButton:hover {
background-color : @color-panel-bg;
}
.dijitTree {
.dijitTreeNode .dijitTreeRow {
padding : 4px 0px 4px;
border-width : 1px;
color : @default-text;
}
}
}

14
css/dijit_light.less Normal file
View File

@ -0,0 +1,14 @@
.flat {
.dijitDialog .dijitDialogPaneContent {
background : @color-panel-bg;
}
.dijitTab:not(.dijitTabChecked) {
background : @color-panel-bg;
}
.dijitCheckBox {
background : #ccc;
}
}

174
css/prefs.less Normal file
View File

@ -0,0 +1,174 @@
body.ttrss_prefs {
background-color : @color-panel-bg;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
h1, h2, h3, h4 {
font-family : @fonts-ui-bold;
font-weight : 600;
color : @default-text;
}
.dijitContentPane {
h1:first-of-type,
h2:first-of-type,
h3:first-of-type {
margin-top: 0px;
}
}
#footer, #header {
padding : 8px;
font-size : 13px;
}
#header {
float : right;
}
#footer_splitter {
display : none;
}
#footer {
background-color : @color-panel-bg;
font-size : 13px;
border : 0px;
text-align : center;
}
#header img {
vertical-align : middle;
cursor : pointer;
}
.dijitTree#filterTree .dijitTreeIcon,
.dijitTree#labelTree .dijitTreeIcon,
.dijitTree#filterTree .dijitTreeIcon {
display : none;
}
.dijitAccordionTitle i.material-icons {
top : -1px;
position : relative;
}
.dijitAccordionTitleSelected i.material-icons {
color : white;
}
.dijitDialog #pref-profiles-list .dijitInlineEditBoxDisplayMode {
padding : 0px;
}
div#feedlistLoading, div#filterlistLoading, div#labellistLoading {
text-align : center;
padding : 5px;
color : @default-text;
}
div#feedlistLoading img, div#filterlistLoading img, div#labellistLoading {
margin-right : 5px;
}
#errorButton {
color : red;
}
.user-css-editor {
height : 300px;
width : 575px;
}
fieldset.prefs {
min-height : 30px;
label:first-of-type {
min-width : 300px;
}
.help-text {
display : inline-block;
margin-left : 10px;
}
}
fieldset.plugin {
label.description {
width : 600px;
margin-right : 150px;
display : inline-block;
.dijitCheckBox {
margin-right : 10px;
}
}
}
table.prefErrorLog tr.errrow td {
font-size : 10px;
}
table.prefErrorLog tr.errrow td.errno {
font-style : italic;
font-weight : bold;
white-space : nowrap;
}
table.prefErrorLog td.filename, table.prefErrorLog td.login, table.prefErrorLog td.timestamp {
color : @default-text;
}
hr {
border-color : #ecf4ff;
max-width : 100%;
}
.phpinfo {
table {
border-collapse : collapse;
}
td.e, td.v {
border : 1px solid #ccc;
}
td.e {
font-weight : bold;
}
td.v {
font-family : monospace;
word-break : break-all;
}
}
}
body.ttrss_prefs,
body.ttrss_utility {
fieldset {
border-width : 0px;
padding : 5px 0px;
}
fieldset.narrow {
padding : 2px 0px;
}
fieldset.align-right {
text-align : right;
}
fieldset > label:first-of-type {
min-width : 140px;
margin-right : 20px;
display : inline-block;
text-align : right;
font-weight : bold;
}
fieldset > label.checkbox {
display : inline;
font-weight : normal;
}
}

1253
css/tt-rss.less Executable file

File diff suppressed because it is too large Load Diff

80
css/updates-night.css Normal file
View File

@ -0,0 +1,80 @@
.grid-content {
grid-area: content;
white-space: normal !important;
width: 475px !important;
color: rgba(255, 255, 255, 0.45) !important;
}
#feed_title {
font-size: 20px !important;
line-height: 32px !important;
color: rgba(255, 255, 255, 0.75) !important;
}
img.img_preview {
width: 130px;
height: 80px;
object-fit: cover;
border-radius: 5px;
border: 1px solid #333333;
}
img.img_card_preview {
width: 180px;
height: 180px;
object-fit: cover;
border-radius: 5px;
border: 1px solid #333333;
}
#slide-out {
visibility: hidden;
position: absolute;
z-index: 900;
top: 0px;
right: 0px;
width: 55%;
height: 100%;
background-color: #000000;
border-radius: 10px 0px 0px 10px;
overflow: auto;
padding: 100px;
}
#slide-out-shadow {
visibility: hidden;
position: absolute;
z-index: 899;
top: 0px;
right: 0px;
width: 100%;
height: 100%;
background-color: #FFFFFF;
opacity: 0.2;
}
.grid-full-title {
font: normal normal bold 30px/34px SansCn !important;
color: rgba(255, 255, 255, 0.75) !important;
}
.grid-title {
font: normal normal bold 20px/24px SansCn !important;
color: rgba(255, 255, 255, 0.5) !important;
}
#content-wrap#content-wrap #floatingTitle.Unread .title,
#content-wrap#content-wrap [data-article-id].cdm.Unread .title,
#content-wrap#content-wrap .hl.Unread .title {
color: rgba(255, 255, 255, 0.9) !important;
}
.active-display {
color: rgba(255, 255, 255, 1) !important;
cursor: pointer;
}
.inactive-display {
color: rgba(255, 255, 255, 0.3) !important;
cursor: pointer;
}

234
css/updates.css Normal file
View File

@ -0,0 +1,234 @@
div.img_preview {
width: 130px;
height: 80px;
padding-right: 20px;
padding-top: 10px;
border-radius: 5px;
}
img.img_preview {
width: 130px;
height: 80px;
object-fit: cover;
border-radius: 5px;
border: 1px solid #DDDDDD;
}
img.img_card_preview {
width: 180px;
height: 180px;
object-fit: cover;
border-radius: 5px;
border: 1px solid #DDDDDD;
}
.grid-container {
display: grid;
grid-template-areas:
'image headline'
'image buttons'
'image content';
grid-gap: 0px;
padding: 0px;
}
.grid-cards-three {
display: grid;
grid-template-columns: 350px 350px 350px;
grid-gap: 0px;
padding: 0px;
grid-auto-flow: row;
justify-content: center;
}
.grid-cards-two {
display: grid;
grid-template-columns: 350px 350px;
grid-gap: 0px;
padding: 0px;
grid-auto-flow: row;
justify-content: center;
}
.grid-cards-one {
display: grid;
grid-template-columns: 350px;
grid-gap: 0px;
padding: 0px;
grid-auto-flow: row;
justify-content: center;
}
.grid-card-container {
display: grid;
grid-template-areas:
'image'
'headline'
'buttons'
'content';
grid-gap: 0px;
padding: 0px;
}
.grid-full-container {
display: grid;
grid-template-areas:
'headline'
'buttons';
grid-gap: 0px;
padding: 0px;
width: 100%;
}
.grid-left {
display: inline !important;
}
.grid-right {
display: inline !important;
float: right !important;
}
#slide-out {
visibility: hidden;
position: absolute;
z-index: 900;
top: 0px;
right: 0px;
width: 55%;
height: 100%;
background-color: #ffffff;
border-radius: 10px 0px 0px 10px;
overflow: auto;
padding: 100px;
}
#slide-out-shadow {
visibility: hidden;
position: absolute;
z-index: 899;
top: 0px;
right: 0px;
width: 100%;
height: 100%;
background-color: #000000;
opacity: 0.4;
}
.cdm {
border: none !important;
padding-top: 10px !important;
padding-bottom: 20px !important;
margin-left: auto !important;
margin-right: auto !important;
}
#feeds-holder {
margin-left: 10px !important;
}
#feedTree {
font-size: 13px !important;
}
.icon-score {
right: unset !important;
position: unset !important;
}
.grid-title {
font: normal normal bold 20px/24px SansCn !important;
}
.grid-full-title {
font: normal normal bold 30px/34px SansCn !important;
color: rgba(0, 0, 0, 0.75) !important;
}
#feed_title {
font-size: 20px !important;
line-height: 32px !important;
color: rgba(0, 0, 0, 0.75) !important;
}
#feed_title a {
color: rgba(0, 0, 0, 0.75) !important;
}
.grid-image {
grid-area: image;
align-self: start;
}
.headline-listing {
width: 475px !important;
}
.grid-headline {
grid-area: headline;
white-space: normal !important;
padding-bottom: 5px;
}
.headline-buttons {
width: 475px !important;
}
.grid-buttons {
grid-area: buttons;
white-space: no-wrap !important;
padding-bottom: 10px;
}
.grid-content {
grid-area: content;
white-space: normal !important;
width: 475px !important;
color: rgba(0, 0, 0, 0.45) !important;
}
.toolbar-hide {
visibility: hidden !important;
}
.dijitMenuPopup {
background: #ffffff !important;
}
.grid-title {
font: normal normal bold 20px/24px SansCn !important;
color: rgba(0, 0, 0, 0.4) !important;
}
#content-wrap#content-wrap #floatingTitle.Unread .title,
#content-wrap#content-wrap [data-article-id].cdm.Unread .title,
#content-wrap#content-wrap .hl.Unread .title {
color: rgba(0, 0, 0, 0.75) !important;
}
.active-display {
color: rgba(0, 0, 0, 1) !important;
cursor: pointer;
}
.inactive-display {
color: rgba(0, 0, 0, 0.3) !important;
cursor: pointer;
}
.view-full {
width: 625px;
}
.view-cards {
width: 300px;
margin-left: unset !important;
margin-right: unset !important;
}
.view-magazine {
width: 625px;
}

116
css/utility.less Normal file
View File

@ -0,0 +1,116 @@
body.ttrss_utility.sanity_failed {
background : #900;
}
body.ttrss_utility {
background : @color-panel-bg;
color : @default-fg;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
margin : 4em;
.content {
background : white;
border : 1px solid #ddd;
padding : 20px;
box-shadow : 0px 1px 1px -1px rgba(0,0,0,0.1);
h2:first-of-type {
margin-top : 0;
}
h2, h3, h4 {
color : @color-accent;
font-family: @fonts-ui-bold;
}
h2 {
font-size : 18px;
}
h3 {
font-size : 16px;
}
}
a {
color : @color-link;
text-decoration : none;
}
a:hover,
a:focus {
color: darken(@color-link, 20%);
text-decoration: underline;
}
h1 {
color : gray;
font-family: @fonts-ui-bold;
font-size : 18px;
margin : 10px 0 0 0;
}
.footer {
text-align : center;
padding-top : 10px;
a {
color : gray;
}
a:hover {
color : @color-accent;
}
}
form {
margin : 0;
}
}
body.ttrss_utility.otp {
.content {
fieldset > label {
display: inline;
}
}
}
body.ttrss_utility.ttrss_login {
margin : 0;
padding : 0;
width : 100%;
height : 100%;
position : absolute;
display : flex;
align-items: center;
justify-content : center;
.container {
max-width : 600px;
margin-left : auto;
margin-right : auto;
.content {
padding : 40px;
}
}
}
body.ttrss_utility.installer,
body.ttrss_utility.feed_debugger {
margin : 2em;
}
body.ttrss_utility.share_popup {
margin : 0;
padding : 0;
background : white;
.content {
padding : 15px;
border-width : 0;
box-shadow : none;
}
}

78
css/zoom.less Normal file
View File

@ -0,0 +1,78 @@
body.ttrss_zoom {
max-width : 900px;
margin : 2em auto;
div.post {
border : 1px solid #ddd;
background : white;
box-shadow : 0px 1px 1px -1px rgba(0,0,0,0.1);
.attachments {
display : none;
}
div.header {
padding-bottom : 10px;
border: 0px solid #eee;
border-bottom-width: 1px;
background : white;
font-size : 12px;
color : #555;
.row {
display : flex;
margin-bottom : 4px;
flex-wrap : nowrap;
align-items : center;
justify-content : space-between;
}
}
p {
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
}
div.content {
font-size : 15px;
line-height : 1.5;
border-width : 0;
padding : 0;
img, video {
max-width : 760px;
height : auto;
}
blockquote {
margin : 5px 0px 5px 0px;
color : @default-text;
padding-left : 10px;
border: 0px solid #ccc;
border-left-width: 4px;
}
code {
color : #009900;
font-family : monospace;
font-size : 12px;
}
pre {
margin : 5px 0px 5px 0px;
padding : 10px;
color : @default-text;
font-family : monospace;
font-size : 12px;
border: 0px solid #ccc;
background : @color-panel-bg;
display : block;
max-width : 98%;
overflow : auto;
}
}
}
}

56
errors.php Normal file
View File

@ -0,0 +1,56 @@
<?php
set_include_path(dirname(__FILE__) ."/include" . PATH_SEPARATOR .
get_include_path());
require_once "functions.php";
$ERRORS[0] = "";
$ERRORS[1] = __("This program requires XmlHttpRequest " .
"to function properly. Your browser doesn't seem to support it.");
$ERRORS[2] = __("This program requires cookies " .
"to function properly. Your browser doesn't seem to support them.");
$ERRORS[3] = __("Backend sanity check failed.");
$ERRORS[4] = __("Frontend sanity check failed.");
$ERRORS[5] = __("Incorrect database schema version. &lt;a href='db-updater.php'&gt;Please update&lt;/a&gt;.");
$ERRORS[6] = __("Request not authorized.");
$ERRORS[7] = __("No operation to perform.");
$ERRORS[8] = __("Could not display feed: query failed. Please check label match syntax or local configuration.");
$ERRORS[8] = __("Denied. Your access level is insufficient to access this page.");
$ERRORS[9] = __("Configuration check failed");
$ERRORS[10] = __("Your version of MySQL is not currently supported. Please see official site for more information.");
$ERRORS[11] = "[This error is not returned by server]";
$ERRORS[12] = __("SQL escaping test failed, check your database and PHP configuration");
$ERRORS[13] = __("Method not found");
$ERRORS[14] = __("Plugin not found");
$ERRORS[15] = __("Encoding data as JSON failed");
if ($_REQUEST['mode'] == 'js') {
header("Content-Type: text/javascript; charset=UTF-8");
print "var ERRORS = [];\n";
foreach ($ERRORS as $id => $error) {
$error = preg_replace("/\n/", "", $error);
$error = preg_replace("/\"/", "\\\"", $error);
print "ERRORS[$id] = \"$error\";\n";
}
}
?>

0
feed-icons/.empty Executable file
View File

0
feed-icons/index.html Normal file
View File

BIN
images/blank_icon.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 B

BIN
images/favicon-72px.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

BIN
images/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

BIN
images/indicator_tiny.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 723 B

BIN
images/indicator_white.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

BIN
images/information.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 778 B

BIN
images/logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

BIN
images/logo_small.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.6 KiB

26
include/autoload.php Normal file
View File

@ -0,0 +1,26 @@
<?php
require_once "functions.php";
spl_autoload_register(function($class) {
$namespace = '';
$class_name = $class;
if (strpos($class, '\\') !== FALSE)
list ($namespace, $class_name) = explode('\\', $class, 2);
$root_dir = dirname(__DIR__); // we're in tt-rss/include
// 1. third party libraries with namespaces are loaded from vendor/
// 2. internal tt-rss classes are loaded from classes/ and use special naming logic instead of namespaces
// 3. plugin classes are loaded by PluginHandler from plugins.local/ and plugins/ (TODO: use generic autoloader?)
if ($namespace && $class_name) {
$class_file = "$root_dir/vendor/$namespace/" . str_replace('\\', '/', $class_name) . ".php";
} else {
$class_file = "$root_dir/classes/" . str_replace("_", "/", strtolower($class)) . ".php";
}
if (file_exists($class_file))
include $class_file;
});

351
include/colors.php Normal file
View File

@ -0,0 +1,351 @@
<?php
if (file_exists("lib/floIcon.php")) {
require_once "lib/floIcon.php";
}
function _resolve_htmlcolor($color) {
$htmlcolors = array ("aliceblue" => "#f0f8ff",
"antiquewhite" => "#faebd7",
"aqua" => "#00ffff",
"aquamarine" => "#7fffd4",
"azure" => "#f0ffff",
"beige" => "#f5f5dc",
"bisque" => "#ffe4c4",
"black" => "#000000",
"blanchedalmond" => "#ffebcd",
"blue" => "#0000ff",
"blueviolet" => "#8a2be2",
"brown" => "#a52a2a",
"burlywood" => "#deb887",
"cadetblue" => "#5f9ea0",
"chartreuse" => "#7fff00",
"chocolate" => "#d2691e",
"coral" => "#ff7f50",
"cornflowerblue" => "#6495ed",
"cornsilk" => "#fff8dc",
"crimson" => "#dc143c",
"cyan" => "#00ffff",
"darkblue" => "#00008b",
"darkcyan" => "#008b8b",
"darkgoldenrod" => "#b8860b",
"darkgray" => "#a9a9a9",
"darkgrey" => "#a9a9a9",
"darkgreen" => "#006400",
"darkkhaki" => "#bdb76b",
"darkmagenta" => "#8b008b",
"darkolivegreen" => "#556b2f",
"darkorange" => "#ff8c00",
"darkorchid" => "#9932cc",
"darkred" => "#8b0000",
"darksalmon" => "#e9967a",
"darkseagreen" => "#8fbc8f",
"darkslateblue" => "#483d8b",
"darkslategray" => "#2f4f4f",
"darkslategrey" => "#2f4f4f",
"darkturquoise" => "#00ced1",
"darkviolet" => "#9400d3",
"deeppink" => "#ff1493",
"deepskyblue" => "#00bfff",
"dimgray" => "#696969",
"dimgrey" => "#696969",
"dodgerblue" => "#1e90ff",
"firebrick" => "#b22222",
"floralwhite" => "#fffaf0",
"forestgreen" => "#228b22",
"fuchsia" => "#ff00ff",
"gainsboro" => "#dcdcdc",
"ghostwhite" => "#f8f8ff",
"gold" => "#ffd700",
"goldenrod" => "#daa520",
"gray" => "#808080",
"grey" => "#808080",
"green" => "#008000",
"greenyellow" => "#adff2f",
"honeydew" => "#f0fff0",
"hotpink" => "#ff69b4",
"indianred " => "#cd5c5c",
"indigo " => "#4b0082",
"ivory" => "#fffff0",
"khaki" => "#f0e68c",
"lavender" => "#e6e6fa",
"lavenderblush" => "#fff0f5",
"lawngreen" => "#7cfc00",
"lemonchiffon" => "#fffacd",
"lightblue" => "#add8e6",
"lightcoral" => "#f08080",
"lightcyan" => "#e0ffff",
"lightgoldenrodyellow" => "#fafad2",
"lightgray" => "#d3d3d3",
"lightgrey" => "#d3d3d3",
"lightgreen" => "#90ee90",
"lightpink" => "#ffb6c1",
"lightsalmon" => "#ffa07a",
"lightseagreen" => "#20b2aa",
"lightskyblue" => "#87cefa",
"lightslategray" => "#778899",
"lightslategrey" => "#778899",
"lightsteelblue" => "#b0c4de",
"lightyellow" => "#ffffe0",
"lime" => "#00ff00",
"limegreen" => "#32cd32",
"linen" => "#faf0e6",
"magenta" => "#ff00ff",
"maroon" => "#800000",
"mediumaquamarine" => "#66cdaa",
"mediumblue" => "#0000cd",
"mediumorchid" => "#ba55d3",
"mediumpurple" => "#9370db",
"mediumseagreen" => "#3cb371",
"mediumslateblue" => "#7b68ee",
"mediumspringgreen" => "#00fa9a",
"mediumturquoise" => "#48d1cc",
"mediumvioletred" => "#c71585",
"midnightblue" => "#191970",
"mintcream" => "#f5fffa",
"mistyrose" => "#ffe4e1",
"moccasin" => "#ffe4b5",
"navajowhite" => "#ffdead",
"navy" => "#000080",
"oldlace" => "#fdf5e6",
"olive" => "#808000",
"olivedrab" => "#6b8e23",
"orange" => "#ffa500",
"orangered" => "#ff4500",
"orchid" => "#da70d6",
"palegoldenrod" => "#eee8aa",
"palegreen" => "#98fb98",
"paleturquoise" => "#afeeee",
"palevioletred" => "#db7093",
"papayawhip" => "#ffefd5",
"peachpuff" => "#ffdab9",
"peru" => "#cd853f",
"pink" => "#ffc0cb",
"plum" => "#dda0dd",
"powderblue" => "#b0e0e6",
"purple" => "#800080",
"red" => "#ff0000",
"rosybrown" => "#bc8f8f",
"royalblue" => "#4169e1",
"saddlebrown" => "#8b4513",
"salmon" => "#fa8072",
"sandybrown" => "#f4a460",
"seagreen" => "#2e8b57",
"seashell" => "#fff5ee",
"sienna" => "#a0522d",
"silver" => "#c0c0c0",
"skyblue" => "#87ceeb",
"slateblue" => "#6a5acd",
"slategray" => "#708090",
"slategrey" => "#708090",
"snow" => "#fffafa",
"springgreen" => "#00ff7f",
"steelblue" => "#4682b4",
"tan" => "#d2b48c",
"teal" => "#008080",
"thistle" => "#d8bfd8",
"tomato" => "#ff6347",
"turquoise" => "#40e0d0",
"violet" => "#ee82ee",
"wheat" => "#f5deb3",
"white" => "#ffffff",
"whitesmoke" => "#f5f5f5",
"yellow" => "#ffff00",
"yellowgreen" => "#9acd32");
$color = strtolower($color);
if (isset($htmlcolors[$color]))
return $htmlcolors[$color];
else
return $color;
}
### RGB >> HSL
function _color_rgb2hsl($rgb) {
$r = $rgb[0]; $g = $rgb[1]; $b = $rgb[2];
$min = min($r, min($g, $b)); $max = max($r, max($g, $b));
$delta = $max - $min; $l = ($min + $max) / 2; $s = 0;
if ($l > 0 && $l < 1) {
$s = $delta / ($l < 0.5 ? (2 * $l) : (2 - 2 * $l));
}
$h = 0;
if ($delta > 0) {
if ($max == $r && $max != $g) $h += ($g - $b) / $delta;
if ($max == $g && $max != $b) $h += (2 + ($b - $r) / $delta);
if ($max == $b && $max != $r) $h += (4 + ($r - $g) / $delta);
$h /= 6;
} return array($h, $s, $l);
}
### HSL >> RGB
function _color_hsl2rgb($hsl) {
$h = $hsl[0]; $s = $hsl[1]; $l = $hsl[2];
$m2 = ($l <= 0.5) ? $l * ($s + 1) : $l + $s - $l*$s;
$m1 = $l * 2 - $m2;
return array(_color_hue2rgb($m1, $m2, $h + 0.33333),
_color_hue2rgb($m1, $m2, $h),
_color_hue2rgb($m1, $m2, $h - 0.33333));
}
### Helper function for _color_hsl2rgb().
function _color_hue2rgb($m1, $m2, $h) {
$h = ($h < 0) ? $h + 1 : (($h > 1) ? $h - 1 : $h);
if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
if ($h * 2 < 1) return $m2;
if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (0.66666 - $h) * 6;
return $m1;
}
### Convert a hex color into an RGB triplet.
function _color_unpack($hex, $normalize = false) {
if (strpos($hex, '#') !== 0)
$hex = _resolve_htmlcolor($hex);
if (strlen($hex) == 4) {
$hex = $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];
} $c = hexdec($hex);
for ($i = 16; $i >= 0; $i -= 8) {
$out[] = (($c >> $i) & 0xFF) / ($normalize ? 255 : 1);
} return $out;
}
### Convert an RGB triplet to a hex color.
function _color_pack($rgb, $normalize = false) {
foreach ($rgb as $k => $v) {
$out |= (($v * ($normalize ? 255 : 1)) << (16 - $k * 8));
}return '#'. str_pad(dechex($out), 6, 0, STR_PAD_LEFT);
}
function rgb2hsl($arr) {
$r = $arr[0];
$g = $arr[1];
$b = $arr[2];
$var_R = ($r / 255);
$var_G = ($g / 255);
$var_B = ($b / 255);
$var_Min = min($var_R, $var_G, $var_B);
$var_Max = max($var_R, $var_G, $var_B);
$del_Max = $var_Max - $var_Min;
$v = $var_Max;
if ($del_Max == 0) {
$h = 0;
$s = 0;
} else {
$s = $del_Max / $var_Max;
$del_R = ((($var_Max - $var_R ) / 6 ) + ($del_Max / 2 ) ) / $del_Max;
$del_G = ((($var_Max - $var_G ) / 6 ) + ($del_Max / 2 ) ) / $del_Max;
$del_B = ((($var_Max - $var_B ) / 6 ) + ($del_Max / 2 ) ) / $del_Max;
if ($var_R == $var_Max) $h = $del_B - $del_G;
else if ($var_G == $var_Max) $h = (1 / 3 ) + $del_R - $del_B;
else if ($var_B == $var_Max) $h = (2 / 3 ) + $del_G - $del_R;
if ($h < 0) $h++;
if ($h > 1) $h--;
}
return array($h, $s, $v);
}
function hsl2rgb($arr) {
$h = $arr[0];
$s = $arr[1];
$v = $arr[2];
if($s == 0) {
$r = $g = $B = $v * 255;
} else {
$var_H = $h * 6;
$var_i = floor($var_H );
$var_1 = $v * (1 - $s );
$var_2 = $v * (1 - $s * ($var_H - $var_i ) );
$var_3 = $v * (1 - $s * (1 - ($var_H - $var_i ) ) );
if ($var_i == 0) { $var_R = $v ; $var_G = $var_3 ; $var_B = $var_1 ; }
else if ($var_i == 1) { $var_R = $var_2 ; $var_G = $v ; $var_B = $var_1 ; }
else if ($var_i == 2) { $var_R = $var_1 ; $var_G = $v ; $var_B = $var_3 ; }
else if ($var_i == 3) { $var_R = $var_1 ; $var_G = $var_2 ; $var_B = $v ; }
else if ($var_i == 4) { $var_R = $var_3 ; $var_G = $var_1 ; $var_B = $v ; }
else { $var_R = $v ; $var_G = $var_1 ; $var_B = $var_2 ; }
$r = $var_R * 255;
$g = $var_G * 255;
$B = $var_B * 255;
}
return array($r, $g, $B);
}
function colorPalette($imageFile, $numColors, $granularity = 5) {
$granularity = max(1, abs((int)$granularity));
$colors = array();
$size = @getimagesize($imageFile);
// to enable .ico support place floIcon.php into lib/
if (strtolower($size['mime']) == 'image/vnd.microsoft.icon') {
if (class_exists("floIcon")) {
$ico = new floIcon();
@$ico->readICO($imageFile);
if(count($ico->images)==0)
return false;
else
$img = @$ico->images[count($ico->images)-1]->getImageResource();
} else {
return false;
}
} else if ($size[0] > 0 && $size[1] > 0) {
$img = @imagecreatefromstring(file_get_contents($imageFile));
}
if (!$img) return false;
for($x = 0; $x < $size[0]; $x += $granularity) {
for($y = 0; $y < $size[1]; $y += $granularity) {
$thisColor = imagecolorat($img, $x, $y);
$rgb = imagecolorsforindex($img, $thisColor);
$red = round(round(($rgb['red'] / 0x33)) * 0x33);
$green = round(round(($rgb['green'] / 0x33)) * 0x33);
$blue = round(round(($rgb['blue'] / 0x33)) * 0x33);
$thisRGB = sprintf('%02X%02X%02X', $red, $green, $blue);
if(array_key_exists($thisRGB, $colors)) {
$colors[$thisRGB]++;
} else{
$colors[$thisRGB] = 1;
}
}
}
arsort($colors);
return array_slice(array_keys($colors), 0, $numColors);
}
function calculate_avg_color($iconFile) {
$palette = colorPalette($iconFile, 4, 4);
if (is_array($palette)) {
foreach ($palette as $p) {
$hsl = rgb2hsl(_color_unpack("#$p"));
if ($hsl[1] > 0.25 && $hsl[2] > 0.25 &&
!($hsl[0] >= 0 && $hsl[0] < 0.01 && $hsl[1] < 0.01) &&
!($hsl[0] >= 0 && $hsl[0] < 0.01 && $hsl[2] > 0.99)) {
return _color_pack(hsl2rgb($hsl));
}
}
}
return '';
}

339
include/controls.php Executable file
View File

@ -0,0 +1,339 @@
<?php
function print_select($id, $default, $values, $attributes = "", $name = "") {
if (!$name) $name = $id;
print "<select name=\"$name\" id=\"$id\" $attributes>";
foreach ($values as $v) {
if ($v == $default)
$sel = "selected=\"1\"";
else
$sel = "";
$v = trim($v);
print "<option value=\"$v\" $sel>$v</option>";
}
print "</select>";
}
function print_select_hash($id, $default, $values, $attributes = "", $name = "") {
if (!$name) $name = $id;
print "<select name=\"$name\" id='$id' $attributes>";
foreach (array_keys($values) as $v) {
if ($v == $default)
$sel = 'selected="selected"';
else
$sel = "";
$v = trim($v);
print "<option $sel value=\"$v\">".$values[$v]."</option>";
}
print "</select>";
}
function print_hidden($name, $value) {
print "<input dojoType=\"dijit.form.TextBox\" style=\"display : none\" name=\"$name\" value=\"$value\">";
}
function print_checkbox($id, $checked, $value = "", $attributes = "") {
$checked_str = $checked ? "checked" : "";
$value_str = $value ? "value=\"$value\"" : "";
print "<input dojoType=\"dijit.form.CheckBox\" id=\"$id\" $value_str $checked_str $attributes name=\"$id\">";
}
function print_button($type, $value, $attributes = "") {
print "<p><button dojoType=\"dijit.form.Button\" $attributes type=\"$type\">$value</button>";
}
function print_radio($id, $default, $true_is, $values, $attributes = "") {
foreach ($values as $v) {
if ($v == $default)
$sel = "checked";
else
$sel = "";
if ($v == $true_is) {
$sel .= " value=\"1\"";
} else {
$sel .= " value=\"0\"";
}
print "<input class=\"noborder\" dojoType=\"dijit.form.RadioButton\"
type=\"radio\" $sel $attributes name=\"$id\">&nbsp;$v&nbsp;";
}
}
function print_feed_multi_select($id, $default_ids = [],
$attributes = "", $include_all_feeds = true,
$root_id = null, $nest_level = 0) {
$pdo = DB::pdo();
print_r(in_array("CAT:6",$default_ids));
if (!$root_id) {
print "<select multiple=\true\" id=\"$id\" name=\"$id\" $attributes>";
if ($include_all_feeds) {
$is_selected = (in_array("0", $default_ids)) ? "selected=\"1\"" : "";
print "<option $is_selected value=\"0\">".__('All feeds')."</option>";
}
}
if (get_pref('ENABLE_FEED_CATS')) {
if (!$root_id) $root_id = null;
$sth = $pdo->prepare("SELECT id,title,
(SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
c2.parent_cat = ttrss_feed_categories.id) AS num_children
FROM ttrss_feed_categories
WHERE owner_uid = :uid AND
(parent_cat = :root_id OR (:root_id IS NULL AND parent_cat IS NULL)) ORDER BY title");
$sth->execute([":uid" => $_SESSION['uid'], ":root_id" => $root_id]);
while ($line = $sth->fetch()) {
for ($i = 0; $i < $nest_level; $i++)
$line["title"] = " - " . $line["title"];
$is_selected = in_array("CAT:".$line["id"], $default_ids) ? "selected=\"1\"" : "";
printf("<option $is_selected value='CAT:%d'>%s</option>",
$line["id"], htmlspecialchars($line["title"]));
if ($line["num_children"] > 0)
print_feed_multi_select($id, $default_ids, $attributes,
$include_all_feeds, $line["id"], $nest_level+1);
$f_sth = $pdo->prepare("SELECT id,title FROM ttrss_feeds
WHERE cat_id = ? AND owner_uid = ? ORDER BY title");
$f_sth->execute([$line['id'], $_SESSION['uid']]);
while ($fline = $f_sth->fetch()) {
$is_selected = (in_array($fline["id"], $default_ids)) ? "selected=\"1\"" : "";
$fline["title"] = " + " . $fline["title"];
for ($i = 0; $i < $nest_level; $i++)
$fline["title"] = " - " . $fline["title"];
printf("<option $is_selected value='%d'>%s</option>",
$fline["id"], htmlspecialchars($fline["title"]));
}
}
if (!$root_id) {
$is_selected = in_array("CAT:0", $default_ids) ? "selected=\"1\"" : "";
printf("<option $is_selected value='CAT:0'>%s</option>",
__("Uncategorized"));
$f_sth = $pdo->prepare("SELECT id,title FROM ttrss_feeds
WHERE cat_id IS NULL AND owner_uid = ? ORDER BY title");
$f_sth->execute([$_SESSION['uid']]);
while ($fline = $f_sth->fetch()) {
$is_selected = in_array($fline["id"], $default_ids) ? "selected=\"1\"" : "";
$fline["title"] = " + " . $fline["title"];
for ($i = 0; $i < $nest_level; $i++)
$fline["title"] = " - " . $fline["title"];
printf("<option $is_selected value='%d'>%s</option>",
$fline["id"], htmlspecialchars($fline["title"]));
}
}
} else {
$sth = $pdo->prepare("SELECT id,title FROM ttrss_feeds
WHERE owner_uid = ? ORDER BY title");
$sth->execute([$_SESSION['uid']]);
while ($line = $sth->fetch()) {
$is_selected = (in_array($line["id"], $default_ids)) ? "selected=\"1\"" : "";
printf("<option $is_selected value='%d'>%s</option>",
$line["id"], htmlspecialchars($line["title"]));
}
}
if (!$root_id) {
print "</select>";
}
}
function print_feed_cat_select($id, $default_id,
$attributes, $include_all_cats = true, $root_id = null, $nest_level = 0) {
if (!$root_id) {
print "<select id=\"$id\" name=\"$id\" default=\"$default_id\" $attributes>";
}
$pdo = DB::pdo();
if (!$root_id) $root_id = null;
$sth = $pdo->prepare("SELECT id,title,
(SELECT COUNT(id) FROM ttrss_feed_categories AS c2 WHERE
c2.parent_cat = ttrss_feed_categories.id) AS num_children
FROM ttrss_feed_categories
WHERE owner_uid = :uid AND
(parent_cat = :root_id OR (:root_id IS NULL AND parent_cat IS NULL)) ORDER BY title");
$sth->execute([":uid" => $_SESSION['uid'], ":root_id" => $root_id]);
$found = 0;
while ($line = $sth->fetch()) {
++$found;
if ($line["id"] == $default_id) {
$is_selected = "selected=\"1\"";
} else {
$is_selected = "";
}
for ($i = 0; $i < $nest_level; $i++)
$line["title"] = " - " . $line["title"];
if ($line["title"])
printf("<option $is_selected value='%d'>%s</option>",
$line["id"], htmlspecialchars($line["title"]));
if ($line["num_children"] > 0)
print_feed_cat_select($id, $default_id, $attributes,
$include_all_cats, $line["id"], $nest_level+1);
}
if (!$root_id) {
if ($include_all_cats) {
if ($found > 0) {
print "<option disabled=\"1\">--------</option>";
}
if ($default_id == 0) {
$is_selected = "selected=\"1\"";
} else {
$is_selected = "";
}
print "<option $is_selected value=\"0\">".__('Uncategorized')."</option>";
}
print "</select>";
}
}
function stylesheet_tag($filename, $id = false) {
$timestamp = filemtime($filename);
$id_part = $id ? "id=\"$id\"" : "";
return "<link rel=\"stylesheet\" $id_part type=\"text/css\" href=\"$filename?$timestamp\"/>\n";
}
function javascript_tag($filename) {
$query = "";
if (!(strpos($filename, "?") === FALSE)) {
$query = substr($filename, strpos($filename, "?")+1);
$filename = substr($filename, 0, strpos($filename, "?"));
}
$timestamp = filemtime($filename);
if ($query) $timestamp .= "&$query";
return "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$filename?$timestamp\"></script>\n";
}
function format_warning($msg, $id = "") {
return "<div class=\"alert\" id=\"$id\">$msg</div>";
}
function format_notice($msg, $id = "") {
return "<div class=\"alert alert-info\" id=\"$id\">$msg</div>";
}
function format_error($msg, $id = "") {
return "<div class=\"alert alert-danger\" id=\"$id\">$msg</div>";
}
function print_notice($msg) {
return print format_notice($msg);
}
function print_warning($msg) {
return print format_warning($msg);
}
function print_error($msg) {
return print format_error($msg);
}
function format_inline_player($url, $ctype) {
$entry = "";
$url = htmlspecialchars($url);
if (strpos($ctype, "audio/") === 0) {
$entry .= "<div class='inline-player'>";
if ($_SESSION["hasAudio"] && (strpos($ctype, "ogg") !== false ||
$_SESSION["hasMp3"])) {
$entry .= "<audio preload=\"none\" controls>
<source type=\"$ctype\" src=\"$url\"/>
</audio> ";
}
if ($entry) $entry .= "<a target=\"_blank\" rel=\"noopener noreferrer\"
href=\"$url\">" . basename($url) . "</a>";
$entry .= "</div>";
return $entry;
}
return "";
}
function print_label_select($name, $value, $attributes = "") {
$pdo = Db::pdo();
$sth = $pdo->prepare("SELECT caption FROM ttrss_labels2
WHERE owner_uid = ? ORDER BY caption");
$sth->execute([$_SESSION['uid']]);
print "<select default=\"$value\" name=\"" . htmlspecialchars($name) .
"\" $attributes>";
while ($line = $sth->fetch()) {
$issel = ($line["caption"] == $value) ? "selected=\"1\"" : "";
print "<option value=\"".htmlspecialchars($line["caption"])."\"
$issel>" . htmlspecialchars($line["caption"]) . "</option>";
}
# print "<option value=\"ADD_LABEL\">" .__("Add label...") . "</option>";
print "</select>";
}

10
include/db-prefs.php Normal file
View File

@ -0,0 +1,10 @@
<?php
require_once "db.php";
function get_pref($pref_name, $user_id = false, $die_on_error = false) {
return Db_Prefs::get()->read($pref_name, $user_id, $die_on_error);
}
function set_pref($pref_name, $value, $user_id = false, $strip_tags = true) {
return Db_Prefs::get()->write($pref_name, $value, $user_id, $strip_tags);
}

38
include/db.php Normal file
View File

@ -0,0 +1,38 @@
<?php
function db_escape_string($s, $strip_tags = true) {
return Db::get()->escape_string($s, $strip_tags);
}
function db_query($query, $die_on_error = true) {
return Db::get()->query($query, $die_on_error);
}
function db_fetch_assoc($result) {
return Db::get()->fetch_assoc($result);
}
function db_num_rows($result) {
return Db::get()->num_rows($result);
}
function db_fetch_result($result, $row, $param) {
return Db::get()->fetch_result($result, $row, $param);
}
function db_affected_rows($result) {
return Db::get()->affected_rows($result);
}
function db_last_error() {
return Db::get()->last_error();
}
function db_last_query_error() {
return Db::get()->last_query_error();
}
function db_quote($str){
return Db::get()->quote($str);
}

74
include/errorhandler.php Normal file
View File

@ -0,0 +1,74 @@
<?php
function format_backtrace($trace) {
$rv = "";
$idx = 1;
if (is_array($trace)) {
foreach ($trace as $e) {
if (isset($e["file"]) && isset($e["line"])) {
$fmt_args = [];
if (is_array($e["args"])) {
foreach ($e["args"] as $a) {
if (!is_object($a)) {
array_push($fmt_args, $a);
} else {
array_push($fmt_args, "[" . get_class($a) . "]");
}
}
}
$filename = str_replace(dirname(__DIR__) . "/", "", $e["file"]);
$rv .= sprintf("%d. %s(%s): %s(%s)\n",
$idx, $filename, $e["line"], $e["function"], implode(", ", $fmt_args));
$idx++;
}
}
}
return $rv;
}
function ttrss_error_handler($errno, $errstr, $file, $line, $context) {
if (error_reporting() == 0 || !$errno) return false;
$file = substr(str_replace(dirname(dirname(__FILE__)), "", $file), 1);
$context = format_backtrace(debug_backtrace());
$errstr = truncate_middle($errstr, 16384, " (...) ");
if (class_exists("Logger"))
return Logger::get()->log_error($errno, $errstr, $file, $line, $context);
}
function ttrss_fatal_handler() {
global $last_query;
$error = error_get_last();
if ($error !== NULL) {
$errno = $error["type"];
$file = $error["file"];
$line = $error["line"];
$errstr = $error["message"];
if (!$errno) return false;
$context = format_backtrace(debug_backtrace());
$file = substr(str_replace(dirname(dirname(__FILE__)), "", $file), 1);
if ($last_query) $errstr .= " [Last query: $last_query]";
if (class_exists("Logger"))
return Logger::get()->log_error($errno, $errstr, $file, $line, $context);
}
return false;
}
register_shutdown_function('ttrss_fatal_handler');
set_error_handler('ttrss_error_handler');

2554
include/functions.php Executable file

File diff suppressed because it is too large Load Diff

156
include/login_form.php Executable file
View File

@ -0,0 +1,156 @@
<?php startup_gettext(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Agriget : Login</title>
<?php echo stylesheet_tag("css/default.css") ?>
<link rel="shortcut icon" type="image/png" href="images/favicon.png">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<?php
foreach (array("lib/prototype.js",
"lib/dojo/dojo.js",
"lib/dojo/tt-rss-layer.js",
"js/common.js",
"errors.php?mode=js") as $jsfile) {
echo javascript_tag($jsfile);
} ?>
<script type="text/javascript">
require({cache:{}});
</script>
</head>
<body class="flat ttrss_utility ttrss_login">
<script type="text/javascript">
require(['dojo/parser', "dojo/ready", 'dijit/form/Button','dijit/form/CheckBox', 'dijit/form/Form',
'dijit/form/Select','dijit/form/TextBox','dijit/form/ValidationTextBox'],function(parser, ready){
ready(function() {
parser.parse();
dijit.byId("bw_limit").attr("checked", Cookie.get("ttrss_bwlimit") == 'true');
dijit.byId("login").focus();
});
});
function fetchProfiles() {
xhrJson("public.php", { op: "getprofiles", login: dijit.byId("login").attr('value') },
(reply) => {
const profile = dijit.byId('profile');
profile.removeOption(profile.getOptions());
reply.each((p) => {
profile
.attr("disabled", false)
.addOption(p);
});
});
}
function gotoRegForm() {
window.location.href = "register.php";
return false;
}
function bwLimitChange(elem) {
Cookie.set("ttrss_bwlimit", elem.checked,
<?php print SESSION_COOKIE_LIFETIME ?>);
}
</script>
<?php $return = urlencode(make_self_url()) ?>
<div class="container">
<h1><?php echo "Authentication" ?></h1>
<div class="content">
<form action="public.php?return=<?php echo $return ?>"
dojoType="dijit.form.Form" method="POST">
<?php print_hidden("op", "login"); ?>
<?php if ($_SESSION["login_error_msg"]) { ?>
<?php echo format_error($_SESSION["login_error_msg"]) ?>
<?php $_SESSION["login_error_msg"] = ""; ?>
<?php } ?>
<fieldset>
<label><?php echo __("Login:") ?></label>
<input name="login" id="login" dojoType="dijit.form.TextBox" type="text"
onchange="fetchProfiles()" onfocus="fetchProfiles()" onblur="fetchProfiles()"
required="1" value="<?php echo $_SESSION["fake_login"] ?>" />
</fieldset>
<fieldset>
<label><?php echo __("Password:") ?></label>
<input type="password" name="password" required="1"
dojoType="dijit.form.TextBox"
class="input input-text"
value="<?php echo $_SESSION["fake_password"] ?>"/>
<?php if (strpos(PLUGINS, "auth_internal") !== FALSE) { ?>
<a href="public.php?op=forgotpass"><?php echo __("I forgot my password") ?></a>
<?php } ?>
</fieldset>
<fieldset>
<label><?php echo __("Profile:") ?></label>
<select disabled='disabled' name="profile" id="profile" dojoType='dijit.form.Select'>
<option><?php echo __("Default profile") ?></option>
</select>
</fieldset>
<fieldset class="narrow">
<label> </label>
<label id="bw_limit_label"><input dojoType="dijit.form.CheckBox" name="bw_limit" id="bw_limit"
type="checkbox" onchange="bwLimitChange(this)">
<?php echo __("Use less traffic") ?></label>
</fieldset>
<div dojoType="dijit.Tooltip" connectId="bw_limit_label" position="below" style="display:none">
<?php echo __("Does not display images in articles, reduces automatic refreshes."); ?>
</div>
<?php if (SESSION_COOKIE_LIFETIME > 0) { ?>
<fieldset class="narrow">
<label> </label>
<label>
<input dojoType="dijit.form.CheckBox" name="remember_me" id="remember_me" type="checkbox">
<?php echo __("Remember me") ?>
</label>
</fieldset>
<?php } ?>
<hr/>
<fieldset class="align-right">
<label> </label>
<button dojoType="dijit.form.Button" type="submit" class="alt-primary"><?php echo __('Log in') ?></button>
<?php if (defined('ENABLE_REGISTRATION') && ENABLE_REGISTRATION) { ?>
<button onclick="return gotoRegForm()" dojoType="dijit.form.Button">
<?php echo __("Create new account") ?></button>
<?php } ?>
</fieldset>
</form>
</div>
<div class="footer">
<a href="https://github.com/Fmstrat/agriget/">Agriget</a>
&copy; 2005&ndash;<?php echo date('Y') ?>
</div>
</div>
</body>
</html>

248
include/sanity_check.php Executable file
View File

@ -0,0 +1,248 @@
<?php
/* WARNING!
*
* If you modify this file, you are ON YOUR OWN!
*
* Believe it or not, all of the checks below are required to succeed for
* tt-rss to actually function properly.
*
* If you think you have a better idea about what is or isn't required, feel
* free to modify the file, note though that you are therefore automatically
* disqualified from any further support by official channels, e.g. tt-rss.org
* issue tracker or the forums.
*
* If you come crying when stuff inevitably breaks, you will be mocked and told
* to get out. */
function make_self_url() {
$proto = is_server_https() ? 'https' : 'http';
return $proto . '://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
}
function make_self_url_path() {
$proto = is_server_https() ? 'https' : 'http';
$url_path = $proto . '://' . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
return $url_path;
}
/**
* @SuppressWarnings(PHPMD.UnusedLocalVariable)
*/
function initial_sanity_check() {
$errors = array();
if (!file_exists("data/config.php")) {
array_push($errors, "Configuration file not found. Looks like you forgot to copy config.php-dist to config.php and edit it.");
} else {
require_once "sanity_config.php";
if (file_exists("install") && !file_exists("data/config.php")) {
array_push($errors, "Please copy config.php-dist to config.php or run the installer in install/");
}
if (strpos(PLUGINS, "auth_") === FALSE) {
array_push($errors, "Please enable at least one authentication module via PLUGINS constant in config.php");
}
if (function_exists('posix_getuid') && posix_getuid() == 0) {
array_push($errors, "Please don't run this script as root.");
}
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
array_push($errors, "PHP version 5.6.0 or newer required. You're using " . PHP_VERSION . ".");
}
if (CONFIG_VERSION != EXPECTED_CONFIG_VERSION) {
array_push($errors, "Configuration file (config.php) has incorrect version. Update it with new options from config.php-dist and set CONFIG_VERSION to the correct value.");
}
if (!is_writable(DATA_DIR)) {
array_push($errors, "Data is not writable (chmod -R 777 ".DATA_DIR.")");
} else {
if (!is_dir(DATA_DIR . "/cache")) mkdir(DATA_DIR . "/cache");
if (!is_dir(DATA_DIR . "/lock")) mkdir(DATA_DIR . "/lock");
if (!is_dir(DATA_DIR . "/feed-icons")) mkdir(DATA_DIR . "/feed-icons");
if (!is_dir(DATA_DIR . "/plugins.local")) mkdir(DATA_DIR . "/plugins.local");
if (!is_dir(DATA_DIR . "/themes.local")) mkdir(DATA_DIR . "/themes.local");
}
if (!is_writable(CACHE_DIR)) {
array_push($errors, "Cache is not writable (chmod -R 777 ".CACHE_DIR.")");
} else {
if (!is_dir(CACHE_DIR . "/images")) mkdir(CACHE_DIR . "/images");
if (!is_dir(CACHE_DIR . "/upload")) mkdir(CACHE_DIR . "/upload");
if (!is_dir(CACHE_DIR . "/export")) mkdir(CACHE_DIR . "/export");
if (!is_dir(CACHE_DIR . "/feeds")) mkdir(CACHE_DIR . "/feeds");
}
if (!is_writable(CACHE_DIR . "/images")) {
array_push($errors, "Image cache is not writable (chmod -R 777 ".CACHE_DIR."/images)");
}
if (!is_writable(CACHE_DIR . "/upload")) {
array_push($errors, "Upload cache is not writable (chmod -R 777 ".CACHE_DIR."/upload)");
}
if (!is_writable(CACHE_DIR . "/export")) {
array_push($errors, "Data export cache is not writable (chmod -R 777 ".CACHE_DIR."/export)");
}
if (GENERATED_CONFIG_CHECK != EXPECTED_CONFIG_VERSION) {
array_push($errors,
"Configuration option checker sanity_config.php is outdated, please recreate it using ./utils/regen_config_checks.sh");
}
foreach ($required_defines as $d) {
if (!defined($d)) {
array_push($errors,
"Required configuration file parameter $d is not defined in config.php. You might need to copy it from config.php-dist.");
}
}
if (SINGLE_USER_MODE && class_exists("PDO")) {
$pdo = DB::pdo();
$res = $pdo->query("SELECT id FROM ttrss_users WHERE id = 1");
if (!$res->fetch()) {
array_push($errors, "SINGLE_USER_MODE is enabled in config.php but default admin account is not found.");
}
}
$ref_self_url_path = make_self_url_path();
$ref_self_url_path = preg_replace("/\w+\.php$/", "", $ref_self_url_path);
if (SELF_URL_PATH == "http://example.org/tt-rss/") {
array_push($errors,
"Please set SELF_URL_PATH to the correct value for your server (possible value: <b>$ref_self_url_path</b>)");
}
if (isset($_SERVER["HTTP_HOST"]) &&
(!defined('_SKIP_SELF_URL_PATH_CHECKS') || !_SKIP_SELF_URL_PATH_CHECKS) &&
SELF_URL_PATH != $ref_self_url_path && SELF_URL_PATH != mb_substr($ref_self_url_path, 0, mb_strlen($ref_self_url_path)-1)) {
array_push($errors,
"Please set SELF_URL_PATH to the correct value detected for your server: <b>$ref_self_url_path</b>");
}
if (!is_writable(ICONS_DIR)) {
array_push($errors, "ICONS_DIR defined in config.php is not writable (chmod -R 777 ".ICONS_DIR.").\n");
}
if (!is_writable(LOCK_DIRECTORY)) {
array_push($errors, "LOCK_DIRECTORY defined in config.php is not writable (chmod -R 777 ".LOCK_DIRECTORY.").\n");
}
if (!function_exists("curl_init") && !ini_get("allow_url_fopen")) {
array_push($errors, "PHP configuration option allow_url_fopen is disabled, and CURL functions are not present. Either enable allow_url_fopen or install PHP extension for CURL.");
}
if (!function_exists("json_encode")) {
array_push($errors, "PHP support for JSON is required, but was not found.");
}
if (DB_TYPE == "mysql" && !function_exists("mysqli_connect")) {
array_push($errors, "PHP support for MySQL is required for configured DB_TYPE in config.php.");
}
if (DB_TYPE == "pgsql" && !function_exists("pg_connect")) {
array_push($errors, "PHP support for PostgreSQL is required for configured DB_TYPE in config.php");
}
if (!class_exists("PDO")) {
array_push($errors, "PHP support for PDO is required but was not found.");
}
if (!function_exists("mb_strlen")) {
array_push($errors, "PHP support for mbstring functions is required but was not found.");
}
if (!function_exists("hash")) {
array_push($errors, "PHP support for hash() function is required but was not found.");
}
if (ini_get("safe_mode")) {
array_push($errors, "PHP safe mode setting is obsolete and not supported by tt-rss.");
}
if (!function_exists("mime_content_type")) {
array_push($errors, "PHP function mime_content_type() is missing, try enabling fileinfo module.");
}
if (!class_exists("DOMDocument")) {
array_push($errors, "PHP support for DOMDocument is required, but was not found.");
}
if (DB_TYPE == "mysql") {
$bad_tables = check_mysql_tables();
if (count($bad_tables) > 0) {
$bad_tables_fmt = [];
foreach ($bad_tables as $bt) {
array_push($bad_tables_fmt, sprintf("%s (%s)", $bt['table_name'], $bt['engine']));
}
$msg = "<p>The following tables use an unsupported MySQL engine: <b>" .
implode(", ", $bad_tables_fmt) . "</b>.</p>";
$msg .= "<p>The only supported engine on MySQL is InnoDB. MyISAM lacks functionality to run
tt-rss.
Please backup your data (via OPML) and re-import the schema before continuing.</p>
<p><b>WARNING: importing the schema would mean LOSS OF ALL YOUR DATA.</b></p>";
array_push($errors, $msg);
}
}
}
if (count($errors) > 0 && $_SERVER['REQUEST_URI']) { ?>
<!DOCTYPE html>
<html>
<head>
<title>Startup failed</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="css/default.css">
</head>
<body class='sanity_failed claro ttrss_utility'>
<div class="content">
<h1>Startup failed</h1>
<p>Agriget was unable to start properly. This usually means a misconfiguration or an incomplete upgrade. Please fix
errors indicated by the following messages:</p>
<?php foreach ($errors as $error) { echo format_error($error); } ?>
<p>You might want to check tt-rss <a href="http://tt-rss.org/wiki">wiki</a> or the
<a href="http://tt-rss.org/forum">forums</a> for more information. Please search the forums before creating new topic
for your question.</p>
</div>
</body>
</html>
<?php
die;
} else if (count($errors) > 0) {
echo "Agriget was unable to start properly. This usually means a misconfiguration or an incomplete upgrade.\n";
echo "Please fix errors indicated by the following messages:\n\n";
foreach ($errors as $error) {
echo " * $error\n";
}
echo "\nYou might want to check tt-rss wiki or the forums for more information.\n";
echo "Please search the forums before creating new topic for your question.\n";
exit(-1);
}
}
initial_sanity_check();
?>

View File

@ -0,0 +1,3 @@
<?php # This file has been generated at: Thu Nov 22 22:14:43 MSK 2018
define('GENERATED_CONFIG_CHECK', 26);
$required_defines = array( 'DB_TYPE', 'DB_HOST', 'DB_USER', 'DB_NAME', 'DB_PASS', 'MYSQL_CHARSET', 'SELF_URL_PATH', 'SINGLE_USER_MODE', 'SIMPLE_UPDATE_MODE', 'PHP_EXECUTABLE', 'LOCK_DIRECTORY', 'CACHE_DIR', 'ICONS_DIR', 'ICONS_URL', 'AUTH_AUTO_CREATE', 'AUTH_AUTO_LOGIN', 'FORCE_ARTICLE_PURGE', 'SPHINX_SERVER', 'SPHINX_INDEX', 'ENABLE_REGISTRATION', 'REG_NOTIFY_ADDRESS', 'REG_MAX_USERS', 'SESSION_COOKIE_LIFETIME', 'SMTP_FROM_NAME', 'SMTP_FROM_ADDRESS', 'DIGEST_SUBJECT', 'CHECK_FOR_UPDATES', 'ENABLE_GZIP_OUTPUT', 'PLUGINS', 'LOG_DESTINATION', 'CONFIG_VERSION'); ?>

165
include/sessions.php Normal file
View File

@ -0,0 +1,165 @@
<?php
// Original from http://www.daniweb.com/code/snippet43.html
require_once "data/config.php";
require_once "classes/db.php";
require_once "autoload.php";
require_once "errorhandler.php";
require_once "lib/accept-to-gettext.php";
require_once "lib/gettext/gettext.inc";
require_once "version.php";
$session_expire = min(2147483647 - time() - 1, max(SESSION_COOKIE_LIFETIME, 86400));
$session_name = (!defined('TTRSS_SESSION_NAME')) ? "ttrss_sid" : TTRSS_SESSION_NAME;
if (is_server_https()) {
ini_set("session.cookie_secure", true);
}
ini_set("session.gc_probability", 75);
ini_set("session.name", $session_name);
ini_set("session.use_only_cookies", true);
ini_set("session.gc_maxlifetime", $session_expire);
ini_set("session.cookie_lifetime", min(0, SESSION_COOKIE_LIFETIME));
function session_get_schema_version() {
global $schema_version;
if (!$schema_version) {
$row = Db::pdo()->query("SELECT schema_version FROM ttrss_version")->fetch();
$version = $row["schema_version"];
$schema_version = $version;
return $version;
} else {
return $schema_version;
}
}
function validate_session() {
if (SINGLE_USER_MODE) return true;
if (isset($_SESSION["ref_schema_version"]) && $_SESSION["ref_schema_version"] != session_get_schema_version()) {
$_SESSION["login_error_msg"] =
__("Session failed to validate (schema version changed)");
return false;
}
$pdo = Db::pdo();
if ($_SESSION["uid"]) {
if ($_SESSION["user_agent"] != sha1($_SERVER['HTTP_USER_AGENT'])) {
$_SESSION["login_error_msg"] = __("Session failed to validate (UA changed).");
return false;
}
$sth = $pdo->prepare("SELECT pwd_hash FROM ttrss_users WHERE id = ?");
$sth->execute([$_SESSION['uid']]);
// user not found
if ($row = $sth->fetch()) {
$pwd_hash = $row["pwd_hash"];
if ($pwd_hash != $_SESSION["pwd_hash"]) {
$_SESSION["login_error_msg"] =
__("Session failed to validate (password changed)");
return false;
}
} else {
$_SESSION["login_error_msg"] =
__("Session failed to validate (user not found)");
return false;
}
}
return true;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
function ttrss_open ($s, $n) {
return true;
}
function ttrss_read ($id){
global $session_expire;
$sth = Db::pdo()->prepare("SELECT data FROM ttrss_sessions WHERE id=?");
$sth->execute([$id]);
if ($row = $sth->fetch()) {
return base64_decode($row["data"]);
} else {
$expire = time() + $session_expire;
$sth = Db::pdo()->prepare("INSERT INTO ttrss_sessions (id, data, expire)
VALUES (?, '', ?)");
$sth->execute([$id, $expire]);
return "";
}
}
function ttrss_write ($id, $data) {
global $session_expire;
$data = base64_encode($data);
$expire = time() + $session_expire;
$sth = Db::pdo()->prepare("SELECT id FROM ttrss_sessions WHERE id=?");
$sth->execute([$id]);
if ($row = $sth->fetch()) {
$sth = Db::pdo()->prepare("UPDATE ttrss_sessions SET data=?, expire=? WHERE id=?");
$sth->execute([$data, $expire, $id]);
} else {
$sth = Db::pdo()->prepare("INSERT INTO ttrss_sessions (id, data, expire)
VALUES (?, ?, ?)");
$sth->execute([$id, $data, $expire]);
}
return true;
}
function ttrss_close () {
return true;
}
function ttrss_destroy($id) {
$sth = Db::pdo()->prepare("DELETE FROM ttrss_sessions WHERE id = ?");
$sth->execute([$id]);
return true;
}
/**
* @SuppressWarnings(PHPMD.UnusedFormalParameter)
*/
function ttrss_gc ($expire) {
Db::pdo()->query("DELETE FROM ttrss_sessions WHERE expire < " . time());
return true;
}
if (!SINGLE_USER_MODE /* && DB_TYPE == "pgsql" */) {
session_set_save_handler("ttrss_open",
"ttrss_close", "ttrss_read", "ttrss_write",
"ttrss_destroy", "ttrss_gc");
register_shutdown_function('session_write_close');
}
if (!defined('NO_SESSION_AUTOSTART')) {
if (isset($_COOKIE[session_name()])) {
@session_start();
}
}

43
include/version.php Normal file
View File

@ -0,0 +1,43 @@
<?php
define('VERSION_STATIC', '19.2');
function get_version() {
date_default_timezone_set('UTC');
$root_dir = dirname(dirname(__FILE__));
if (is_dir("$root_dir/.git") && file_exists("$root_dir/.git/HEAD")) {
$head = trim(file_get_contents("$root_dir/.git/HEAD"));
if ($head) {
$matches = array();
if (preg_match("/^ref: (.*)/", $head, $matches)) {
$ref = $matches[1];
if (!file_exists("$root_dir/.git/$ref"))
return VERSION_STATIC;
$suffix = substr(trim(file_get_contents("$root_dir/.git/$ref")), 0, 7);
$timestamp = filemtime("$root_dir/.git/$ref");
define("GIT_VERSION_HEAD", $suffix);
define("GIT_VERSION_TIMESTAMP", $timestamp);
return VERSION_STATIC . " ($suffix)";
} else {
$suffix = substr(trim($head), 0, 7);
$timestamp = filemtime("$root_dir/.git/HEAD");
define("GIT_VERSION_HEAD", $suffix);
define("GIT_VERSION_TIMESTAMP", $timestamp);
return VERSION_STATIC . " ($suffix)";
}
}
}
return VERSION_STATIC;
}
define('VERSION', get_version());

285
index.php Normal file
View File

@ -0,0 +1,285 @@
<?php
if (file_exists("install") && !file_exists("data/config.php")) {
header("Location: install/");
}
if (!file_exists("data/config.php")) {
print "<b>Fatal Error</b>: You forgot to copy
<b>config.php-dist</b> to <b>config.php</b> and edit it.\n";
exit;
}
// we need a separate check here because functions.php might get parsed
// incorrectly before 5.3 because of :: syntax.
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
print "<b>Fatal Error</b>: PHP version 5.6.0 or newer required. You're using " . PHP_VERSION . ".\n";
exit;
}
set_include_path(dirname(__FILE__) ."/include" . PATH_SEPARATOR .
get_include_path());
require_once "autoload.php";
require_once "sessions.php";
require_once "functions.php";
require_once "sanity_check.php";
require_once "version.php";
require_once "data/config.php";
require_once "db-prefs.php";
if (!init_plugins()) return;
login_sequence();
header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
<title>Agriget</title>
<meta name="viewport" content="initial-scale=1,width=device-width" />
<script type="text/javascript">
var __ttrss_version = "<?php echo VERSION ?>"
</script>
<?php if ($_SESSION["uid"]) {
$theme = get_pref("USER_CSS_THEME", false, false);
if ($theme && theme_exists("$theme")) {
echo stylesheet_tag(get_theme_path($theme), 'theme_css');
echo stylesheet_tag("css/updates.css", 'theme_css');
if (strpos($theme, "night") !== false)
echo stylesheet_tag("css/updates-night.css", 'theme_css');
} else {
echo stylesheet_tag("themes/agriget.css", 'theme_css');
echo stylesheet_tag("css/updates.css", 'theme_css');
}
}
?>
<?php print_user_stylesheet() ?>
<style type="text/css">
<?php
foreach (PluginHost::getInstance()->get_plugins() as $n => $p) {
if (method_exists($p, "get_css")) {
echo $p->get_css();
}
}
?>
</style>
<link rel="shortcut icon" type="image/png" href="images/favicon.png"/>
<link rel="icon" type="image/png" sizes="72x72" href="images/favicon-72px.png" />
<script>
dojoConfig = {
async: true,
cacheBust: "<?php echo get_scripts_timestamp(); ?>",
packages: [
{ name: "fox", location: "../../js" },
]
};
</script>
<script type="text/javascript" src="js/updates.js"></script>
<?php
foreach (array("lib/prototype.js",
"lib/scriptaculous/scriptaculous.js?load=effects,controls",
"lib/dojo/dojo.js",
"lib/dojo/tt-rss-layer.js",
"js/tt-rss.js",
"js/common.js",
"errors.php?mode=js") as $jsfile) {
echo javascript_tag($jsfile);
} ?>
<script type="text/javascript">
require({cache:{}});
</script>
<script type="text/javascript">
<?php
foreach (PluginHost::getInstance()->get_plugins() as $n => $p) {
if (method_exists($p, "get_js")) {
$script = $p->get_js();
if ($script) {
echo "try {
$script
} catch (e) {
console.warn('failed to initialize plugin JS: $n', e);
}";
}
}
}
init_js_translations();
?>
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="referrer" content="no-referrer"/>
</head>
<body class="flat ttrss_main ttrss_index">
<div id="overlay" style="display : block">
<div id="overlay_inner">
<?php echo __("Loading, please wait...") ?>
<div dojoType="dijit.ProgressBar" places="0" style="width : 300px" id="loading_bar"
progress="0" maximum="100">
</div>
<noscript><br/><?php print_error('Javascript is disabled. Please enable it.') ?></noscript>
</div>
</div>
<div id="notify" class="notify"></div>
<div id="cmdline" style="display : none"></div>
<div id="main" dojoType="dijit.layout.BorderContainer">
<div id="feeds-holder" dojoType="dijit.layout.ContentPane" region="leading" style="width : 20%" splitter="true">
<div id="feedlistLoading">
<img src='images/indicator_tiny.gif'/>
<?php echo __("Loading, please wait..."); ?></div>
<div id="feedTree"></div>
</div>
<div dojoType="dijit.layout.BorderContainer" region="center" id="content-wrap">
<div id="toolbar-frame" dojoType="dijit.layout.ContentPane" region="top">
<div id="toolbar" dojoType="dijit.Toolbar">
<i class="material-icons net-alert" style="display : none"
title="<?php echo __("Communication problem with server.") ?>">error_outline</i>
<i class="material-icons log-alert" style="display : none"
title="<?php echo __("Recent entries found in event log.") ?>">warning</i>
<i id="updates-available" class="material-icons icon-new-version" style="display : none"
title="<?php echo __('Updates are available from Git.') ?>">new_releases</i>
<?php
foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_MAIN_TOOLBAR_BUTTON) as $p) {
echo $p->hook_main_toolbar_button();
}
?>
<form id="toolbar-headlines" action="" onsubmit='return false'>
</form>
<form class="toolbar-hide" id="toolbar-main" action="" onsubmit='return false'>
<select name="view_mode" title="<?php echo __('Show articles') ?>"
onchange="App.onViewModeChanged()"
dojoType="dijit.form.Select">
<option selected="selected" value="adaptive"><?php echo __('Adaptive') ?></option>
<option value="all_articles"><?php echo __('All Articles') ?></option>
<option value="marked"><?php echo __('Starred') ?></option>
<option value="published"><?php echo __('Published') ?></option>
<option value="unread"><?php echo __('Unread') ?></option>
<option value="has_note"><?php echo __('With Note') ?></option>
<!-- <option value="noscores"><?php echo __('Ignore Scoring') ?></option> -->
</select>
<select title="<?php echo __('Sort articles') ?>"
onchange="App.onViewModeChanged()"
dojoType="dijit.form.Select" name="order_by">
<option selected="selected" value="default"><?php echo __('Default') ?></option>
<option value="feed_dates"><?php echo __('Newest first') ?></option>
<option value="date_reverse"><?php echo __('Oldest first') ?></option>
<option value="title"><?php echo __('Title') ?></option>
</select>
<div dojoType="dijit.form.ComboButton" onclick="Feeds.catchupCurrent()">
<span><?php echo __('Mark as read') ?></span>
<div dojoType="dijit.DropDownMenu">
<div dojoType="dijit.MenuItem" onclick="Feeds.catchupCurrent('1day')">
<?php echo __('Older than one day') ?>
</div>
<div dojoType="dijit.MenuItem" onclick="Feeds.catchupCurrent('1week')">
<?php echo __('Older than one week') ?>
</div>
<div dojoType="dijit.MenuItem" onclick="Feeds.catchupCurrent('2week')">
<?php echo __('Older than two weeks') ?>
</div>
</div>
</div>
</form>
<div class="action-chooser toolbar-hide">
<?php
foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_TOOLBAR_BUTTON) as $p) {
echo $p->hook_toolbar_button();
}
?>
<div dojoType="dijit.form.DropDownButton" class="action-button" title="<?php echo __('Actions...') ?>">
<span><i class="material-icons">menu</i></span>
<div dojoType="dijit.Menu" style="display: none">
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcPrefs')"><?php echo __('Preferences...') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcSearch')"><?php echo __('Search...') ?></div>
<div dojoType="dijit.MenuItem" disabled="1"><?php echo __('Feed actions:') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcAddFeed')"><?php echo __('Subscribe to feed...') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcEditFeed')"><?php echo __('Edit this feed...') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcRemoveFeed')"><?php echo __('Unsubscribe') ?></div>
<div dojoType="dijit.MenuItem" disabled="1"><?php echo __('All feeds:') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcCatchupAll')"><?php echo __('Mark as read') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcShowOnlyUnread')"><?php echo __('(Un)hide read feeds') ?></div>
<div dojoType="dijit.MenuItem" disabled="1"><?php echo __('Other actions:') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcToggleNightMode')"><?php echo __('Toggle night mode') ?></div>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcHKhelp')"><?php echo __('Keyboard shortcuts help') ?></div>
<?php
foreach (PluginHost::getInstance()->get_hooks(PluginHost::HOOK_ACTION_ITEM) as $p) {
echo $p->hook_action_item();
}
?>
<?php if (!$_SESSION["hide_logout"]) { ?>
<div dojoType="dijit.MenuItem" onclick="App.onActionSelected('qmcLogout')"><?php echo __('Logout') ?></div>
<?php } ?>
</div>
</div>
</div>
<div id="more-button">
<span id="display-buttons">
<i onclick="App.setViewMode('magazine');Headlines.renderAgain()" id="display-magazine" class="active-display material-icons icon icon-inbox">format_list_bulleted</i>
&nbsp;
<i onclick="App.setViewMode('cards');Headlines.renderAgain()" id="display-cards" class="inactive-display material-icons icon icon-inbox">apps</i>
&nbsp;
<i onclick="App.setViewMode('full');Headlines.renderAgain()" id="display-full" class="inactive-display material-icons icon icon-inbox">fullscreen</i>
&nbsp;
&nbsp;
&nbsp;
</span>
<a href="#" onclick="toggleToolbar()"><i class='icon-syndicate material-icons'>more_vert</i></a>
</div>
</div> <!-- toolbar -->
</div> <!-- toolbar pane -->
<div id="headlines-wrap-inner" dojoType="dijit.layout.BorderContainer" region="center">
<div id="floatingTitle" style="display : none"></div>
<div id="headlines-frame" dojoType="dijit.layout.ContentPane" tabindex="0"
region="center">
<div id="headlinesInnerContainer">
<div class="whiteBox"><?php echo __('Loading, please wait...') ?></div>
</div>
</div>
<div id="content-insert" dojoType="dijit.layout.ContentPane" region="bottom"
style="height : 50%" splitter="true"></div>
</div>
</div>
</div>
<div dojoType="dijit.layout.ContentPane" id="slide-out" class="cdm expanded">No article</div>
<div id="slide-out-shadow" onclick="Headlines.hideFull()"></div>
</body>
</html>

517
install/index.php Executable file
View File

@ -0,0 +1,517 @@
<?php
function stylesheet_tag($filename, $id = false) {
$timestamp = filemtime($filename);
$id_part = $id ? "id=\"$id\"" : "";
return "<link rel=\"stylesheet\" $id_part type=\"text/css\" href=\"$filename?$timestamp\"/>\n";
}
function javascript_tag($filename) {
$query = "";
if (!(strpos($filename, "?") === FALSE)) {
$query = substr($filename, strpos($filename, "?")+1);
$filename = substr($filename, 0, strpos($filename, "?"));
}
$timestamp = filemtime($filename);
if ($query) $timestamp .= "&$query";
return "<script type=\"text/javascript\" charset=\"utf-8\" src=\"$filename?$timestamp\"></script>\n";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Agriget - Installer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
textarea { font-size : 12px; }
</style>
<?php
echo stylesheet_tag("../css/default.css");
echo javascript_tag("../lib/prototype.js");
echo javascript_tag("../lib/dojo/dojo.js");
echo javascript_tag("../lib/dojo/tt-rss-layer.js");
?>
</head>
<body class="flat ttrss_utility installer">
<script type="text/javascript">
require(['dojo/parser', "dojo/ready", 'dijit/form/Button','dijit/form/CheckBox', 'dijit/form/Form',
'dijit/form/Select','dijit/form/TextBox','dijit/form/ValidationTextBox'],function(parser, ready){
ready(function() {
parser.parse();
});
});
</script>
<?php
// could be needed because of existing config.php
function define_default($param, $value) {
//
}
function make_password($length = 12) {
$password = "";
$possible = "0123456789abcdfghjkmnpqrstvwxyzABCDFGHJKMNPQRSTVWXYZ*%+^";
$i = 0;
while ($i < $length) {
try {
$idx = function_exists("random_int") ? random_int(0, strlen($possible) - 1) : mt_rand(0, strlen($possible) - 1);
} catch (Exception $e) {
$idx = mt_rand(0, strlen($possible) - 1);
}
$char = substr($possible, $idx, 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}
function sanity_check($db_type) {
$errors = array();
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
array_push($errors, "PHP version 5.6.0 or newer required. You're using " . PHP_VERSION . ".");
}
if (!function_exists("curl_init") && !ini_get("allow_url_fopen")) {
array_push($errors, "PHP configuration option allow_url_fopen is disabled, and CURL functions are not present. Either enable allow_url_fopen or install PHP extension for CURL.");
}
if (!function_exists("json_encode")) {
array_push($errors, "PHP support for JSON is required, but was not found.");
}
if (!class_exists("PDO")) {
array_push($errors, "PHP support for PDO is required but was not found.");
}
if (!function_exists("mb_strlen")) {
array_push($errors, "PHP support for mbstring functions is required but was not found.");
}
if (!function_exists("hash")) {
array_push($errors, "PHP support for hash() function is required but was not found.");
}
if (!function_exists("iconv")) {
array_push($errors, "PHP support for iconv is required to handle multiple charsets.");
}
if (ini_get("safe_mode")) {
array_push($errors, "PHP safe mode setting is obsolete and not supported by agriget.");
}
if (!class_exists("DOMDocument")) {
array_push($errors, "PHP support for DOMDocument is required, but was not found.");
}
return $errors;
}
function print_error($msg) {
print "<div class='alert alert-error'>$msg</div>";
}
function print_notice($msg) {
print "<div class=\"alert alert-info\">$msg</div>";
}
function pdo_connect($host, $user, $pass, $db, $type, $port = false) {
$db_port = $port ? ';port=' . $port : '';
$db_host = $host ? ';host=' . $host : '';
try {
$pdo = new PDO($type . ':dbname=' . $db . $db_host . $db_port,
$user,
$pass);
return $pdo;
} catch (Exception $e) {
print "<div class='alert alert-danger'>" . $e->getMessage() . "</div>";
return null;
}
}
function make_config($DB_TYPE, $DB_HOST, $DB_USER, $DB_NAME, $DB_PASS,
$DB_PORT, $SELF_URL_PATH) {
$data = explode("\n", file_get_contents("../config.php-dist"));
$rv = "";
$finished = false;
foreach ($data as $line) {
if (preg_match("/define\('DB_TYPE'/", $line)) {
$rv .= "\tdefine('DB_TYPE', '$DB_TYPE');\n";
} else if (preg_match("/define\('DB_HOST'/", $line)) {
$rv .= "\tdefine('DB_HOST', '$DB_HOST');\n";
} else if (preg_match("/define\('DB_USER'/", $line)) {
$rv .= "\tdefine('DB_USER', '$DB_USER');\n";
} else if (preg_match("/define\('DB_NAME'/", $line)) {
$rv .= "\tdefine('DB_NAME', '$DB_NAME');\n";
} else if (preg_match("/define\('DB_PASS'/", $line)) {
$rv .= "\tdefine('DB_PASS', '$DB_PASS');\n";
} else if (preg_match("/define\('DB_PORT'/", $line)) {
$rv .= "\tdefine('DB_PORT', '$DB_PORT');\n";
} else if (preg_match("/define\('SELF_URL_PATH'/", $line)) {
$rv .= "\tdefine('SELF_URL_PATH', '$SELF_URL_PATH');\n";
} else if (!$finished) {
$rv .= "$line\n";
}
if (preg_match("/\?\>/", $line)) {
$finished = true;
}
}
return $rv;
}
function is_server_https() {
return (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off')) || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
}
function make_self_url_path() {
$url_path = (is_server_https() ? 'https://' : 'http://') . $_SERVER["HTTP_HOST"] . parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
return $url_path;
}
?>
<h1>Agriget Installer</h1>
<div class='content'>
<?php
if (file_exists("../data/config.php")) {
require "../data/config.php";
if (!defined('_INSTALLER_IGNORE_CONFIG_CHECK')) {
print_error("Error: config.php already exists in data directory; aborting.");
print "<form method='GET' action='../index.php'>
<button type='submit' dojoType='dijit.form.Button' class='alt-primary'>Return to Agriget</button>
</form>";
exit;
}
}
@$op = $_REQUEST['op'];
@$DB_HOST = strip_tags($_POST['DB_HOST']);
@$DB_TYPE = strip_tags($_POST['DB_TYPE']);
@$DB_USER = strip_tags($_POST['DB_USER']);
@$DB_NAME = strip_tags($_POST['DB_NAME']);
@$DB_PASS = strip_tags($_POST['DB_PASS']);
@$DB_PORT = strip_tags($_POST['DB_PORT']);
@$SELF_URL_PATH = strip_tags($_POST['SELF_URL_PATH']);
if (!$SELF_URL_PATH) {
$SELF_URL_PATH = preg_replace("/\/install\/$/", "/", make_self_url_path());
}
?>
<form action="" method="post">
<input type="hidden" name="op" value="testconfig">
<h2>Database settings</h2>
<?php
$issel_pgsql = $DB_TYPE == "pgsql" ? "selected='selected'" : "";
$issel_mysql = $DB_TYPE == "mysql" ? "selected='selected'" : "";
?>
<fieldset>
<label>Database type:</label>
<select name="DB_TYPE" dojoType="dijit.form.Select">
<option <?php echo $issel_pgsql ?> value="pgsql">PostgreSQL</option>
<option <?php echo $issel_mysql ?> value="mysql">MySQL</option>
</select>
</fieldset>
<fieldset>
<label>Username:</label>
<input dojoType="dijit.form.TextBox" required name="DB_USER" size="20" value="<?php echo $DB_USER ?>"/>
</fieldset>
<fieldset>
<label>Password:</label>
<input dojoType="dijit.form.TextBox" name="DB_PASS" size="20" type="password" value="<?php echo $DB_PASS ?>"/>
</fieldset>
<fieldset>
<label>Database name:</label>
<input dojoType="dijit.form.TextBox" required name="DB_NAME" size="20" value="<?php echo $DB_NAME ?>"/>
</fieldset>
<fieldset>
<label>Host name:</label>
<input dojoType="dijit.form.TextBox" name="DB_HOST" size="20" value="<?php echo $DB_HOST ?>"/>
<span class="hint">If needed</span>
</fieldset>
<fieldset>
<label>Port:</label>
<input dojoType="dijit.form.TextBox" name="DB_PORT" type="number" size="20" value="<?php echo $DB_PORT ?>"/>
<span class="hint">Usually 3306 for MySQL or 5432 for PostgreSQL</span>
</fieldset>
<h2>Other settings</h2>
<p>This should be set to the location your Agriget will be available on.</p>
<fieldset>
<label>Agriget URL:</label>
<input dojoType="dijit.form.TextBox" type="url" name="SELF_URL_PATH" placeholder="<?php echo $SELF_URL_PATH; ?>" value="<?php echo $SELF_URL_PATH ?>"/>
</fieldset>
<p><button type="submit" dojoType="dijit.form.Button" class="alt-primary">Test configuration</button></p>
</form>
<?php if ($op == 'testconfig') { ?>
<h2>Checking configuration</h2>
<?php
$errors = sanity_check($DB_TYPE);
if (count($errors) > 0) {
print "<p>Some configuration tests failed. Please correct them before continuing.</p>";
print "<ul>";
foreach ($errors as $error) {
print "<li style='color : red'>$error</li>";
}
print "</ul>";
exit;
}
$notices = array();
if (!function_exists("curl_init")) {
array_push($notices, "It is highly recommended to enable support for CURL in PHP.");
}
if (function_exists("curl_init") && ini_get("open_basedir")) {
array_push($notices, "CURL and open_basedir combination breaks support for HTTP redirects. See the FAQ for more information.");
}
if (!function_exists("idn_to_ascii")) {
array_push($notices, "PHP support for Internationalization Functions is required to handle Internationalized Domain Names.");
}
if ($DB_TYPE == "mysql" && !function_exists("mysqli_connect")) {
array_push($notices, "PHP extension for MySQL (mysqli) is missing. This may prevent legacy plugins from working.");
}
if ($DB_TYPE == "pgsql" && !function_exists("pg_connect")) {
array_push($notices, "PHP extension for PostgreSQL is missing. This may prevent legacy plugins from working.");
}
if (count($notices) > 0) {
print_notice("Configuration check succeeded with minor problems:");
print "<ul>";
foreach ($notices as $notice) {
print "<li>$notice</li>";
}
print "</ul>";
} else {
print_notice("Configuration check succeeded.");
}
?>
<h2>Checking database</h2>
<?php
$pdo = pdo_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME, $DB_TYPE, $DB_PORT);
if (!$pdo) {
print_error("Unable to connect to database using specified parameters (driver: $DB_TYPE).");
exit;
}
print_notice("Database test succeeded.");
?>
<h2>Initialize database</h2>
<p>Before you can start using agriget, database needs to be initialized. Click on the button below to do that now.</p>
<?php
$res = $pdo->query("SELECT true FROM ttrss_feeds");
if ($res && $res->fetch()) {
print_error("Some agriget data already exists in this database. If you continue with database initialization your current data <b>WILL BE LOST</b>.");
$need_confirm = true;
} else {
$need_confirm = false;
}
?>
<table><tr><td>
<form method="post">
<input type="hidden" name="op" value="installschema">
<input type="hidden" name="DB_USER" value="<?php echo $DB_USER ?>"/>
<input type="hidden" name="DB_PASS" value="<?php echo $DB_PASS ?>"/>
<input type="hidden" name="DB_NAME" value="<?php echo $DB_NAME ?>"/>
<input type="hidden" name="DB_HOST" value="<?php echo $DB_HOST ?>"/>
<input type="hidden" name="DB_PORT" value="<?php echo $DB_PORT ?>"/>
<input type="hidden" name="DB_TYPE" value="<?php echo $DB_TYPE ?>"/>
<input type="hidden" name="SELF_URL_PATH" value="<?php echo $SELF_URL_PATH ?>"/>
<p>
<?php if ($need_confirm) { ?>
<button onclick="return confirm('Please read the warning above. Continue?')" type="submit"
class="alt-danger" dojoType="dijit.form.Button">Initialize database</button>
<?php } else { ?>
<button type="submit" class="alt-danger" dojoType="dijit.form.Button">Initialize database</button>
<?php } ?>
</p>
</form>
</td><td>
<form method="post">
<input type="hidden" name="DB_USER" value="<?php echo $DB_USER ?>"/>
<input type="hidden" name="DB_PASS" value="<?php echo $DB_PASS ?>"/>
<input type="hidden" name="DB_NAME" value="<?php echo $DB_NAME ?>"/>
<input type="hidden" name="DB_HOST" value="<?php echo $DB_HOST ?>"/>
<input type="hidden" name="DB_PORT" value="<?php echo $DB_PORT ?>"/>
<input type="hidden" name="DB_TYPE" value="<?php echo $DB_TYPE ?>"/>
<input type="hidden" name="SELF_URL_PATH" value="<?php echo $SELF_URL_PATH ?>"/>
<input type="hidden" name="op" value="skipschema">
<p><button type="submit" dojoType="dijit.form.Button">Skip initialization</button></p>
</form>
</td></tr></table>
<?php
} else if ($op == 'installschema' || $op == 'skipschema') {
$pdo = pdo_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME, $DB_TYPE, $DB_PORT);
if (!$pdo) {
print_error("Unable to connect to database using specified parameters.");
exit;
}
if ($op == 'installschema') {
print "<h2>Initializing database...</h2>";
$lines = explode(";", preg_replace("/[\r\n]/", "",
file_get_contents("../schema/ttrss_schema_".basename($DB_TYPE).".sql")));
foreach ($lines as $line) {
if (strpos($line, "--") !== 0 && $line) {
$res = $pdo->query($line);
if (!$res) {
print_notice("Query: $line");
print_error("Error: " . implode(", ", $this->pdo->errorInfo()));
}
}
}
print_notice("Database initialization completed.");
} else {
print_notice("Database initialization skipped.");
}
print "<h2>Generated configuration file</h2>";
print "<p>Copy following text and save as <code>config.php</code> in the data directory. It is suggested to read through the file to the end in case you need any options changed fom default values.</p>";
print "<p>After copying the file, you will be able to login with default username and password combination: <code>admin</code> and <code>password</code>. Don't forget to change the password immediately!</p>"; ?>
<form action="" method="post">
<input type="hidden" name="op" value="saveconfig">
<input type="hidden" name="DB_USER" value="<?php echo $DB_USER ?>"/>
<input type="hidden" name="DB_PASS" value="<?php echo $DB_PASS ?>"/>
<input type="hidden" name="DB_NAME" value="<?php echo $DB_NAME ?>"/>
<input type="hidden" name="DB_HOST" value="<?php echo $DB_HOST ?>"/>
<input type="hidden" name="DB_PORT" value="<?php echo $DB_PORT ?>"/>
<input type="hidden" name="DB_TYPE" value="<?php echo $DB_TYPE ?>"/>
<input type="hidden" name="SELF_URL_PATH" value="<?php echo $SELF_URL_PATH ?>"/>
<?php print "<textarea rows='20' style='width : 100%'>";
echo make_config($DB_TYPE, $DB_HOST, $DB_USER, $DB_NAME, $DB_PASS,
$DB_PORT, $SELF_URL_PATH);
print "</textarea>"; ?>
<hr/>
<?php if (is_writable("../data")) { ?>
<p>We can also try saving the file automatically now.</p>
<p><button type="submit" dojoType='dijit.form.Button' class='alt-primary'>Save configuration</button></p>
</form>
<?php } else {
print_error("Unfortunately, data directory is not writable, so we're unable to save config.php automatically.");
}
print_notice("You can generate the file again by changing the form above.");
} else if ($op == "saveconfig") {
print "<h2>Saving configuration file to parent directory...</h2>";
if (!file_exists("../data/config.php")) {
$fp = fopen("../data/config.php", "w");
if ($fp) {
$written = fwrite($fp, make_config($DB_TYPE, $DB_HOST,
$DB_USER, $DB_NAME, $DB_PASS,
$DB_PORT, $SELF_URL_PATH));
if ($written > 0) {
print_notice("Successfully saved config.php. You can try <a href=\"..\">loading agriget now</a>.");
} else {
print_notice("Unable to write into config.php in data directory.");
}
fclose($fp);
} else {
print_error("Unable to open config.php in data directory for writing.");
}
} else {
print_error("config.php already present in data directory, refusing to overwrite.");
}
}
?>
</div>
</body>
</html>

473
js/AppBase.js Normal file
View File

@ -0,0 +1,473 @@
'use strict'
/* global __, ngettext */
define(["dojo/_base/declare"], function (declare) {
return declare("fox.AppBase", null, {
_initParams: [],
_rpc_seq: 0,
hotkey_prefix: 0,
hotkey_prefix_pressed: false,
hotkey_prefix_timeout: 0,
constructor: function() {
window.onerror = this.Error.onWindowError;
},
getInitParam: function(k) {
return this._initParams[k];
},
setInitParam: function(k, v) {
this._initParams[k] = v;
},
enableCsrfSupport: function() {
Ajax.Base.prototype.initialize = Ajax.Base.prototype.initialize.wrap(
function (callOriginal, options) {
if (App.getInitParam("csrf_token") != undefined) {
Object.extend(options, options || { });
if (Object.isString(options.parameters))
options.parameters = options.parameters.toQueryParams();
else if (Object.isHash(options.parameters))
options.parameters = options.parameters.toObject();
options.parameters["csrf_token"] = App.getInitParam("csrf_token");
}
return callOriginal(options);
}
);
},
urlParam: function(param) {
return String(window.location.href).parseQuery()[param];
},
next_seq: function() {
this._rpc_seq += 1;
return this._rpc_seq;
},
get_seq: function() {
return this._rpc_seq;
},
setLoadingProgress: function(p) {
loading_progress += p;
if (dijit.byId("loading_bar"))
dijit.byId("loading_bar").update({progress: loading_progress});
if (loading_progress >= 90) {
$("overlay").hide();
}
},
keyeventToAction: function(event) {
const hotkeys_map = App.getInitParam("hotkeys");
const keycode = event.which;
const keychar = String.fromCharCode(keycode);
if (keycode == 27) { // escape and drop prefix
this.hotkey_prefix = false;
}
if (!this.hotkey_prefix && hotkeys_map[0].indexOf(keychar) != -1) {
this.hotkey_prefix = keychar;
$("cmdline").innerHTML = keychar;
Element.show("cmdline");
window.clearTimeout(this.hotkey_prefix_timeout);
this.hotkey_prefix_timeout = window.setTimeout(() => {
this.hotkey_prefix = false;
Element.hide("cmdline");
}, 3 * 1000);
event.stopPropagation();
return false;
}
Element.hide("cmdline");
let hotkey_name = "";
if (event.type == "keydown") {
hotkey_name = "(" + keycode + ")";
// ensure ^*char notation
if (event.shiftKey) hotkey_name = "*" + hotkey_name;
if (event.ctrlKey) hotkey_name = "^" + hotkey_name;
if (event.altKey) hotkey_name = "+" + hotkey_name;
if (event.metaKey) hotkey_name = "%" + hotkey_name;
} else {
hotkey_name = keychar ? keychar : "(" + keycode + ")";
}
const hotkey_full = this.hotkey_prefix ? this.hotkey_prefix + " " + hotkey_name : hotkey_name;
this.hotkey_prefix = false;
let action_name = false;
for (const sequence in hotkeys_map[1]) {
if (hotkeys_map[1].hasOwnProperty(sequence)) {
if (sequence == hotkey_full) {
action_name = hotkeys_map[1][sequence];
break;
}
}
}
console.log('keyeventToAction', hotkey_full, '=>', action_name);
return action_name;
},
cleanupMemory: function(root) {
const dijits = dojo.query("[widgetid]", dijit.byId(root).domNode).map(dijit.byNode);
dijits.each(function (d) {
dojo.destroy(d.domNode);
});
$$("#" + root + " *").each(function (i) {
i.parentNode ? i.parentNode.removeChild(i) : true;
});
},
helpDialog: function(topic) {
const query = "backend.php?op=backend&method=help&topic=" + encodeURIComponent(topic);
if (dijit.byId("helpDlg"))
dijit.byId("helpDlg").destroyRecursive();
const dialog = new dijit.Dialog({
id: "helpDlg",
title: __("Help"),
style: "width: 600px",
href: query,
});
dialog.show();
},
displayDlg: function(title, id, param, callback) {
Notify.progress("Loading, please wait...", true);
const query = {op: "dlg", method: id, param: param};
xhrPost("backend.php", query, (transport) => {
try {
const content = transport.responseText;
let dialog = dijit.byId("infoBox");
if (!dialog) {
dialog = new dijit.Dialog({
title: title,
id: 'infoBox',
style: "width: 600px",
onCancel: function () {
return true;
},
onExecute: function () {
return true;
},
onClose: function () {
return true;
},
content: content
});
} else {
dialog.attr('title', title);
dialog.attr('content', content);
}
dialog.show();
Notify.close();
if (callback) callback(transport);
} catch (e) {
this.Error.report(e);
}
});
return false;
},
handleRpcJson: function(transport) {
const netalert = $$("#toolbar .net-alert")[0];
try {
const reply = JSON.parse(transport.responseText);
if (reply) {
const error = reply['error'];
if (error) {
const code = error['code'];
const msg = error['message'];
console.warn("[handleRpcJson] received fatal error ", code, msg);
if (code != 0) {
/* global ERRORS */
this.Error.fatal(ERRORS[code], {info: msg, code: code});
return false;
}
}
const seq = reply['seq'];
if (seq && this.get_seq() != seq) {
console.log("[handleRpcJson] sequence mismatch: ", seq, '!=', this.get_seq());
return true;
}
const message = reply['message'];
if (message == "UPDATE_COUNTERS") {
console.log("need to refresh counters...");
Feeds.requestCounters(true);
}
const counters = reply['counters'];
if (counters)
Feeds.parseCounters(counters);
const runtime_info = reply['runtime-info'];
if (runtime_info)
App.parseRuntimeInfo(runtime_info);
if (netalert) netalert.hide();
return reply;
} else {
if (netalert) netalert.show();
Notify.error("Communication problem with server.");
}
} catch (e) {
if (netalert) netalert.show();
Notify.error("Communication problem with server.");
console.error(e);
}
return false;
},
parseRuntimeInfo: function(data) {
for (const k in data) {
if (data.hasOwnProperty(k)) {
const v = data[k];
console.log("RI:", k, "=>", v);
if (k == "daemon_is_running" && v != 1) {
Notify.error("<span onclick=\"App.explainError(1)\">Update daemon is not running.</span>", true);
return;
}
if (k == "recent_log_events") {
const alert = $$(".log-alert")[0];
if (alert) {
v > 0 ? alert.show() : alert.hide();
}
}
if (k == "daemon_stamp_ok" && v != 1) {
Notify.error("<span onclick=\"App.explainError(3)\">Update daemon is not updating feeds.</span>", true);
return;
}
if (k == "max_feed_id" || k == "num_feeds") {
if (App.getInitParam(k) != v) {
console.log("feed count changed, need to reload feedlist.");
Feeds.reload();
}
}
this.setInitParam(k, v);
}
}
PluginHost.run(PluginHost.HOOK_RUNTIME_INFO_LOADED, data);
},
backendSanityCallback: function (transport) {
const reply = JSON.parse(transport.responseText);
/* global ERRORS */
if (!reply) {
this.Error.fatal(ERRORS[3], {info: transport.responseText});
return;
}
if (reply['error']) {
const code = reply['error']['code'];
if (code && code != 0) {
return this.Error.fatal(ERRORS[code],
{code: code, info: reply['error']['message']});
}
}
console.log("sanity check ok");
const params = reply['init-params'];
if (params) {
console.log('reading init-params...');
for (const k in params) {
if (params.hasOwnProperty(k)) {
switch (k) {
case "label_base_index":
_label_base_index = parseInt(params[k]);
break;
case "cdm_auto_catchup":
if (params[k] == 1) {
const hl = $("headlines-frame");
if (hl) hl.addClassName("auto_catchup");
}
break;
case "hotkeys":
// filter mnemonic definitions (used for help panel) from hotkeys map
// i.e. *(191)|Ctrl-/ -> *(191)
const tmp = [];
for (const sequence in params[k][1]) {
if (params[k][1].hasOwnProperty(sequence)) {
const filtered = sequence.replace(/\|.*$/, "");
tmp[filtered] = params[k][1][sequence];
}
}
params[k][1] = tmp;
break;
}
console.log("IP:", k, "=>", params[k]);
this.setInitParam(k, params[k]);
}
}
// PluginHost might not be available on non-index pages
if (typeof PluginHost !== 'undefined')
PluginHost.run(PluginHost.HOOK_PARAMS_LOADED, App._initParams);
}
this.initSecondStage();
},
toggleNightMode: function() {
const link = $("theme_css");
if (link) {
let user_theme = "";
let user_css = "";
if (link.getAttribute("href").indexOf("themes/agriget-night.css") == -1) {
user_css = "themes/agriget-night.css?" + Date.now();
user_theme = "agriget-night.css";
} else {
user_theme = "agriget.css";
user_css = "css/default.css?" + Date.now();
}
$("main").fade({duration: 0.5, afterFinish: () => {
link.setAttribute("href", user_css);
$("main").appear({duration: 0.5});
xhrPost("backend.php", {op: "rpc", method: "setpref", key: "USER_CSS_THEME", value: user_theme}, (transport) => { window.location.reload(false); });
}});
}
},
explainError: function(code) {
return this.displayDlg(__("Error explained"), "explainError", code);
},
Error: {
fatal: function (error, params) {
params = params || {};
if (params.code) {
if (params.code == 6) {
window.location.href = "index.php";
return;
} else if (params.code == 5) {
window.location.href = "public.php?op=dbupdate";
return;
}
}
return this.report(error,
Object.extend({title: __("Fatal error")}, params));
},
report: function(error, params) {
params = params || {};
if (!error) return;
console.error("[Error.report]", error, params);
const message = params.message ? params.message : error.toString();
try {
xhrPost("backend.php",
{op: "rpc", method: "log",
file: params.filename ? params.filename : error.fileName,
line: params.lineno ? params.lineno : error.lineNumber,
msg: message,
context: error.stack},
(transport) => {
console.warn("[Error.report] log response", transport.responseText);
});
} catch (re) {
console.error("[Error.report] exception while saving logging error on server", re);
}
try {
if (dijit.byId("exceptionDlg"))
dijit.byId("exceptionDlg").destroyRecursive();
let stack_msg = "";
if (error.stack)
stack_msg += `<div><b>Stack trace:</b></div>
<textarea name="stack" readonly="1">${error.stack}</textarea>`;
if (params.info)
stack_msg += `<div><b>Additional information:</b></div>
<textarea name="stack" readonly="1">${params.info}</textarea>`;
let content = `<div class="error-contents">
<p class="message">${message}</p>
${stack_msg}
<div class="dlgButtons">
<button dojoType="dijit.form.Button"
onclick=\"dijit.byId('exceptionDlg').hide()">${__('Close this window')}</button>
</div>
</div>`;
const dialog = new dijit.Dialog({
id: "exceptionDlg",
title: params.title || __("Unhandled exception"),
style: "width: 600px",
content: content
});
dialog.show();
} catch (de) {
console.error("[Error.report] exception while showing error dialog", de);
alert(error.stack ? error.stack : message);
}
},
onWindowError: function (message, filename, lineno, colno, error) {
// called without context (this) from window.onerror
App.Error.report(error,
{message: message, filename: filename, lineno: lineno, colno: colno});
},
}
});
});

Some files were not shown because too many files have changed in this diff Show More