Initial commit

Functional, without SSO
This commit is contained in:
Jimmy Monin
2016-09-18 11:03:26 +02:00
commit 57708e3169
253 changed files with 30787 additions and 0 deletions

674
LICENSE 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:
{project} Copyright (C) {year} {fullname}
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>.

19
README.md Normal file
View File

@ -0,0 +1,19 @@
LBCAlerte for YunoHost
---------------------
Logiciel pour être alerté de nouvelles annonces par mail, flux RSS et SMS sur Leboncoin et d'autres sites d'annonces.
**Version incluse:** 3.2
## Limitations
Application en français uniquement.
Ne fonctionne pas avec le SSO (comptes admin/utilisateurs séparés).
## Links
* Report a bug: https://github.com/JimboJoe/LBCAlerte_ynh/issues
* LBCAlerte website: https://alerte.ilatumi.org/
* YunoHost website: https://yunohost.org/

1
conf/LBCAlerte.cron Normal file
View File

@ -0,0 +1 @@
*/5 * * * * www-data /usr/bin/php -f #DESTDIR#/check.php

33
conf/nginx.conf Normal file
View File

@ -0,0 +1,33 @@
location YNH_WWW_PATH {
# Path to source
alias YNH_WWW_ALIAS ;
# Example PHP configuration (remove if not used)
index index.php;
# Common parameter to increase upload size limit in conjuction with dedicated php-fpm file
#client_max_body_size 50M;
try_files $uri $uri/ index.php;
location ~ [^/]\.php(/|$) {
fastcgi_split_path_info ^(.+?\.php)(/.*)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
# Filename to be changed if dedicated php-fpm process is required
# This is to be used INSTEAD of line above
# Don't forget to adjust scripts install/upgrade/remove/backup accordingly
#
#fastcgi_pass unix:/var/run/php5-fpm-YNH_WWW_APP.sock;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param REMOTE_USER $remote_user;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param SCRIPT_FILENAME $request_filename;
}
# PHP configuration end
# Include SSOWAT user panel.
include conf.d/yunohost_panel.conf.inc;
}

66
manifest.json Normal file
View File

@ -0,0 +1,66 @@
{
"name": "LBCAlerte",
"id": "LBCAlerte",
"packaging_format": 1,
"description": {
"en": "LBCAlerte package for YunoHost.",
"fr": "Application LBCAlerte pour YunoHost."
},
"url": "https://alerte.ilatumi.org/",
"license": "free",
"maintainer": {
"name": "JimboJoe",
"email": "jimmy@monin.net",
"url": ""
},
"requirements": {
"yunohost": ">> 2.4.0"
},
"multi_instance": true,
"services": [
"nginx",
"php5-fpm",
"mysql"
],
"arguments": {
"install" : [
{
"name": "domain",
"type": "domain",
"ask": {
"en": "Choose a domain name for LBCAlerte",
"fr": "Choisissez un nom de domaine pour LBCAlerte"
},
"example": "example.com"
},
{
"name": "path",
"type": "path",
"ask": {
"en": "Choose a path for LBCAlerte",
"fr": "Choisissez un chemin pour LBCAlerte"
},
"example": "/LBCAlerte",
"default": "/LBCAlerte"
},
{
"name": "password",
"type": "password",
"ask": {
"en": "Password for admin account",
"fr": "Mot de passe compte admin"
},
"example": "password"
},
{
"name": "is_public",
"type": "boolean",
"ask": {
"en": "Is it a public application?",
"fr": "Est-ce une application publique ?"
},
"default": true
}
]
}
}

25
scripts/backup Normal file
View File

@ -0,0 +1,25 @@
#!/bin/bash
# Exit on command errors and treat unset variables as an error
set -eu
# See comments in install script
app=$YNH_APP_INSTANCE_NAME
# Source YunoHost helpers
source /usr/share/yunohost/helpers
# Backup sources & data
# Note: the last argument is where to save this path, see the restore script.
ynh_backup "/var/www/${app}" "sources"
# Dump the database
dbname=$app
dbuser=$app
dbpass=$(ynh_app_setting_get "$app" mysqlpwd)
mysqldump -u "$dbuser" -p"$dbpass" --no-create-db "$dbname" > ./dump.sql
# Copy NGINX and cron configuration
domain=$(ynh_app_setting_get "$app" domain)
ynh_backup "/etc/nginx/conf.d/${domain}.d/${app}.conf" "nginx.conf"
ynh_backup "/etc/cron.d/${app}" "conf/cron"

83
scripts/install Normal file
View File

@ -0,0 +1,83 @@
#!/bin/bash
# Exit on command errors and treat unset variables as an error
set -eu
# This is a multi-instance app, meaning it can be installed several times independently
# The id of the app as stated in the manifest is available as $YNH_APP_ID
# The instance number is available as $YNH_APP_INSTANCE_NUMBER (equals "1", "2", ...)
# The app instance name is available as $YNH_APP_INSTANCE_NAME
# - the first time the app is installed, YNH_APP_INSTANCE_NAME = ynhexample
# - the second time the app is installed, YNH_APP_INSTANCE_NAME = ynhexample__2
# - ynhexample__{N} for the subsequent installations, with N=3,4, ...
# The app instance name is probably what you are interested the most, since this is
# guaranteed to be unique. This is a good unique identifier to define installation path,
# db names, ...
app=$YNH_APP_INSTANCE_NAME
# Retrieve arguments
domain=$YNH_APP_ARG_DOMAIN
path=$YNH_APP_ARG_PATH
password=$YNH_APP_ARG_PASSWORD
is_public=$YNH_APP_ARG_IS_PUBLIC
# Source YunoHost helpers
source /usr/share/yunohost/helpers
# Save app settings
ynh_app_setting_set "$app" is_public "$is_public"
# Check domain/path availability
sudo yunohost app checkurl "${domain}${path}" -a "$app" \
|| ynh_die "Path not available: ${domain}${path}"
# Copy source files
src_path=/var/www/$app
sudo mkdir -p $src_path/var
sudo cp -a ../sources/. $src_path
# Set permissions to app files
# you may need to make some file and/or directory writeable by www-data (nginx user)
sudo chown -R root: $src_path
# Generate MySQL password and create database
dbuser=$app
dbname=$app
dbpass=$(ynh_string_random 12)
ynh_app_setting_set "$app" mysqlpwd "$dbpass"
ynh_mysql_create_db "$dbname" "$dbuser" "$dbpass"
# Load initial SQL into the new database
#ynh_mysql_connect_as "$dbuser" "$dbpass" "$dbname" < "../sources/sql/mysql.init.sql"
# Modify Nginx configuration file and copy it to Nginx conf directory
nginx_conf=../conf/nginx.conf
sed -i "s@YNH_WWW_PATH@$path@g" $nginx_conf
sed -i "s@YNH_WWW_ALIAS@$src_path/@g" $nginx_conf
# If a dedicated php-fpm process is used:
# Don't forget to modify ../conf/nginx.conf accordingly or your app will not work!
# sed -i "s@YNH_WWW_APP@$app@g" $nginx_conf
sudo cp $nginx_conf /etc/nginx/conf.d/$domain.d/$app.conf
# Set permissions and reload nginx (needed at this stage for the PHP piwigo installation process)
sudo service nginx reload
sudo yunohost app setting "$app" unprotected_uris -v "/"
sudo yunohost app ssowatconf
# Configure LBCAlerte via curl
sleep 2
curl --resolve $domain:443:127.0.0.1 -kL -X POST https://$domain$path/index.php?mod=install --data "password=$password&confirmPassword=$password&type=db&db[host]=localhost&db[user]=$dbuser&db[password]=$dbpass&db[dbname]=$dbname" > /tmp/LBCAlerte-install.log 2>&1
#protect URIs if private
if [ $is_public -eq 0 ];
then
sudo yunohost app setting "$app" -d unprotected_uris
sudo yunohost app setting "$app" protected_uris -v "/"
fi
# Add cron job
cron_path="/etc/cron.d/$app"
sed -i "s@#DESTDIR#@${src_path}@g" ../conf/LBCAlerte.cron
sudo cp ../conf/LBCAlerte.cron "$cron_path"
sudo chmod 644 "$cron_path"

31
scripts/remove Normal file
View File

@ -0,0 +1,31 @@
#!/bin/bash
# See comments in install script
app=$YNH_APP_INSTANCE_NAME
# Source YunoHost helpers
source /usr/share/yunohost/helpers
# Retrieve app settings
domain=$(ynh_app_setting_get "$app" domain)
# Remove sources
sudo rm -rf /var/www/$app
# Remove nginx configuration file
sudo rm -f /etc/nginx/conf.d/$domain.d/$app.conf
### PHP (remove if not used) ###
# If a dedicated php-fpm process is used:
# sudo rm -f /etc/php5/fpm/pool.d/$app.conf
# sudo service php5-fpm reload
### PHP end ###
# Drop MySQL database and user
dbname=$app
dbuser=$app
ynh_mysql_drop_db "$dbname" || true
ynh_mysql_drop_user "$dbuser" || true
# Reload nginx service
sudo service nginx reload

40
scripts/restore Normal file
View File

@ -0,0 +1,40 @@
#!/bin/bash
# Exit on command errors and treat unset variables as an error
set -eu
# See comments in install script
app=$YNH_APP_INSTANCE_NAME
# Source YunoHost helpers
source /usr/share/yunohost/helpers
# Retrieve old app settings
domain=$(ynh_app_setting_get "$app" domain)
path=$(ynh_app_setting_get "$app" path)
# Check domain/path availability
sudo yunohost app checkurl "${domain}${path}" -a "$app" \
|| ynh_die "Path not available: ${domain}${path}"
# Restore sources & data
src_path="/var/www/${app}"
sudo cp -a ./sources "$src_path"
# Restore permissions to app files
# you may need to make some file and/or directory writeable by www-data (nginx user)
sudo chown -R root: "$src_path"
# Create and restore the database
dbname=$app
dbuser=$app
dbpass=$(ynh_app_setting_get "$app" mysqlpwd)
ynh_mysql_create_db "$dbname" "$dbuser" "$dbpass"
ynh_mysql_connect_as "$dbuser" "$dbpass" "$dbname" < ./dump.sql
# Restore NGINX and cron configuration
sudo cp -a ./nginx.conf "/etc/nginx/conf.d/${domain}.d/${app}.conf"
sudo cp -a ./conf/cron "/etc/cron.d/${app}"
# Restart webserver
sudo service nginx reload

125
sources/CHANGELOG.txt Normal file
View File

@ -0,0 +1,125 @@
## Version 3.2
* correction: si CURLOPT_FOLLOWLOCATION désactivé, suivre manuellement les redirections.
* correction: utiliser portail.free.fr pour le test de connexion distant.
* correction: utiliser le protocol HTTPs pour Leboncoin et alerte.ilatumi.org.
* correction: supprimer le nom du fichier dans l'URL de base de LBCAlerte.
* correction: crash possible si URL invalide.
* correction: amélioration des infos de log pour la tâche cron.
## Version 3.1
* ajout: prise en charge de SeLoger.com.
* correction: last_id contient maintenant l'ID de la dernière annonce et max_id l'ID max trouvé.
* correction: indiquer l'URL mobile seulement si disponible pour le site d'annonce.
* correction: si pas de date de publication fournie, on désactive la détection des annonces remontées.
* correction: date optionnelle dans les flux RSS.
* correction: date mise à jour du parser pour le nouveau site LBC.
## Version 3.0
* ajout: liens modifier, supprimer et activer/désactiver dans les mails d'alerte.
* ajout: bouton permettant de réinitialiser les alertes afin de recevoir toutes les dernières annonces.
* correction: amélioration de la mise à jour automatique.
## Version 2.9
* correction: prise en charge du protocole HTTPS pour les URL Leboncoin.
* correction: utiliser le protocole HTTPS pour les URL externe (Google) (fixes 34).
## Version 2.8
* ajout: en charge de NotityMyAndroid et Pushover pour les alertes.
* correction: mise en forme de la liste des catégories des formulaires (fixes #29)
* correction: ne pas échapper les caractères spéciaux pour l'URL de recherche dans le flux RSS (fixes #27)
* correction: indiquer le nombre de nouelles annonces dans les mails (fixes #24)
* correction: lien vers la version mobile de l'annonce dans le mail d'alerte (fixes #17).
## Version 2.7
* ajout: message "Pas de photo disponible." dans les flux RSS lorsqu'une annonce n'a pas de photo.
* ajout: mise en place d'une nouvelle structure de classe pour permettre l'ajout d'autre site d'annonce dans le système.
* ajout: prise en charge du site d'annonce Olx.ua
* correction: supprimer le trie par prix lors de l'enregistrement des URLs (fixes #30).
* correction: configurer correctement l'envoi des mails (fixes #28).
* correction: avertissement sur l'utilisation du filtre sur catégorie (fixes #22).
* correction: ne pas activer CURLOPT_FOLLOWLOCATION si open_basedir définit (fixes #18).
* correction: le fichier lock ne fait pas son boulot et des tâches parallèles s'exécutaient.
* correction: enlever la date pour l'ID des éléments de flux (risque de doublon pour Olx)
* correction: utiliser \AdService\SiteConfigFactory::factory pour valider l'URL de recherche.
* correction: mise en forme du rendu des alertes.
* correction: orthographe.
* supprimer: système de daemon car non utilisé.
## Version 2.6.2
* ajout: oublie d'ajout d'une colonne en BDD.
* correction: modification du parser d'annonce suite à modif sur Leboncoin.
## Version 2.6.1
* correction: crash mise à jour.
## Version 2.6
* ajout: option pour ne pas recevoir les annonces remontées (évite les doublons)
* ajout: prise en charge des notifications SMS OVH et Pushbullet.
* correction: installation bloquée par le système de mise à jour automatique.
* correction: définir la propriété Sender de PHPMailer afin d'éviter de passer en spam.
## Version 2.5
* ajout: gestion de la mise à jour automatique.
* ajout: possibilité d'utiliser une base de données (MySQL) pour stocker les informations.
* ajout: configuration du stockage des données dans l'administration.
* ajout: possibilité de changer le type de stockage avec prise en charge d'une migration (seulement fichier > BDD).
* correction: ne pas logger "Contrôle de l'alerte " si l'alerte n'a pas besoin d'être analysée.
* correction: masquer les colonnes "Prix" et "Villes" du tableau d'alerte si non utilisées.
* correction: refonte graphique et simplification des formulaires + correctons divers bugs.
## Version 2.4.1
* correction: faute orthographe dans nom de méthode.
## Version 2.4
* ajout: notification par SMS pour les abonnés Free Mobile.
* ajout: numéroter les lignes dans le tableau des alertes mails.
* ajout: filtre multi départements en complément du filtre multi villes (thx @greenchap).
* ajout: trie des alertes par email ou par titre.
* ajout: configurer l'UTF-8 pour les fonctions mb_*
* ajout: prise en charge de certain proxy web (expérimental).
* amélioration: formulaire d'ajout et de modification d'alerte améliorer.
* correction: conflit de session possible si installation en parallèle avec d'autre application (sous dossier).
* correction: trier les groupes par ordre alphabétique.
* correction: corriger la définition du type de proxy.
* utiliser file_get_contents/file_put_contents au lieu de "rename" (problème de droit).
## Version 2.3
* correction: mise en place de rotation de log (5*3Mo max).
* correction: paramètre invalide pour la fonction date.
* correction: tester la connexion même si aucun proxy spécifié.
## Version 2.2
* ajout: possibilité de spécifier plusieurs adresses de destinataire pour les alertes mails.
* amélioration de l'affichage de la liste des alertes.
* correction: crash de check.php si une adresse mail est invalide.
* correction: vérifier la prise en charge des SIGNAL.
## Version 2.1
* correction: check.php crash sur variable inéxistante.
## Version 2.0
* fusion de LBCRss et LBCMail.
* ajout: installateur.
* ajout: panneau d'administration (gestion proxy, configuration envoi de mail, etc.).
* ajout: gestion de compte utilisateur.
* ajout: que ce soit pour les flux RSS ou les alertes mail, une identification est requise.
* ajout: possibilité de recevoir les nouvelles annonces dans des mails séparés.
* ajout: nouveau système de contrôle des alertes.
* ajout: inclure l'URL de recherche dans le mail.

674
sources/LICENSE 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:
{project} Copyright (C) {year} {fullname}
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>.

17
sources/README.md Normal file
View File

@ -0,0 +1,17 @@
LBCAlerte
======
Alerte mail et RSS pour Leboncoin.fr
## Introduction
À quoi sert cette application ?
* recevoir des alertes mails sur vos recherches.
* générer des flux RSS pour vos recherches.
* recevoir des alertes SMS pour les abonnés Free Mobile.
* compléter vos recherches avec des filtres supplémentaires (multi-categories, multi-villes, etc.).
## Documentation
Pour l'installation et la configuration, une documentation est disponible sur le site officiel :
https://alerte.ilatumi.org

View File

@ -0,0 +1,6 @@
<?php
if ($auth->getUsername() != "admin") {
header("HTTP/1.1 403 Forbidden");
exit;
}

View File

@ -0,0 +1,21 @@
<?php
$user = new \App\User\User();
$errors = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_POST["username"]) || !trim($_POST["username"])) {
$errors["username"] = "Veuillez indiquer un nom d'utilisateur.";
} else {
$user->setUsername(trim($_POST["username"]));
}
if (empty($_POST["password"])) {
$errors["password"] = "Veuillez indiquer un mot de passe.";
} elseif (empty($_POST["password"]) || $_POST["password"] != $_POST["confirmPassword"]) {
$errors["confirmPassword"] = "Les deux mots de passe ne correspondent pas.";
}
if (empty($errors)) {
$user->setPassword(sha1($_POST["password"]));
$userStorage->save($user);
header("LOCATION: ?mod=admin&a=users");
exit;
}
}

View File

@ -0,0 +1,15 @@
<?php
if (!isset($_GET["username"]) || !$user = $userStorage->fetchByUsername($_GET["username"])) {
header("LOCATION: ?mod=admin&a=users");
exit;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$userStorage->delete($user);
$configAlert = DOCUMENT_ROOT."/var/configs/".$user->getUsername().".csv";
if (is_file($configAlert)) {
unlink($configAlert);
}
header("LOCATION: ?mod=admin&a=users");
exit;
}

View File

@ -0,0 +1,12 @@
<?php
$filename = DOCUMENT_ROOT."/var/log/info.log";
$lines = array();
if (is_file($filename)) {
$lines = file($filename);
if (count($lines) > 200) {
$lines = array_slice($lines, count($lines)-200);
}
}

View File

@ -0,0 +1,76 @@
<?php
$errors = array();
$options = array(
"host" => "", "port" => "",
"username" => "", "password" => "",
"secure" => "",
"from" => "",
"testMail" => ""
);
if ($config->hasSection("mailer")) {
if ($smtp = $config->get("mailer", "smtp", array())) {
$options = array_merge($options, $smtp);
}
if ($from = $config->get("mailer", "from", null)) {
$options["from"] = $from;
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$options = array_merge($options, array_map("trim", $_POST));
if (isset($_POST["testSMTP"])) {
require_once "PHPMailer/class.phpmailer.php";
$mailer = new PHPMailer($exceptions=true);
$mailer->setLanguage("fr", DOCUMENT_ROOT."/lib/PHPMailer/language/");
$mailer->CharSet = "utf-8";
if (!empty($options["host"])) {
$mailer->Host = $options["host"];
$mailer->isSMTP();
}
if (!empty($options["port"])) {
$mailer->Port = $options["port"];
$mailer->isSMTP();
}
if (!empty($options["username"])) {
$mailer->SMTPAuth = true;
$mailer->Username = $options["username"];
}
if (!empty($options["password"])) {
$mailer->SMTPAuth = true;
$mailer->Password = $options["password"];
}
if (!empty($options["secure"])) {
$mailer->SMTPSecure = $options["secure"];
}
if (!empty($options["from"])) {
$mailer->Sender = $options["from"];
$mailer->From = $options["from"];
}
if (empty($_POST["testMail"])) {
$errors["testMail"] = "Indiquez une adresse e-mail pour l'envoi du test.";
} else {
$mailer->clearAddresses();
$mailer->addAddress($_POST["testMail"]);
if ($options["from"]) {
$mailer->FromName = $options["from"];
}
$mailer->Subject = "Test d'envoi de mail";
$mailer->Body = "Bravo.\nVotre configuration mail est validée.";
try {
$mailer->send();
$testSended = true;
} catch (phpmailerException $e) {
$testError = $e->getMessage();
}
}
} else {
$config->set("mailer", "smtp", array(
"host" => $options["host"], "port" => $options["port"],
"username" => $options["username"], "password" => $options["password"],
"secure" => $options["secure"]
));
$config->set("mailer", "from", $options["from"]);
$config->save();
header("LOCATION: ?mod=admin&a=mail");
exit;
}
}

View File

@ -0,0 +1,46 @@
<?php
$errors = array();
$options = array(
"proxy_ip" => $config->get("proxy", "ip", ""),
"proxy_port" => $config->get("proxy", "port", ""),
"proxy_user" => $config->get("proxy", "user", ""),
"proxy_password" => $config->get("proxy", "password", "")
);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$options = array_merge(array(
"proxy_ip" => "",
"proxy_port" => "",
"proxy_user" => ""
), array_map("trim", $_POST));
if (isset($options["proxy_ip"])) {
$options["proxy_ip"] = $options["proxy_ip"];
if (isset($options["proxy_port"])) {
$options["proxy_port"] = $options["proxy_port"];
}
}
if (isset($_POST["testProxy"])) {
$client->setProxyIp($options["proxy_ip"])
->setProxyPort($options["proxy_port"])
->setProxyUser($options["proxy_user"]);
if (!empty($options["proxy_password"])) {
$client->setProxyPassword($options["proxy_password"]);
}
$errors["test"] = array();
if (false === $client->request("http://portail.free.fr")) {
$errors["test"]["site"] = $client->getError();
}
if (false === $client->request("https://www.leboncoin.fr")) {
$errors["test"]["lbc"] = $client->getError();
}
} else {
$config->set("proxy", "ip", $options["proxy_ip"]);
$config->set("proxy", "port", $options["proxy_port"]);
$config->set("proxy", "user", $options["proxy_user"]);
if (!empty($options["proxy_password"])) {
$config->set("proxy", "password", $options["proxy_password"]);
}
$config->save();
header("LOCATION: ?mod=admin&a=proxy");
exit;
}
}

View File

@ -0,0 +1,102 @@
<?php
$storageType = $config->get("storage", "type", "files");
$currentStorage = array(
"type" => $config->get("storage", "type", "files"),
"options" => $config->get("storage", "options", array())
);
$errors = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_POST["type"]) || !trim($_POST["type"])
|| !in_array($_POST["type"], array("files", "db"))) {
$errors["type"] = "Type de stockage invalide.";
}
$currentStorage = array(
"type" => isset($_POST["type"]) ? $_POST["type"] : $currentStorage["type"],
"options" => array_merge($currentStorage["options"],
isset($_POST["options"]) && is_array($_POST["options"]) ? $_POST["options"] : array())
);
if ($_POST["type"] == "db") {
if (!isset($_POST["options"]["password"])) {
$_POST["options"]["password"] = "";
}
if (empty($_POST["options"]["host"])) {
$errors["host"] = "Nom d'hôte invalide.";
}
if (empty($_POST["options"]["user"])) {
$errors["user"] = "Spécifiez un nom d'utilisateur.";
}
if (empty($_POST["options"]["dbname"])) {
$errors["dbname"] = "Spécifiez une base de données.";
}
if (!empty($_POST["options"]["user"]) && !empty($_POST["options"]["dbname"])) {
// test de connexion
$dbConnection = new mysqli(
$_POST["options"]["host"], $_POST["options"]["user"],
$_POST["options"]["password"], $_POST["options"]["dbname"]);
if ($dbConnection->connect_error) {
$errors["host"] = "Connexion impossible à la base de données.";
}
}
}
if (empty($errors)) {
if ($_POST["type"] == "db") {
$config->set("storage", "type", "db");
$config->set("storage", "options", array(
"host" => $_POST["options"]["host"],
"user" => $_POST["options"]["user"],
"password" => $_POST["options"]["password"],
"dbname" => $_POST["options"]["dbname"],
));
} else {
$config->set("storage", "type", "files");
}
$config->save();
if ($_POST["type"] == "db" && !empty($_POST["importtodb"])) {
// installation de la base
require DOCUMENT_ROOT."/others/install/schema.php";
$userStorageDb = new \App\Storage\Db\User($dbConnection);
$users = array();
$usersDb = $userStorageDb->fetchAll(); // utilisateurs actuellement en BDD
foreach ($usersDb AS $user) {
$users[$user->getUsername()] = $user;
}
unset($usersDb);
$userStorageFiles = new \App\Storage\File\User(DOCUMENT_ROOT."/var/users.db");
$usersFiles = $userStorageFiles->fetchAll();
foreach ($usersFiles AS $user) {
if (!isset($users[$user->getUsername()])) {
$userStorageDb->save($user);
}
}
$users = $userStorageDb->fetchAll();
foreach ($users AS $user) {
$file = DOCUMENT_ROOT."/var/configs/".$user->getUsername().".csv";
if (!is_file($file)) {
continue;
}
$storageFiles = new \App\Storage\File\Alert($file);
$storageDb = new \App\Storage\Db\Alert($userStorageDb->getDbConnection(), $user);
$alerts = $storageFiles->fetchAll();
foreach ($alerts AS $alert) {
$storageDb->save($alert, $forceinsert=true);
}
}
}
header("LOCATION: ?mod=admin&a=storage&success=1");
exit;
}
}

View File

@ -0,0 +1,76 @@
<?php
$updater = new \App\Updater();
if ($url = $config->get("general", "url_version", "")) {
$updater->setUrlVersion($url);
}
if ($url = $config->get("general", "url_archive", "")) {
$updater->setUrlArchive($url);
}
if (isset($_POST["checkVersion"])) {
unset($_SESSION["lbcLastVersion"], $_SESSION["lbcLastVersionTime"]);
header("LOCATION: ?mod=admin&a=upgrade");
exit;
}
if ($_SERVER["REQUEST_METHOD"] == "POST" || empty($_SESSION["lbcLastVersion"]) || empty($_SESSION["lbcLastVersionTime"])) {
try {
$_SESSION["lbcLastVersion"] = $updater->getLastVersion();
$_SESSION["lbcLastVersionTime"] = time();
} catch (Exception $e) {
}
}
$lastVersion = "";
if (!empty($_SESSION["lbcLastVersion"])) {
$lastVersion = $_SESSION["lbcLastVersion"];
}
$errors = array();
$allow_update = true;
if (!is_writable(DOCUMENT_ROOT."/version.php")) {
$allow_update = false;
$errors[] = "Le fichier version.php est en lecture seule, la mise à jour automatique ne peut être effectuée.".
"<br />Vérifiez que tous les fichiers soient accéssibles en écriture (pas seulement le fichier version.php).";
} elseif (is_file(DOCUMENT_ROOT."/var/.lock")) {
$allow_update = false;
$errors[] = "Une vérification de nouvelle annonce est en cours, veuillez attendre la fin de celle-ci pour mettre à jour.";
}
$currentVersion = $config->get("general", "version");
$upgradeStarted = version_compare($currentVersion, APPLICATION_VERSION, "<");
$upgradeAvailable = version_compare($currentVersion, $lastVersion, "<");
if ($upgradeStarted && !empty($_POST["upgrade"])) {
$updater->update($currentVersion, $lastVersion);
// mise à jour du numéro de version dans la config.
$config->set("general", "version", $lastVersion);
$config->save();
header("LOCATION: ?mod=admin&a=upgrade");
exit;
} elseif ($allow_update && $upgradeAvailable && !empty($_POST["upgrade"])) {
file_put_contents(DOCUMENT_ROOT."/var/.lock_update", time());
try {
$updater->installFiles($lastVersion);
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
$version = require DOCUMENT_ROOT."/version.php";
if ($version != $lastVersion) {
$errors[] = "La mise à jour semble avoir échouée.";
} else {
$updater->update($currentVersion, $lastVersion);
// mise à jour du numéro de version dans la config.
$config->set("general", "version", $lastVersion);
$config->save();
}
unlink(DOCUMENT_ROOT."/var/.lock_update");
if (!$errors) {
header("LOCATION: ?mod=admin&a=upgrade");
exit;
}
}

View File

@ -0,0 +1,2 @@
<?php
$users = $userStorage->fetchAll();

View File

@ -0,0 +1,30 @@
<form action="" method="post" autocomplete="off">
<h2>Ajouter un utilisateur</h2>
<dl>
<dt><label for="username">Nom d'utilisateur</label></dt>
<dd>
<input type="text" id="username" name="username" value="<?php
echo htmlspecialchars($user->getUsername());
?>" />
<?php if (isset($errors["username"])) : ?>
<p class="error"><?php echo $errors["username"]; ?></p>
<?php endif; ?>
</dd>
<dt><label for="password">Mot de passe</label></dt>
<dd>
<input type="password" id="password" name="password" />
<?php if (isset($errors["password"])) : ?>
<p class="error"><?php echo $errors["password"]; ?></p>
<?php endif; ?>
</dd>
<dt><label for="confirmPassword">Confirmez le mot de passe</label></dt>
<dd>
<input type="password" id="confirmPassword" name="confirmPassword" />
<?php if (isset($errors["confirmPassword"])) : ?>
<p class="error"><?php echo $errors["confirmPassword"]; ?></p>
<?php endif; ?>
</dd>
</dl>
<p><input type="submit" value="Enregistrer" />
| <a href="?mod=admin&amp;a=users">annuler</a></p>
</form>

View File

@ -0,0 +1,6 @@
<form action="" method="post">
<p>
Supprimer l'utilisateur "<?php echo htmlspecialchars($user->getUsername()); ?>" ?<br />
<input type="submit" value="Oui" /> | <a href="?mod=admin&amp;a=users">non</a>
</p>
</form>

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>Alerte mail pour Leboncoin.fr</title>
<meta charset="utf-8">
<meta name="robots" content="none">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="static/styles.css?v=<?php echo APPLICATION_VERSION; ?>" />
</head>
<body>
<?php if ($userAuthed) : ?>
<header>
<h1><a href="./">Système d'alerte Leboncoin</a></h1>
<ul class="topmenu">
<li<?php echo $action === "users"?' class="active"':''; ?>><a href="?mod=admin&amp;a=users">Utilisateurs</a></li>
<li<?php echo $action === "storage"?' class="active"':''; ?>><a href="?mod=admin&amp;a=storage">Stockage</a></li>
<li<?php echo $action === "proxy"?' class="active"':''; ?>><a href="?mod=admin&amp;a=proxy">Proxy</a></li>
<li<?php echo $action === "mail"?' class="active"':''; ?>><a href="?mod=admin&amp;a=mail">Mail</a></li>
<li<?php echo $action === "upgrade"?' class="active"':''; ?>><a href="?mod=admin&amp;a=upgrade">Mise à jour</a></li>
<li<?php echo $action === "log"?' class="active"':''; ?>><a href="?mod=admin&amp;a=log">Log</a></li>
<li style="float: right;"><a href="?a=logout">Déconnexion <span>(<?php echo htmlspecialchars($userAuthed->getUsername()); ?>)</span></a></li>
</ul>
</header>
<?php endif; ?>
<div class="content">
<?php echo $content; ?>
</div>
<?php if ($userAuthed) : ?>
<footer>
<?php if ($userAuthed->getUsername() == "admin") : ?>
<a href="?mod=admin&amp;a=users" style="color: #EF0000;">Administration</a> |
<?php endif; ?>
Version <?php echo APPLICATION_VERSION; ?>
| <a href="https://github.com/Blount/LBCAlerte/issues">Rapporter un bug</a>
</footer>
<?php endif; ?>
</body>
</html>

View File

@ -0,0 +1,19 @@
<h2>Fichier jounal</h2>
<p>Voici les dernières lignes du fichier log: <?php
echo htmlspecialchars($filename, null, "UTF-8"); ?></p>
<ul id="lastlog" class="lastlog">
<?php if (0 == count($lines)) : ?>
<li>Rien à signaler.</li>
<?php else: ?>
<?php foreach ($lines AS $line) : ?>
<li<?php
if (strpos($line, "ERROR")) {
echo ' class="lastlog-error"';
}
?>><?php echo htmlspecialchars($line, null, "UTF-8"); ?></li>
<?php endforeach; ?>
<?php endif; ?>
</ul>
<script type="text/javascript">
document.getElementById("lastlog").scrollTop = 50000;
</script>

View File

@ -0,0 +1,84 @@
<?php if (empty($errors) && isset($_POST["testSMTP"])) : ?>
<div style="width: 680px; border: 1px solid #666666; margin-bottom: 10px; padding: 10px;">
<h2>Test d'envoi de mail</h2>
<?php if (isset($testSended)) : ?>
<p style="font-weight: bold; color: #333399;">Vous devriez recevoir un mail de test à l'adresse suivante : <?php
echo htmlspecialchars($options["testMail"]);
?></p>
<?php elseif (isset($testError)): ?>
<p style="font-weight: bold; color: #993333;">Erreur de l'envoi du mail : <?php
echo htmlspecialchars($testError);
?></p>
<?php endif; ?>
</div>
<?php endif; ?>
<form action="" method="post" autocomplete="off">
<h2>Configuration de l'envoi des mails</h2>
<dl>
<dt style="clear: both;"><label for="from">Adresse e-mail à indiquer comme expéditeur</label></dt>
<dd>
<input type="text" id="from" name="from" value="<?php
echo htmlspecialchars($options["from"]);
?>" size="40" />
</dd>
<dt style="margin-bottom: 5px;"><label>Serveur SMTP externe</label></dt>
<dd style="float: left;">
&nbsp;<label for="host">Hôte / IP :</label><br />
<input type="text" id="host" name="host" value="<?php
echo htmlspecialchars($options["host"]);
?>" />
</dd>
<dd style="float: left; margin-left: 10px;">
&nbsp;<label for="port">Port :</label><br />
<input type="text" id="port" name="port" value="<?php
echo htmlspecialchars($options["port"]);
?>" size="10" />
<?php if (isset($errors["server"])) : ?>
<p class="error"><?php echo $errors["server"]; ?></p>
<?php endif; ?>
</dd>
<dt style="clear: both; margin-bottom: 5px;">
<label>Utilisateur et mot de passe SMTP si une identification est nécessaire</label>
</dt>
<dd style="float: left;">
&nbsp;<label for="username">Utilisateur :</label><br />
<input type="text" id="username" name="username" value="<?php
echo htmlspecialchars($options["username"]);
?>" />
</dd>
<dd style="float: left; margin-left: 10px;">
&nbsp;<label for="password">Mot de passe :</label><br />
<input type="password" id="password" name="password" value="<?php
echo htmlspecialchars($options["password"]);
?>" />
<?php if (isset($errors["password"])) : ?>
<p class="error"><?php echo $errors["password"]; ?></p>
<?php endif; ?>
</dd>
<dt style="clear: both;"><label for="secure">Sécurité de la connexion</label></dt>
<dd>
<select name="secure">
<option value=""<?php echo empty($options["secure"])?' selected="selected"':''; ?>>Aucune</option>
<option value="tls"<?php echo $options["secure"] == "tls"?' selected="selected"':''; ?>>TLS</option>
<option value="ssl"<?php echo $options["secure"] == "ssl"?' selected="selected"':''; ?>>SSL</option>
</select>
</dd>
<dt style="clear: both;">
<label for="testMail">Pour tester l'envoi des mails, entrez une adresse et cliquez sur "Tester"</label>
</dt>
<dd>
<input type="text" id="testMail" name="testMail" value="<?php
echo htmlspecialchars($options["testMail"]);
?>" size="40" />
<?php if (isset($errors["testMail"])) : ?>
<p class="error"><?php echo $errors["testMail"]; ?></p>
<?php endif; ?>
<p class="description">Un mail de test sera envoyé à cette adresse</p>
</dd>
</dl>
<p>
<input type="submit" value="Enregistrer" />
<input type="submit" name="testSMTP" value="Tester" />
</p>
</form>

View File

@ -0,0 +1,62 @@
<?php if (isset($_POST["testProxy"])) : ?>
<div style="width: 680px; border: 1px solid #666666; margin-bottom: 10px; padding: 10px;">
<h2>Test de connexion</h2>
<ul>
<?php if (!$client->hasProxy()) : ?>
<li>aucun proxy configuré.</li>
<?php else: ?>
<li>utilisation d'un proxy pour la connexion.</li>
<?php endif; ?>
<li>Connexion à <a href="http://portail.free.fr">portail.free.fr</a> :
<?php if (isset($errors["test"]["site"])) : ?>
<span style="color: red;">échec</span>
(erreur: <?php echo htmlspecialchars($errors["test"]["site"]); ?>)
<?php else: ?>
<span style="color: #009900;">réussi</span>
<?php endif; ?>
</li>
<li>Connexion à <a href="https://www.leboncoin.fr">Leboncoin</a> :
<?php if (isset($errors["test"]["lbc"])) : ?>
<span style="color: red;">échec</span>
(erreur: <?php echo htmlspecialchars($errors["test"]["lbc"]); ?>)
<?php else: ?>
<span style="color: #009900;">réussi</span>
<?php endif; ?>
</li>
</ul>
</div>
<?php endif; ?>
<h2>Configuration d'un serveur proxy</h2>
<p>
Vous pouvez configurer ici un proxy de connexion qui sera
utilisé pour se connecter à Leboncoin.
</p>
<form action="" method="post" autocomplete="off">
<h2>Paramètres du proxy</h2>
<dl>
<dt><label for="proxy_ip">Adresse du proxy</label></dt>
<dd><input type="text" id="proxy_ip" name="proxy_ip" value="<?php
echo htmlspecialchars($options["proxy_ip"]);
?>" /></dd>
<dt><label for="proxy_port">Port</label></dt>
<dd><input type="text" id="proxy_port" name="proxy_port" value="<?php
echo htmlspecialchars($options["proxy_port"]);
?>" size="7" /></dd>
</dl>
<h2>Le serveur proxy requiert une identification ?</h2>
<dl>
<dt><label for="proxy_user">Utilisateur</label></dt>
<dd><input type="text" id="proxy_user" name="proxy_user" value="<?php
echo htmlspecialchars($options["proxy_user"]);
?>" />
</dd>
<dt><label for="proxy_password">Mot de passe</label></dt>
<dd><input type="password" id="proxy_password" name="proxy_password"<?php
echo !empty($options["proxy_password"])?' placeholder="Valeur masquée"':""; ?> /></dd>
</dl>
<p>
<input type="submit" value="Enregistrer" />
<input type="submit" name="testProxy" value="Tester la connexion" />
</p>
</form>

View File

@ -0,0 +1,102 @@
<?php if (isset($_GET["success"])) : ?>
<p style="color: #001FA6;"><strong>Mise à jour de la configuration effectuée.</strong></p>
<?php endif; ?>
<p>Vous pouvez choisir de stocker les données de l'application
(utilisateurs, alertes, options, etc.)
dans des fichiers ou en base de données (MySQL).</p>
<form action="?mod=admin&amp;a=storage" method="post" autocomplete="off">
<h2>Configuration du stockage des données</h2>
<dl>
<dt><label>Type de stockage :</label></dt>
<dd>
<label for="typefiles">
<input type="radio" id="typefiles" name="type" value="files"<?php
echo "files" == $currentStorage["type"] ? ' checked="checked"' : ""
?> />
fichiers
</label>
<label for="typedb" style="margin-left: 40px;">
<input type="radio" id="typedb" name="type" value="db"<?php
echo "db" == $currentStorage["type"] ? ' checked="checked"' : ""
?> />
base de données MySQL
</label>
<?php if (!empty($errors["type"])) : ?>
<p class="error"><?php echo $errors["type"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options"><label for="options-host">Adresse du serveur</label></dt>
<dd class="storage-db-options">
<input type="text" id="options-host" name="options[host]" value="<?php
echo isset($currentStorage["options"]["host"]) ? htmlspecialchars($currentStorage["options"]["host"]) : "localhost"
?>" />
<?php if (!empty($errors["host"])) : ?>
<p class="error"><?php echo $errors["host"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options"><label for="options-user">Utilisateur</label></dt>
<dd class="storage-db-options">
<input type="text" id="options-user" name="options[user]" value="<?php
echo isset($currentStorage["options"]["user"]) ? htmlspecialchars($currentStorage["options"]["user"]) : ""
?>" />
<?php if (!empty($errors["user"])) : ?>
<p class="error"><?php echo $errors["user"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options"><label for="options-password">Mot de passe</label></dt>
<dd class="storage-db-options">
<input type="password" id="options-password" name="options[password]" value="<?php
echo isset($currentStorage["options"]["password"]) ? htmlspecialchars($currentStorage["options"]["password"]) : ""
?>" />
<?php if (!empty($errors["password"])) : ?>
<p class="error"><?php echo $errors["password"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options"><label for="options-base">Nom de la base de données</label></dt>
<dd class="storage-db-options">
<input type="text" id="options-base" name="options[dbname]" value="<?php
echo isset($currentStorage["options"]["dbname"]) ? htmlspecialchars($currentStorage["options"]["dbname"]) : ""
?>" />
<?php if (!empty($errors["dbname"])) : ?>
<p class="error"><?php echo $errors["dbname"]; ?></p>
<?php endif; ?>
</dd>
<?php if (is_dir(DOCUMENT_ROOT."/var/configs") && 2 < count(scandir(DOCUMENT_ROOT."/var/configs"))) : ?>
<dt class="storage-db-options">
<label for="importtodb"><input type="checkbox" id="importtodb" name="importtodb" value="1"<?php
echo isset($_POST["importtodb"]) ? ' checked="checked"' : ""
?>" /> importer les données existantes dans la base de données.</label>
<?php if (!empty($errors["dbname"])) : ?>
<p class="error"><?php echo $errors["dbname"]; ?></p>
<?php endif; ?>
</dt>
<?php endif; ?>
</dl>
<p><input type="submit" value="Enregistrer" /></p>
</form>
<script type="text/javascript">
if (document.querySelectorAll) {
var elements = document.querySelectorAll(".storage-db-options");
var buttons = document.querySelectorAll("input[name=type]");
var fnCheck = function () {
var display = document.querySelector("input[value=db]").checked ? "block" : "none";
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = display;
}
};
for (var j = 0; j < buttons.length; j++) {
buttons[j].addEventListener("change", fnCheck);
}
fnCheck();
}
</script>

View File

@ -0,0 +1,54 @@
<?php if (!empty($errors)) : ?>
<p class="error">
<?php echo implode("<br />", $errors); ?>
</p>
<br />
<?php endif; ?>
<?php if ($upgradeStarted || $upgradeAvailable) : ?>
<p>
<strong><span style="color: #EF0000;">ATTENTION :</span>
avant de lancer la mise à jour automatique,
merci d'effectuer une sauvegarde de vos données actuelles.</strong>
</p>
<?php endif; ?>
<?php if ($upgradeStarted) : ?>
<form action="" method="post">
<p>
Cliquer sur "Mettre à jour" afin de terminer la mise à jour.
</p>
<p>
<input type="hidden" name="upgrade" value="1" />
<input type="submit" value="Mettre à jour" />
</p>
</form>
<?php elseif ($upgradeAvailable) : ?>
<h2>Une mise à jour est disponible</h2>
<p>
Vous utilisez actuellement la version <strong><?php echo APPLICATION_VERSION; ?></strong>.
La version <strong><?php echo $lastVersion; ?></strong> est disponible.
</p>
<?php if ($allow_update) : ?>
<form action="" method="post">
<p>
<input type="hidden" name="upgrade" value="1" />
<input type="submit" value="Mettre à jour" />
</p>
</form>
<?php endif; ?>
<?php else : ?>
<p><strong>Vous utilisez déjà la dernière version.</strong></p>
<form action="" method="post">
<p>
Dernière vérification effectuée le <?php echo date("d/m/Y à H:i", $_SESSION["lbcLastVersionTime"]); ?>
</p>
<p>
<input type="hidden" name="checkVersion" value="1" />
<input type="submit" value="Vérifier à nouveau" />
</p>
</form>
<?php endif; ?>

View File

@ -0,0 +1,23 @@
<p><a href="?mod=admin&amp;a=add-user">Nouvel utilisateur</a></p>
<table style="width: 500px; text-align: left;">
<thead>
<tr>
<th>Nom d'utilisateur</th>
<th>&nbsp;</th>
</tr>
</thead>
<tbody>
<?php foreach ($users AS $user) : ?>
<tr>
<td><?php echo htmlspecialchars($user->getUsername()); ?></td>
<td>
<?php if ($user->getUsername() != "admin") : ?>
<a href="?mod=admin&amp;a=delete-user&amp;username=<?php echo urlencode($user->getUsername()); ?>">supprimer</a>
<?php else: ?>
-
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

View File

@ -0,0 +1,25 @@
<?php
$username = "";
$errors = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!isset($_POST["username"]) || !trim($_POST["username"])) {
$errors["password"] = "Nom d'utilisateur ou mot de passe incorrecte.";
} else {
$username = $_POST["username"];
}
if (empty($errors)) {
$password = isset($_POST["password"])?$_POST["password"]:"";
$auth->setUsername($username)
->setPassword(sha1($password));
if ($auth->authenticate()) {
if ($module == "default" && $action == "login") {
$redirect = "./";
} else {
$redirect = $_SERVER["REQUEST_URI"];
}
header("LOCATION: ".$redirect);
exit;
}
$errors["password"] = "Nom d'utilisateur ou mot de passe incorrecte.";
}
}

View File

@ -0,0 +1,5 @@
<?php
$auth->clear();
header("LOCATION: ./");
exit;

View File

@ -0,0 +1,11 @@
<p>
Utilisez le menu ci-dessus pour accéder à la gestion de vos alertes mails
et des flux RSS.
</p>
<p>
Vous pouvez aussi :
</p>
<ul>
<li><a href="https://github.com/Blount/LBCAlerte/issues">rapporter des bugs</a>.</li>
<li><a href="https://alerte.ilatumi.org/forum">utiliser le forum</a> pour obtenir de l'aide.</li>
</ul>

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html>
<head>
<title>Alerte mail pour Leboncoin.fr</title>
<meta charset="utf-8">
<meta name="robots" content="none">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="static/styles.css?v=<?php echo APPLICATION_VERSION; ?>" />
</head>
<body>
<?php if ($userAuthed) : ?>
<header>
<h1><a href="./">Système d'alerte Leboncoin</a></h1>
<ul class="topmenu">
<li<?php echo $module === "default"?' class="active"':''; ?>><a href="./?"><img src="static/images/home.png" alt="" /></a></li>
<li<?php echo $module === "mail"?' class="active"':''; ?>><a href="?mod=mail">Mail / SMS</a></li>
<li<?php echo $module === "rss"?' class="active"':''; ?>><a href="?mod=rss">RSS</a></li>
<li<?php echo $module === "user"?' class="active"':''; ?>><a href="?mod=user&amp;a=settings">Paramètres</a></li>
<li><a href="https://alerte.ilatumi.org/forum">Forum</a></li>
<li style="float: right;"><a href="?a=logout">Déconnexion <span>(<?php echo htmlspecialchars($userAuthed->getUsername()); ?>)</span></a></li>
</ul>
</header>
<?php endif; ?>
<div class="content">
<?php echo $content; ?>
</div>
<?php if ($userAuthed) : ?>
<footer>
<?php if ($userAuthed->getUsername() == "admin") : ?>
<a href="?mod=admin&amp;a=users" style="color: #EF0000;">Administration</a> |
<?php endif; ?>
Version <?php echo APPLICATION_VERSION; ?>
| <a href="https://github.com/Blount/LBCAlerte/issues">Rapporter un bug</a>
</footer>
<?php endif; ?>
<script type="text/javascript" src="static/scripts.js"></script>
</body>
</html>

View File

@ -0,0 +1,26 @@
<form action="" method="post">
<h2>Identifiez-vous</h2>
<dl>
<dt>
<label for="username">Nom d'utilisateur</label>
</dt>
<dd>
<input type="text" id="username" name="username" value="<?php
echo htmlspecialchars($username);
?>" />
<?php if (isset($errors["username"])) : ?>
<p class="error"><?php echo $errors["username"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="password">Mot de passe</label>
</dt>
<dd>
<input type="password" id="password" name="password" />
<?php if (isset($errors["password"])) : ?>
<p class="error"><?php echo $errors["password"]; ?></p>
<?php endif; ?>
</dd>
</dl>
<p><input type="submit" value="Connexion" /></p>
</form>

View File

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<title>Mise à jour en cours.</title>
<meta charset="utf-8">
</head>
<body>
<?php if ($userAuthed && $userAuthed->isAdmin()) : ?>
<p><a href="">Cliquez-ici afin d'achever la mise à jour.</a></p>
<?php else: ?>
<p>Mise à jour en cours, veuillez patienter quelques instants …</p>
<?php endif; ?>
</body>
</html>

View File

@ -0,0 +1,11 @@
<?php
if (is_file($config->getFilename()) && !isset($_GET["success"])) {
header("LOCATION: ?mod=install&a=upgrade");
exit;
}
if ($action == "upgrade" && $auth->getUsername() != "admin") {
header("HTTP/1.1 403 Forbidden");
exit;
}

View File

@ -0,0 +1,83 @@
<?php
$errors = array();
$formErrors = array();
$messages = array();
if (!is_writable(DOCUMENT_ROOT."/var")) {
$errors[] = "Il est nécessaire de pouvoir écrire dans le dossier 'var' (".DOCUMENT_ROOT."/var".").";
}
if (!$errors && $_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["password"])) {
$formErrors["password"] = "Ce champ est obligatoire";
} elseif (empty($_POST["confirmPassword"]) || $_POST["confirmPassword"] != $_POST["password"]) {
$formErrors["confirmPassword"] = "Les mots de passe ne sont pas identiques.";
}
if (!empty($_POST["db"]["user"]) || !empty($_POST["db"]["dbname"])) {
if (empty($_POST["db"]["host"])) {
$formErrors["db"]["host"] = "Nom d'hôte invalide.";
}
if (empty($_POST["db"]["user"])) {
$formErrors["db"]["user"] = "Spécifiez un nom d'utilisateur.";
}
if (empty($_POST["db"]["dbname"])) {
$formErrors["db"]["dbname"] = "Spécifiez une base de données.";
}
if (!empty($_POST["db"]["user"]) && !empty($_POST["db"]["dbname"])) {
// test de connexion
$dbConnection = new mysqli(
$_POST["db"]["host"], $_POST["db"]["user"],
$_POST["db"]["password"], $_POST["db"]["dbname"]);
if ($dbConnection->connect_error) {
$formErrors["db"]["host"] = "Connexion impossible à la base de données.";
}
}
}
if (!$formErrors) {
if (!is_dir(DOCUMENT_ROOT."/var/configs")) {
mkdir(DOCUMENT_ROOT."/var/configs");
}
if (!is_dir(DOCUMENT_ROOT."/var/feeds")) {
mkdir(DOCUMENT_ROOT."/var/feeds");
}
if (!is_dir(DOCUMENT_ROOT."/var/log")) {
mkdir(DOCUMENT_ROOT."/var/log");
}
$config->set("general", "version", APPLICATION_VERSION);
if (isset($dbConnection)) {
$config->set("storage", "type", "db");
$config->set("storage", "options", array(
"host" => $_POST["db"]["host"],
"user" => $_POST["db"]["user"],
"password" => $_POST["db"]["password"],
"dbname" => $_POST["db"]["dbname"],
));
} else {
$config->set("storage", "type", "files");
}
$config->save();
$storageType = $config->get("storage", "type", "files");
if ($storageType == "db") {
// installation de la base
require DOCUMENT_ROOT."/others/install/schema.php";
$userStorage = new \App\Storage\Db\User($dbConnection);
} else {
$userStorage = new \App\Storage\File\User(DOCUMENT_ROOT."/var/users.db");
}
// table utilisateurs
$user = new \App\User\User(array(
"username" => "admin",
"password" => sha1($_POST["password"])
));
$userStorage->save($user);
header("LOCATION: ?mod=install&success=true");
exit;
}
}

View File

@ -0,0 +1,17 @@
<?php
if (!is_file($config->getFilename())) {
header("LOCATION: ?mod=install");
exit;
}
if ($auth->getUsername() != "admin") {
header("HTTP/1.1 403 Forbidden");
exit;
}
$require_upgrade = false;
if (-1 == version_compare($config->get("general", "version"), APPLICATION_VERSION)) {
$require_upgrade = true;
}

View File

@ -0,0 +1,116 @@
<?php if (!empty($errors)) : ?>
<ul class="error"><li><?php echo implode("</li><li>", $errors); ?></li></ul>
<?php else: ?>
<form action="" method="post">
<fieldset>
<legend>Nouvelle installation</legend>
<?php if (!isset($_GET["success"]) || $_GET["success"] != "true") : ?>
<dl>
<dt>Mot de passe admin :</dt>
<dd>
<input type="password" name="password" />
<?php if (!empty($formErrors["password"])) : ?>
<p class="error"><?php echo $formErrors["password"]; ?></p>
<?php endif; ?>
</dd>
<dt>Confirmer le mot de passe :</dt>
<dd>
<input type="password" name="confirmPassword" />
<?php if (!empty($formErrors["confirmPassword"])) : ?>
<p class="error"><?php echo $formErrors["confirmPassword"]; ?></p>
<?php endif; ?>
</dd>
</dl>
<h2>Stockage des données</h2>
<p>
Par défaut, les données (utilisateurs, alertes, etc.)
sont stockées dans des fichiers. C'est l'installation la plus simple
et rapide ne nécessitant que peu de connaissance.</p>
<p>
Toutefois, si vous le souhaitez vous pouvez enregistrer les données
dans une base de données MySQL (plus adapté et plus fiable).
</p>
<dl>
<dt>Type de stockage :</dt>
<dd>
<label for="typefiles">
<input type="radio" id="typefiles" name="type" value="files"<?php
echo isset($_POST["type"]) && "files" == $_POST["type"] ? ' checked="checked"' : ""
?> />
fichiers
</label>
<label for="typedb" style="margin-left: 40px;">
<input type="radio" id="typedb" name="type" value="db"<?php
echo isset($_POST["type"]) && "db" == $_POST["type"] ? ' checked="checked"' : ""
?> />
base de données MySQL
</label>
<?php if (!empty($errors["type"])) : ?>
<p class="error"><?php echo $errors["type"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options">Hôte :</dt>
<dd class="storage-db-options">
<input type="text" name="db[host]" value="<?php
echo isset($_POST["db"]["host"]) ? htmlspecialchars($_POST["db"]["host"]) : "localhost"
?>" />
<?php if (!empty($formErrors["db"]["host"])) : ?>
<p class="error"><?php echo $formErrors["db"]["host"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options">Utilisateur :</dt>
<dd class="storage-db-options">
<input type="text" name="db[user]" value="<?php
echo isset($_POST["db"]["user"]) ? htmlspecialchars($_POST["db"]["user"]) : ""
?>" />
<?php if (!empty($formErrors["db"]["user"])) : ?>
<p class="error"><?php echo $formErrors["db"]["user"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options">Mot de passe :</dt>
<dd class="storage-db-options">
<input type="password" name="db[password]" value="<?php
echo isset($_POST["db"]["password"]) ? htmlspecialchars($_POST["db"]["password"]) : ""
?>" />
<?php if (!empty($formErrors["db"]["password"])) : ?>
<p class="error"><?php echo $formErrors["db"]["password"]; ?></p>
<?php endif; ?>
</dd>
<dt class="storage-db-options">Nom de la base de données :</dt>
<dd class="storage-db-options">
<input type="text" name="db[dbname]" value="<?php
echo isset($_POST["db"]["dbname"]) ? htmlspecialchars($_POST["db"]["dbname"]) : ""
?>" />
<?php if (!empty($formErrors["db"]["dbname"])) : ?>
<p class="error"><?php echo $formErrors["db"]["dbname"]; ?></p>
<?php endif; ?>
</dd>
<dt>Cliquez sur le bouton suivant pour lancer l'installation.</dt>
<dd><input type="submit" value="Installer" /></dd>
</dl>
<?php else: ?>
<p style="color: #001FA6;"><strong>Installation terminée.</strong></p>
<p>Vous pouvez vous connecter avec les identifiants suivants :<br />
<strong>Utilisateur:</strong> admin<br />
<strong>Mot de passe:</strong> spécifié lors de l'installation.</p>
<p><a href="./">continuer &gt;</a></p>
<?php endif; ?>
</fieldset>
</form>
<script type="text/javascript">
if (document.querySelectorAll) {
var elements = document.querySelectorAll(".storage-db-options");
var buttons = document.querySelectorAll("input[name=type]");
var fnCheck = function () {
var display = document.querySelector("input[value=db]").checked ? "block" : "none";
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = display;
}
};
for (var j = 0; j < buttons.length; j++) {
buttons[j].addEventListener("change", fnCheck);
}
fnCheck();
}
</script>
<?php endif; ?>

View File

@ -0,0 +1,5 @@
<?php if ($require_upgrade) : ?>
<p>Mise à jour de l'application</p>
<?php else: ?>
<p>Application à jour</p>
<?php endif; ?>

View File

@ -0,0 +1,9 @@
<?php
if ($action != "check") {
$storageType = $config->get("storage", "type", "files");
if ($storageType == "db") {
$storage = new \App\Storage\Db\Alert($dbConnection, $userAuthed);
} else {
$storage = new \App\Storage\File\Alert(DOCUMENT_ROOT."/var/configs/".$auth->getUsername().".csv");
}
}

View File

@ -0,0 +1,561 @@
<?php
set_time_limit(0);
use AdService\SiteConfigFactory;
class Main
{
/**
* @var HttpClientAbstract
*/
protected $_httpClient;
/**
* @var Config_Lite
*/
protected $_config;
/**
* @var PHPMailer
*/
protected $_mailer;
/**
* @var App\User\Storage
*/
protected $_userStorage;
protected $_lockFile;
protected $_logger;
protected $_running = false;
public function __construct(
\Config_Lite $config,
\HttpClientAbstract $client,
\App\Storage\User $userStorage)
{
$this->_config = $config;
if (function_exists("pcntl_signal")) {
pcntl_signal(SIGTERM, array($this, "sigHandler"));
pcntl_signal(SIGINT, array($this, "sigHandler"));
}
$this->_httpClient = $client;
$this->_userStorage = $userStorage;
$this->_logger = Logger::getLogger("main");
$this->_lockFile = DOCUMENT_ROOT."/var/.lock";
$this->_lock();
$this->_running = true;
$this->_logger->info("[Pid ".getmypid()."] Vérification des alertes.");
$this->_mailer = new PHPMailer($exceptions=true);
$this->_mailer->setLanguage("fr", DOCUMENT_ROOT."/lib/PHPMailer/language/");
$this->_mailer->CharSet = "utf-8";
if ($config->hasSection("mailer")) {
if ($smtp = $config->get("mailer", "smtp", array())) {
$this->_mailer->SMTPKeepAlive = true;
if (!empty($smtp["host"])) {
$this->_mailer->Host = $smtp["host"];
if (!empty($smtp["port"])) {
$this->_mailer->Port = $smtp["port"];
}
$this->_mailer->isSMTP();
}
if (!empty($smtp["username"])) {
$this->_mailer->SMTPAuth = true;
$this->_mailer->Username = $smtp["username"];
}
if (!empty($smtp["password"])) {
$this->_mailer->SMTPAuth = true;
$this->_mailer->Password = $smtp["password"];
}
if (!empty($smtp["secure"])) {
$this->_mailer->SMTPSecure = $smtp["secure"];
}
}
if ($from = $config->get("mailer", "from", null)) {
$this->_mailer->Sender = $from;
$this->_mailer->From = $from;
$this->_mailer->FromName = $from;
}
}
$this->_mailer->isHTML(true);
}
public function __destruct()
{
$this->shutdown();
}
public function check()
{
$checkStart = (int)$this->_config->get("general", "check_start", 7);
$checkEnd = (int)$this->_config->get("general", "check_end", 24);
if ($checkStart > 23) {
$checkStart = 0;
}
if ($checkEnd < 1) {
$checkEnd = 24;
}
$hour = (int)date("G");
if ($hour < $checkStart || $hour >= $checkEnd) {
$this->_logger->info("[Pid ".getmypid()."] Hors de la plage horaire. Contrôle annulé.");
return;
}
$this->_checkConnection();
$users = $this->_userStorage->fetchAll();
// génération d'URL court pour les SMS
$curlTinyurl = curl_init();
curl_setopt($curlTinyurl, CURLOPT_RETURNTRANSFER, 1);
$storageType = $this->_config->get("storage", "type", "files");
$baseurl = $this->_config->get("general", "baseurl", "");
foreach ($users AS $user) {
if ($storageType == "db") {
$storage = new \App\Storage\Db\Alert($this->_userStorage->getDbConnection(), $user);
$this->_logger->info("[Pid ".getmypid()."] USER : ".$user->getUsername());
} else {
$file = DOCUMENT_ROOT."/var/configs/".$user->getUsername().".csv";
if (!is_file($file)) {
continue;
}
$storage = new \App\Storage\File\Alert($file);
$this->_logger->info("[Pid ".getmypid()."] USER : ".$user->getUsername()." (".$file.")");
}
$reset_filename = DOCUMENT_ROOT."/var/tmp/reset_".$user->getId();
$reset = is_file($reset_filename);
if ($reset) {
unlink($reset_filename);
}
// configuration des notifications.
$notifications = array();
$notifications_params = $user->getOption("notification");
if ($notifications_params && is_array($notifications_params)) {
foreach ($notifications_params AS $notification_name => $options) {
if (!is_array($options)) {
continue;
}
try {
$notifications[$notification_name] = \Message\AdapterFactory::factory($notification_name, $options);
$this->_logger->debug(
"[Pid ".getmypid()."] USER : ".$user->getUsername().
" -> Notification ".get_class($notifications[$notification_name])." activée"
);
} catch (\Exception $e) {
$this->_logger->warn(
"[Pid ".getmypid()."] USER : ".$user->getUsername().
" -> Notification ".$notification_name." invalide"
);
}
}
}
$alerts = $storage->fetchAll();
$this->_logger->info(
"[Pid ".getmypid()."] USER : ".$user->getUsername()." -> ".
count($alerts)." alerte".(count($alerts) > 1 ? "s" : "").
" trouvée".(count($alerts) > 1 ? "s" : ""));
if (count($alerts) == 0) {
continue;
}
foreach ($alerts AS $i => $alert) {
$log_id = "[Pid ".getmypid()."] USER : ".$user->getUsername()." - ALERT ID : ".$alert->id." -> ";
try {
$config = SiteConfigFactory::factory($alert->url);
} catch (Exception $e) {
$this->_logger->warn($log_id.$e->getMessage());
continue;
}
$unique_ads = $user->getOption("unique_ads");
/**
* Si le site ne fourni pas de date par annonce,
* on est obligé de baser la dernière annonce reçue sur l'ID.
*/
if (!$config->getOption("has_date")) {
$unique_ads = true;
}
$currentTime = time();
if (!isset($alert->time_updated)) {
$alert->time_updated = 0;
}
if ($reset) {
$alert->time_updated = 0;
$alert->last_id = array();
$alert->max_id = 0;
$alert->time_last_ad = 0;
}
if (((int)$alert->time_updated + (int)$alert->interval*60) > $currentTime
|| $alert->suspend) {
continue;
}
$this->_logger->info($log_id."URL : ".$alert->url);
try {
$parser = \AdService\ParserFactory::factory($alert->url);
} catch (\AdService\Exception $e) {
$this->_logger->err($log_id." ".$e->getMessage());
continue;
}
$this->_logger->debug($log_id."Dernière mise à jour : ".(
!empty($alert->time_updated) ?
date("d/m/Y H:i", (int) $alert->time_updated) :
"inconnue"
));
$this->_logger->debug($log_id."Dernière annonce : ".(
!empty($alert->time_last_ad) ?
date("d/m/Y H:i", (int) $alert->time_last_ad) :
"inconnue"
));
$alert->time_updated = $currentTime;
if (!$content = $this->_httpClient->request($alert->url)) {
$this->_logger->error($log_id."Curl Error : ".$this->_httpClient->getError());
continue;
}
$cities = array();
if ($alert->cities) {
$cities = array_map("trim", explode("\n", mb_strtolower($alert->cities)));
}
$filter = new \AdService\Filter(array(
"price_min" => $alert->price_min,
"price_max" => $alert->price_max,
"cities" => $cities,
"price_strict" => (bool)$alert->price_strict,
"categories" => $alert->getCategories(),
"min_id" => $unique_ads ? $alert->max_id : 0,
"exclude_ids" => $alert->last_id,
));
$ads = $parser->process(
$content,
$filter,
parse_url($alert->url, PHP_URL_SCHEME)
);
$countAds = count($ads);
/**
* Migrer vers le nouveau système de détection d'annonce.
*/
if (is_numeric($alert->last_id)) {
$filter->setExcludeIds(array());
$alert->last_id = array();
$tmp_ads = $parser->process(
$content,
$filter,
parse_url($alert->url, PHP_URL_SCHEME)
);
foreach ($tmp_ads AS $tmp_ad) {
$alert->last_id[] = $tmp_ad->getId();
}
unset($tmp_ads, $tmp_ad);
}
if ($countAds == 0) {
$storage->save($alert);
continue;
}
$siteConfig = \AdService\SiteConfigFactory::factory($alert->url);
$newAds = array();
foreach ($ads AS $ad) {
$time = $ad->getDate();
$id = $ad->getId();
$newAds[$id] = require DOCUMENT_ROOT."/app/mail/views/mail-ad.phtml";
if (!in_array($id, $alert->last_id)) {
array_unshift($alert->last_id, $id);
}
if ($time && $alert->time_last_ad < $time) {
$alert->time_last_ad = $time;
}
if ($unique_ads && $id > $alert->max_id) {
$alert->max_id = $id;
}
}
// On conserve 250 IDs d'annonce vues.
if (250 < count($alert->last_id)) {
$alert->last_id = array_slice($alert->last_id, 0, 250);
}
if (!$newAds) {
$storage->save($alert);
continue;
}
$countAds = count($newAds);
$this->_logger->info(
$log_id.$countAds.
" annonce".($countAds > 1 ? "s" : "").
" trouvée".($countAds > 1?"s":"")
);
$this->_mailer->clearAddresses();
$error = false;
if ($alert->send_mail) {
try {
$emails = explode(",", $alert->email);
foreach ($emails AS $email) {
$this->_mailer->addAddress(trim($email));
}
} catch (phpmailerException $e) {
$this->_logger->warn($log_id.$e->getMessage());
$error = true;
}
if (!$error) {
if ($alert->group_ads) {
$newAdsCount = count($newAds);
$subject = "Alerte ".$siteConfig->getOption("site_name")." : ".$alert->title;
$message = '
<h1 style="font-size: 16px;">Alerte : '.htmlspecialchars($alert->title, null, "UTF-8").'</h1>
<p style="font-size: 14px; margin: 0;"><strong><a href="'.htmlspecialchars($alert->url, null, "UTF-8").'"
style="text-decoration: none; color: #0B6CDA;">LIEN DE RECHERCHE</a>';
if ($baseurl) {
$message .= '
- <a href="'.$baseurl.'?mod=mail&amp;a=form&amp;id='. $alert->id .
'" style="text-decoration: none; color: #E77600;">MODIFIER</a>
- <a href="'.$baseurl.'?mod=mail&amp;a=toggle_status&amp;s=suspend&amp;id='. $alert->id .
'" style="text-decoration: none; color: #999999;">ACTIVER / DÉSACTIVER</a>
- <a href="'.$baseurl.'?mod=mail&amp;a=form-delete&amp;id='. $alert->id .
'" style="text-decoration: none; color: #FF0000;">SUPPRIMER</a>
';
}
$message .= '</strong></p>';
$message .= '<hr />';
$message .= '<p style="font-size: 16px; margin: 10px 0;"><strong>'.
$newAdsCount.' nouvelle'.($newAdsCount > 1?'s':'').
' annonce'.($newAdsCount > 1?'s':'').
' - '.date("d/m/Y à H:i", $currentTime).'</strong></p>';
$message .= '<hr /><br />';
$message .= implode("<br /><hr /><br />", $newAds);
$message .= '<hr /><br />';
$this->_mailer->Subject = $subject;
$this->_mailer->Body = $message;
try {
$this->_mailer->send();
} catch (phpmailerException $e) {
$this->_logger->warn($log_id.$e->getMessage());
}
} else {
$newAds = array_reverse($newAds, true);
foreach ($newAds AS $id => $ad) {
$subject = ($alert->title?$alert->title." : ":"").$ads[$id]->getTitle();
$message = '
<h1 style="font-size: 16px;">Alerte : '.htmlspecialchars($alert->title, null, "UTF-8").'</h1>
<p style="font-size: 14px; margin: 0;"><strong><a href="'.htmlspecialchars($alert->url, null, "UTF-8").'"
style="text-decoration: none; color: #0B6CDA;">LIEN DE RECHERCHE</a>';
if ($baseurl) {
$message .= '
- <a href="'.$baseurl.'?mod=mail&amp;a=form&amp;id='. $alert->id .
'" style="text-decoration: none; color: #E77600;">MODIFIER</a>
- <a href="'.$baseurl.'?mod=mail&amp;a=toggle_status&amp;s=suspend&amp;id='. $alert->id .
'" style="text-decoration: none; color: #999999;">ACTIVER / DÉSACTIVER</a>
- <a href="'.$baseurl.'?mod=mail&amp;a=form-delete&amp;id='. $alert->id .
'" style="text-decoration: none; color: #FF0000;">SUPPRIMER</a>
';
}
$message .= '</strong></p>';
$message .= '<hr /><br />';
$message .= $ad;
$this->_mailer->Subject = $subject;
$this->_mailer->Body = $message;
try {
$this->_mailer->send();
} catch (phpmailerException $e) {
$this->_logger->warn($log_id.$e->getMessage());
}
}
}
}
}
if ($notifications && (
$alert->send_sms_free_mobile
|| $alert->send_sms_ovh
|| $alert->send_pushbullet
|| $alert->send_notifymyandroid
|| $alert->send_pushover
)) {
if ($countAds < 5) { // limite à 5 SMS
foreach ($newAds AS $id => $ad) {
$ad = $ads[$id]; // récupère l'objet.
$url = $ad->getLink();
if (false !== strpos($url, "leboncoin")) {
$url = "https://mobile.leboncoin.fr/vi/".$ad->getId().".htm";
}
curl_setopt($curlTinyurl, CURLOPT_URL, "http://tinyurl.com/api-create.php?url=".$url);
if ($url = curl_exec($curlTinyurl)) {
$msg = "Nouvelle annonce ".($alert->title?$alert->title." : ":"").$ad->getTitle();
$others = array();
if ($ad->getPrice()) {
$others[] = number_format($ad->getPrice(), 0, ',', ' ').$ad->getCurrency();
}
if ($ad->getCity()) {
$others[] = $ad->getCity();
} elseif ($ad->getCountry()) {
$others[] = $ad->getCountry();
}
if ($others) {
$msg .= " (".implode(", ", $others).")";
}
$params = array(
"title" => "Alerte ".$siteConfig->getOption("site_name"),
"description" => "Nouvelle annonce".($alert->title ? " pour : ".$alert->title : ""),
"url" => $url,
);
foreach ($notifications AS $key => $notifier) {
switch ($key) {
case "freeMobile":
$key_test = "send_sms_free_mobile";
break;
case "ovh":
$key_test = "send_sms_ovh";
break;
default:
$key_test = "send_".$key;
}
if (isset($alert->$key_test) && $alert->$key_test) {
try {
$notifier->send($msg, $params);
} catch (Exception $e) {
$this->_logger->warn(
$log_id."Erreur sur envoi via ".
get_class($notifier).
": (".$e->getCode().") ".
$e->getMessage()
);
}
}
}
}
}
} else { // envoi un msg global
curl_setopt($curlTinyurl, CURLOPT_URL, "http://tinyurl.com/api-create.php?url=".$alert->url);
if ($url = curl_exec($curlTinyurl)) {
$msg = "Il y a ".$countAds." nouvelles annonces pour votre alerte '".($alert->title?$alert->title:"sans nom")."'";
$params = array(
"title" => "Alerte ".$siteConfig->getOption("site_name"),
"description" => "Nouvelle".($countAds > 1 ? "s" : "").
" annonce".($countAds > 1 ? "s" : "").
($alert->title ? " pour : ".$alert->title : ""),
"url" => $url,
);
foreach ($notifications AS $key => $notifier) {
switch ($key) {
case "freeMobile":
$key_test = "send_sms_free_mobile";
break;
case "ovh":
$key_test = "send_sms_ovh";
break;
default:
$key_test = "send_".$key;
}
if (isset($alert->$key_test) && $alert->$key_test) {
try {
$notifier->send($msg, $params);
} catch (Exception $e) {
$this->_logger->warn(
$log_id."Erreur sur envoi via ".
get_class($notifier).
": (".$e->getCode().") ".
$e->getMessage()
);
}
}
}
}
}
}
$storage->save($alert);
}
}
curl_close($curlTinyurl);
$this->_mailer->smtpClose();
}
public function shutdown()
{
if ($this->_running && is_file($this->_lockFile)) {
unlink($this->_lockFile);
}
}
public function sigHandler($no)
{
if (in_array($no, array(SIGTERM, SIGINT))) {
$this->_logger->info("[Pid ".getmypid()."] QUIT (".$no.")");
$this->shutdown();
exit;
}
}
protected function _checkConnection()
{
// teste la connexion
$this->_httpClient->setDownloadBody(false);
if (false === $this->_httpClient->request("https://www.leboncoin.fr")) {
throw new Exception("Connexion vers https://www.leboncoin.fr échouée".
(($error = $this->_httpClient->getError())?" (erreur: ".$error.")":"").".");
}
if (200 != $code = $this->_httpClient->getRespondCode()) {
throw new Exception("Code HTTP différent de 200 : ".$code);
}
$this->_httpClient->setDownloadBody(true);
}
protected function _lock()
{
if (is_file($this->_lockFile)) {
throw new Exception("Un processus est en cours d'exécution.");
}
file_put_contents($this->_lockFile, time()."\n".getmypid());
return $this;
}
}
require __DIR__."/../../../bootstrap.php";
// lib
require_once "PHPMailer/class.phpmailer.php";
// modèle
$storageType = $config->get("storage", "type", "files");
if ($storageType == "db") {
$userStorage = new \App\Storage\Db\User($dbConnection);
} else {
$userStorage = new \App\Storage\File\User(DOCUMENT_ROOT."/var/users.db");
}
if (is_file(DOCUMENT_ROOT."/var/.lock_update")) {
Logger::getLogger("main")->info("Tâche annulée : une mise à jour de l'application est en cours.");
return;
}
try {
$main = new Main($config, $client, $userStorage);
} catch (\Exception $e) {
Logger::getLogger("main")->info($e->getMessage());
return;
}
try {
$main->check();
} catch (\Exception $e) {
Logger::getLogger("main")->warn($e->getMessage());
}
$main->shutdown();

View File

@ -0,0 +1,14 @@
<?php
if (!isset($_GET["id"])) {
header("LOCATION: ./?mod=mail"); exit;
}
$alert = $storage->fetchById($_GET["id"]);
if (!$alert->id) {
header("LOCATION: ./?mod=mail"); exit;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["id"]) && $_POST["id"] == $_GET["id"]) {
$storage->delete($alert);
}
header("LOCATION: ./?mod=mail"); exit;
}

View File

@ -0,0 +1,82 @@
<?php
if (isset($_GET["id"])) {
$alert = $storage->fetchById($_GET["id"]);
}
if (empty($alert)) {
$alert = new App\Mail\Alert();
}
$categoryCollection = new \Lbc\CategoryCollection();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach ($_POST AS $name => $value) {
if (is_array($value)) {
$_POST[$name] = array_map("trim", $_POST[$name]);
} else {
$_POST[$name] = trim($_POST[$name]);
}
}
$alert->fromArray($_POST);
if (empty($alert->send_mail)
&& empty($alert->send_sms_free_mobile)
&& empty($alert->send_sms_ovh)
&& empty($alert->send_pushbullet)
&& empty($alert->send_notifymyandroid)
&& empty($alert->send_pushover)
) {
$errors["send_type"] = "Vous devez sélectionner au moins un moyen de communication.";
}
if (empty($alert->email)) {
$errors["email"] = "Ce champ est obligatoire.";
}
if (empty($alert->title)) {
$errors["title"] = "Ce champ est obligatoire.";
}
if (empty($alert->price_min)) {
$alert->price_min = -1;
}
if (empty($alert->price_max)) {
$alert->price_max = -1;
}
if ($alert->price_min != (int)$alert->price_min) {
$errors["price"] = "Valeur de \"prix min\" non valide. ";
}
if ($alert->price_max != (int)$alert->price_max) {
$errors["price"] .= "Valeur de \"prix max\" non valide.";
}
if (!empty($_POST["price_strict"])) {
$alert->price_strict = (int)(bool)$_POST["price_strict"];
} else {
$alert->price_strict = false;
}
$alert->group = !empty($_POST["group"])?trim($_POST["group"]):"";
if (empty($alert->url)) {
$errors["url"] = "Ce champ est obligatoire.";
} else {
try {
$siteConfig = \AdService\SiteConfigFactory::factory($alert->url);
if (false !== strpos($alert->url, "leboncoin.fr")) {
$alert->url = rtrim(preg_replace("#(o|sp)=[0-9]*&?#", "", $alert->url), "?&");
}
} catch (\AdService\Exception $e) {
$errors["url"] = "Cette adresse ne semble pas valide.";
}
}
$alert->interval = (int)$alert->interval;
if ($alert->interval != (int)$alert->interval || $alert->interval < 0) {
$errors["interval"] = "Cette valeur n'est pas valide.";
}
if (empty($errors)) {
if (!empty($_POST["categories"])) {
if (is_array($alert->categories)) {
$alert->categories = implode(",", $_POST["categories"]);
} else {
$alert->categories = null;
}
} else {
$alert->categories = null;
}
$storage->save($alert);
header("LOCATION: ./?mod=mail"); exit;
}
}

View File

@ -0,0 +1,86 @@
<?php
if (isset($_GET["sort"])) {
if (in_array($_GET["sort"], array("title", "email"))) {
if (!isset($_SESSION["mail"]["sort"]) || $_SESSION["mail"]["sort"] != $_GET["sort"]) {
$_SESSION["mail"]["sort"] = $_GET["sort"];
$_SESSION["mail"]["order"] = "asc";
} elseif (!isset($_SESSION["mail"]["order"]) || $_SESSION["mail"]["order"] == "desc") {
$_SESSION["mail"]["order"] = "asc";
} else {
$_SESSION["mail"]["order"] = "desc";
}
}
header("LOCATION: ?mod=mail"); exit;
}
$alerts = $storage->fetchAll();
$sort = "";
$order = isset($_SESSION["mail"]["order"])?$_SESSION["mail"]["order"]:"asc";
if (isset($_SESSION["mail"]["sort"])) {
$sort = $_SESSION["mail"]["sort"];
setlocale(LC_CTYPE, "fr_FR.UTF-8");
usort($alerts, function ($alert1, $alert2) {
$key = $_SESSION["mail"]["sort"];
$param1 = mb_strtolower($alert1->$key);
$param2 = mb_strtolower($alert2->$key);
if ($key == "title" && function_exists("iconv")) {
$param1 = iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $param1);
$param2 = iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", $param2);
}
if ($param1 < $param2) {
return -1;
}
if ($param1 > $param2) {
return 1;
}
return 0;
});
}
if (isset($_SESSION["mail"]["order"]) && $_SESSION["mail"]["order"] == "desc") {
$alerts = array_reverse($alerts);
}
// configuration du tableau d'affichage
$showCities = false;
$showPrice = false;
// trie les alertes par groupes
$alertsByGroup = array();
$groups = array();
foreach ($alerts AS $alert) {
$group = $alert->group?$alert->group:"Sans groupe";
$groups[] = $group;
$alertsByGroup[$group][] = $alert;
if (-1 != $alert->price_min || -1 != $alert->price_max) {
$showPrice = true;
}
if ($alert->cities) {
$showCities = true;
}
}
$groups = array_unique($groups);
sort($groups);
if (in_array("Sans groupe", $groups)) {
// met les alertes sans groupe à la fin.
unset($groups[array_search("Sans groupe", $groups)]);
$groups[] = "Sans groupe";
}
$notification["freeMobile"] = $userAuthed->hasSMSFreeMobile();
$notification["ovh"] = $userAuthed->hasSMSOvh();
$notification["pushbullet"] = $userAuthed->hasPushbullet();
$notification["notifymyandroid"] = $userAuthed->hasNotifyMyAndroid();
$notification["pushover"] = $userAuthed->hasPushover();

View File

@ -0,0 +1,8 @@
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// place le marqueur de réinitialisation
file_put_contents(DOCUMENT_ROOT."/var/tmp/reset_".$userAuthed->getId(), time());
header("LOCATION: ./?mod=mail"); exit;
}

View File

@ -0,0 +1,12 @@
<?php
if (isset($_GET["id"]) && $alert = $storage->fetchById($_GET["id"])) {
$status = isset($_GET["s"])?$_GET["s"]:"";
if (in_array($status, array("suspend", "send_mail", "send_sms_free_mobile",
"send_sms_ovh", "send_pushbullet", "send_notifymyandroid",
"send_pushover"))) {
$alert->$status = !$alert->$status;
$storage->save($alert);
}
}
header("LOCATION: ./?mod=mail"); exit;

View File

@ -0,0 +1,14 @@
<form action="" method="post">
<fieldset>
<legend>Supprimer cette alerte ?</legend>
<ul>
<li>Titre : <?php echo htmlspecialchars($alert->title); ?></li>
<li>Url : <?php echo htmlspecialchars($alert->url); ?></li>
</ul>
<p>
<input type="hidden" name="id" value="<?php echo $_GET["id"]; ?>" />
<input type="submit" value="Oui" style="font-weight: bold;" />
| <a href="?mod=mail">Non</a>
</p>
</fieldset>
</form>

View File

@ -0,0 +1,211 @@
<?php
$alertCategories = $alert->getCategories();
?>
<h2>Création d'une nouvelle alerte</h2>
<form action="" method="post">
<h2>Options obligatoires</h2>
<dl>
<dt>
<label for="url">URL de recherche</label>
</dt>
<dd>
<input type="text" id="url" name="url" value="<?php
echo htmlspecialchars($alert->url);
?>" size="75" placeholder="Ex: <?php
echo htmlspecialchars("https://www.leboncoin.fr/ventes_immobilieres/offres/champagne_ardenne/?f=a&th=1&pe=7&ret=1");
?>" />
<?php if (isset($errors["url"])) : ?>
<p class="error"><?php echo $errors["url"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="title">Indiquez un titre pour l'alerte</label>
</dt>
<dd>
<input type="text" id="title" name="title" value="<?php
echo htmlspecialchars($alert->title);
?>" size="50" placeholder="Ex: Achat de maison" />
<?php if (isset($errors["title"])) : ?>
<p class="error"><?php echo $errors["title"]; ?></p>
<?php endif; ?>
</dd>
<?php if ($userAuthed->hasSMSFreeMobile() || $userAuthed->hasSMSOvh() || $userAuthed->hasPushbullet()) : ?>
<dt>
<label>Comment souhaitez-vous recevoir les alertes</label>
</dt>
<dd class="notification-list">
<input type="hidden" name="send_mail" value="0" />
<input type="hidden" name="send_sms_free_mobile" value="0" />
<input type="hidden" name="send_sms_ovh" value="0" />
<input type="hidden" name="send_pushbullet" value="0" />
<input type="hidden" name="send_notifymyandroid" value="0" />
<input type="hidden" name="send_pushover" value="0" />
<label for="alert_mail">
<input id="alert_mail" type="checkbox" name="send_mail" value="1"<?php
echo $alert->send_mail?' checked="checked"':''
?> />
par email
</label>
<?php if ($userAuthed->hasSMSFreeMobile()) : ?>
<label for="alert_sms_free">
<input id="alert_sms_free" type="checkbox" name="send_sms_free_mobile" value="1"<?php
echo $alert->send_sms_free_mobile?' checked="checked"':''
?> />
par SMS Free Mobile
</label>
<?php endif; ?>
<?php if ($userAuthed->hasSMSOvh()) : ?>
<label for="alert_sms_ovh">
<input id="alert_sms_ovh" type="checkbox" name="send_sms_ovh" value="1"<?php
echo $alert->send_sms_ovh?' checked="checked"':''
?> />
par SMS OVH
</label>
<?php endif; ?>
<?php if ($userAuthed->hasPushbullet()) : ?>
<label for="alert_pushbullet">
<input id="alert_pushbullet" type="checkbox" name="send_pushbullet" value="1"<?php
echo $alert->send_pushbullet?' checked="checked"':''
?> />
par Pushbullet
</label>
<?php endif; ?>
<?php if ($userAuthed->hasNotifyMyAndroid()) : ?>
<label for="alert_notifymyandroid">
<input id="alert_notifymyandroid" type="checkbox" name="send_notifymyandroid" value="1"<?php
echo $alert->send_notifymyandroid?' checked="checked"':''
?> />
par NotityMyAndroid
</label>
<?php endif; ?>
<?php if ($userAuthed->hasPushover()) : ?>
<label for="alert_pushover">
<input id="alert_pushover" type="checkbox" name="send_pushover" value="1"<?php
echo $alert->send_pushover?' checked="checked"':''
?> />
par Pushover
</label>
<?php endif; ?>
<?php if (isset($errors["send_type"])) : ?>
<p class="error"><?php echo $errors["send_type"]; ?></p>
<?php endif; ?>
</dd>
<?php else: ?>
<dt><input type="hidden" name="send_mail" value="1" /></dt>
<?php endif; ?>
<dt>
<label for="email">Entrez une adresse email valide</label>
</dt>
<dd>
<input type="text" id="email" name="email" value="<?php
echo htmlspecialchars($alert->email);
?>" placeholder="Ex: toto@exemple.fr" />
<p class="form-more">Vous pouvez indiquer plusieurs adresses en les séparant par une virgule.</p>
<?php if (isset($errors["email"])) : ?>
<p class="error"><?php echo $errors["email"]; ?></p>
<?php endif; ?>
</dd>
</dl>
<?php $isOpen = !$alert->group_ads || $alert->interval != 30 || $alert->group; ?>
<h2 id="moreoptions" class="formbox">Plus d'options <span>(cliquez pour <?php echo $isOpen ? "fermer" : "ouvrir"; ?>)</span></h2>
<dl id="moreoptions-content" style="display: <?php echo $isOpen ? "block" : "none"; ?>;">
<dt style="margin-bottom: 10px;">
<input type="hidden" name="group_ads" value="0" />
<label for="group_ads">
<input type="checkbox" id="group_ads" name="group_ads" value="1"<?php
echo $alert->group_ads?' checked="checked"':''
?> style="margin-left: 0;" />
Cochez la case pour grouper les annonces dans un unique mail.
</label>
</dt>
<dt>
<label for="interval">Nombre de minutes avant la prochaine
vérification de nouvelles annonces</label>
</dt>
<dd>
<input type="text" id="interval" name="interval" value="<?php
echo $alert->interval;
?>" size="10" />
<?php if (isset($errors["interval"])) : ?>
<p class="error"><?php echo $errors["interval"]; ?></p>
<?php endif; ?>
</dd>
<dt><label for="group">Nom du groupe</label></dt>
<dd>
<input type="text" id="group" name="group" value="<?php echo htmlspecialchars($alert->group); ?>" />
<p class="form-more">Les alertes seront affichées par groupe sur la page de vos alertes.</p>
</dd>
</dl>
<?php $isOpen = $alert->price_min != -1 || $alert->price_max != -1
|| $alert->price_strict || !empty($alert->cities) || $alertCategories; ?>
<h2 id="morefilters" class="formbox">Filtres supplémentaires <span>(cliquez pour <?php echo $isOpen ? "fermer" : "ouvrir"; ?>)</span></h2>
<dl id="morefilters-content" style="display: <?php echo $isOpen ? "block" : "none"; ?>;">
<dt>
<label>Filtre sur le prix</label>
<dt>
<dd>
<label for="price_min">
Prix min :
<input type="text" id="price_min" name="price_min" value="<?php
echo $alert->price_min != -1?(int)$alert->price_min:"";
?>" size="6" />
</label>
<label for="price_max">
Prix max :
<input type="text" id="price_max" name="price_max" value="<?php
echo $alert->price_max != -1?(int)$alert->price_max:"";
?>" size="6" />
</label>
<?php if (isset($errors["price"])) : ?>
<p class="error"><?php echo $errors["price"]; ?></p>
<?php endif; ?>
</dd>
<dt style="margin-bottom: 10px;">
<input type="hidden" name="price_strict" value="0" />
<label for="price_strict">
<input type="checkbox" id="price_strict" name="price_strict" value="1"<?php
echo $alert->price_strict?' checked="checked"':''
?> style="margin-left: 0;" />
cochez cette case pour exclure les annonces sans prix d'indiqué de votre recherche.
</label>
</dt>
<dt><label for="cities">Filtre sur les villes ou départements (un par ligne)</label></dt>
<dd>
<textarea id="cities" name="cities" cols="30" rows="10"><?php
echo htmlspecialchars($alert->cities) ?></textarea>
</dd>
<dt><label>Filtre multi-catégorie</label></dt>
<dd class="categories">
<p class="warning"><span>Attention : </span>
ce filtre ne doit être utilisé que pour les recherches sur "toutes les catégories".</p>
<?php $i = 1; ?>
<?php foreach ($categoryCollection->fetchAll() AS $group => $categories) : ?>
<div class="categories-list categories-list-<?php echo $i++; ?>">
<h3><?php echo htmlspecialchars($group); ?></h3>
<?php foreach ($categories AS $id => $category) : ?>
<label for="category-<?php echo $id; ?>"><input id="category-<?php
echo $id; ?>" type="checkbox" name="categories[]" value="<?php
echo htmlspecialchars($category); ?>"<?php
echo in_array($category, $alertCategories)?' checked="checked"':'';
?> /><?php
echo htmlspecialchars($category); ?></label>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</dd>
</dl>
<p><input type="submit" value="Enregistrer" />
| <a href="?mod=mail">annuler</a></p>
</form>

View File

@ -0,0 +1,153 @@
<p>
<?php if (0 < $nbAlertes = count($alerts)) : ?>
<strong><?php echo $nbAlertes ?> <?php
echo $nbAlertes > 1?"alertes enregistrées":"alerte enregistrée"; ?></strong> |
<?php endif; ?>
<a href="?mod=mail&amp;a=form" class="link-create-alert">Ajouter une alerte</a> |
<a href="?mod=mail&amp;a=reset">Tout renvoyer</a>
</p>
<?php if ($groups) : ?>
<?php foreach ($groups AS $group) : ?>
<?php if (count($groups) > 1 || $group != "Sans groupe") : ?>
<h2><?php echo $group != "Sans groupe"?"Groupe : ":""; ?><?php echo htmlspecialchars($group); ?></h2>
<?php endif; ?>
<?php $alerts = $alertsByGroup[$group]; ?>
<table style="width: 100%;">
<thead>
<tr>
<th style="width: 20px"></th>
<th style="width: 250px"><?php if ($sort == "email") :
?><img src="static/images/sort-<?php echo $order; ?>.png" alt="" />&nbsp;<?php
endif; ?><a href="?mod=mail&amp;sort=email">Envoyer à</a></th>
<th><?php if ($sort == "title") :
?><img src="static/images/sort-<?php echo $order; ?>.png" alt="" />&nbsp;<?php
endif; ?><a href="?mod=mail&amp;sort=title">Titre</a></th>
<th style="width: 100px">Intervalle</th>
<?php if ($showPrice) : ?>
<th style="width: 100px">Prix</th>
<?php endif; ?>
<?php if ($showCities) : ?>
<th style="width: 200px">Villes</th>
<?php endif; ?>
<?php if ($notification["freeMobile"]
|| $notification["ovh"]
|| $notification["pushbullet"]
|| $notification["notifymyandroid"]
|| $notification["pushover"]
) : ?>
<th style="width: 140px">Envoyer par email</th>
<?php if ($notification["freeMobile"]) : ?>
<th style="width: 140px">SMS Free Mobile</th>
<?php endif; ?>
<?php if ($notification["ovh"]) : ?>
<th style="width: 140px">SMS OVH</th>
<?php endif; ?>
<?php if ($notification["pushbullet"]) : ?>
<th style="width: 140px">Pushbullet</th>
<?php endif; ?>
<?php if ($notification["notifymyandroid"]) : ?>
<th style="width: 140px">NotityMyAndroid</th>
<?php endif; ?>
<?php if ($notification["pushover"]) : ?>
<th style="width: 140px">Pushover</th>
<?php endif; ?>
<?php endif; ?>
<th style="width: 70px">Actif</th>
<th style="width: 170px">&nbsp;</th>
</tr>
</thead>
<tbody>
<?php $i = 1; foreach ($alerts AS $alert) : ?>
<tr>
<td><?php echo $i++; ?></td>
<td><?php echo str_replace(",", "<br />", htmlspecialchars($alert->email)); ?></td>
<td class="title"><a href="<?php echo htmlspecialchars($alert->url); ?>" target="_blank"><?php
echo $alert->title?htmlspecialchars($alert->title):"-"; ?></a></td>
<td class="intervalle"><?php echo (int)$alert->interval; ?> mins</td>
<?php if ($showPrice) : ?>
<td>
<?php if ($alert->price_min != -1 && $alert->price_max != -1) : ?>
entre <?php echo $alert->price_min; ?>€ et <?php echo $alert->price_max; ?>
<?php elseif ($alert->price_min != -1) : ?>
à partir de <?php echo $alert->price_min; ?>
<?php elseif ($alert->price_max != -1) : ?>
jusque <?php echo $alert->price_max; ?>
<?php else: ?>
-
<?php endif; ?>
</td>
<?php endif; ?>
<?php if ($showCities) : ?>
<td>
<?php if ($alert->cities) : ?>
<ul style="margin: 0; padding: 0 0 0 15px;"><li>
<?php echo str_replace("\n", "</li><li>", htmlspecialchars($alert->cities)); ?>
</li></ul>
<?php else: ?>
-
<?php endif; ?>
</td>
<?php endif; ?>
<?php if ($notification["freeMobile"]
|| $notification["ovh"]
|| $notification["pushbullet"]
|| $notification["notifymyandroid"]
|| $notification["pushover"]
) : ?>
<td>
<a href="?mod=mail&amp;a=toggle_status&amp;s=send_mail&amp;id=<?php echo $alert->id;
?>"><img src="static/images/<?php
echo !$alert->send_mail?"disable":"enable"; ?>.png" alt="" /></a>
</td>
<?php endif; ?>
<?php if ($notification["freeMobile"]) : ?>
<td>
<a href="?mod=mail&amp;a=toggle_status&amp;s=send_sms_free_mobile&amp;id=<?php echo $alert->id;
?>"><img src="static/images/<?php
echo !$alert->send_sms_free_mobile?"disable":"enable"; ?>.png" alt="" /></a>
</td>
<?php endif; ?>
<?php if ($notification["ovh"]) : ?>
<td>
<a href="?mod=mail&amp;a=toggle_status&amp;s=send_sms_ovh&amp;id=<?php echo $alert->id;
?>"><img src="static/images/<?php
echo !$alert->send_sms_ovh?"disable":"enable"; ?>.png" alt="" /></a>
</td>
<?php endif; ?>
<?php if ($notification["pushbullet"]) : ?>
<td>
<a href="?mod=mail&amp;a=toggle_status&amp;s=send_pushbullet&amp;id=<?php echo $alert->id;
?>"><img src="static/images/<?php
echo !$alert->send_pushbullet?"disable":"enable"; ?>.png" alt="" /></a>
</td>
<?php endif; ?>
<?php if ($notification["notifymyandroid"]) : ?>
<td>
<a href="?mod=mail&amp;a=toggle_status&amp;s=send_notifymyandroid&amp;id=<?php echo $alert->id;
?>"><img src="static/images/<?php
echo !$alert->send_notifymyandroid?"disable":"enable"; ?>.png" alt="" /></a>
</td>
<?php endif; ?>
<?php if ($notification["pushover"]) : ?>
<td>
<a href="?mod=mail&amp;a=toggle_status&amp;s=send_pushover&amp;id=<?php echo $alert->id;
?>"><img src="static/images/<?php
echo !$alert->send_pushover?"disable":"enable"; ?>.png" alt="" /></a>
</td>
<?php endif; ?>
<td>
<a href="?mod=mail&amp;a=toggle_status&amp;s=suspend&amp;id=<?php echo $alert->id;
?>"><img src="static/images/<?php
echo $alert->suspend?"disable":"enable"; ?>.png" alt="" /></a>
</td>
<td>
<a href="?mod=mail&amp;a=form&amp;id=<?php echo $alert->id; ?>">modifier</a> |
<a href="?mod=mail&amp;a=form-delete&amp;id=<?php echo $alert->id; ?>">supprimer</a>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endforeach; ?>
<?php endif; ?>

View File

@ -0,0 +1,46 @@
<?php ob_start(); ?>
<div>
<?php if ($ad->getDate()) : ?>
<strong>Publié le <?php echo date("d/m/Y à H:i", $ad->getDate()); ?></strong>
<br />
<?php endif; ?>
<strong>Nom</strong> :
<a href="<?php echo $ad->getLink(); ?>"><?php echo $ad->getTitle(); ?></a>
<?php if ($link_mobile = $ad->getLinkMobile()) : ?>
(<a href="<?php echo $link_mobile; ?>">Version Mobile</a>)
<?php endif; ?>
<?php if ($ad->getPrice()) : ?>
&nbsp;&nbsp;&nbsp;&nbsp;<strong>Prix</strong> : <?php echo number_format($ad->getPrice(), 0, ',', ' '); ?> <?php echo $ad->getCurrency(); ?>
<?php endif; ?>
<?php if ($ad->getCategory()) : ?>
<br />
<strong>Catégorie</strong> : <?php echo $ad->getCategory(); ?>
<?php endif; ?>
<br />
<?php if ($ad->getCountry()) : ?>
<strong>Département</strong> : <?php echo $ad->getCountry(); ?>
&nbsp;&nbsp;&nbsp;&nbsp;
<?php endif; ?>
<?php if ($ad->getCity()) : ?>
<strong>Ville</strong> : <a href="https://maps.google.fr/?z=9&q=<?php
echo htmlspecialchars($ad->getCountry().' '.$ad->getCity());
?>" title="Localiser sur Google Map"><?php echo $ad->getCity(); ?></a>
<?php endif; ?>
<?php if ($siteConfig->getOption("pro_visible")) : ?>
<br />Annonce de <?php echo $ad->getProfessional()?'professionnel':'particulier.'; ?>
<?php endif; ?>
<br />
<?php if ($ad->getUrgent()) : ?>
<strong style="color: #FF8900;">urgent</strong>
<?php endif; ?>
<?php if ($ad->getThumbnailLink()) : ?>
<br /><img src="<?php echo str_replace('/thumbs/', '/images/', $ad->getThumbnailLink()); ?>" alt=""
style="max-width: 100%; overflow:hidden;" />
<?php else : ?>
<br />Pas de photo disponible.
<?php endif; ?>
</div>
<?php
return ob_get_clean();

View File

@ -0,0 +1,13 @@
<form action="" method="post">
<fieldset>
<legend>Renvoyer toutes les alertes ?</legend>
<p>
En confirmant, vous recevrez toutes les annonces pour chaque alerte
lors du prochain contrôle de nouvelle annonce.
</p>
<p>
<input type="submit" value="Confirmer" style="font-weight: bold;" />
| <a href="?mod=mail">Annuler</a>
</p>
</fieldset>
</form>

View File

@ -0,0 +1,88 @@
<?php
namespace App\Mail;
class Alert
{
public $email;
public $id;
public $title;
public $url;
public $interval = 30;
public $time_last_ad = 0;
public $time_updated = 0;
public $price_min = -1;
public $price_max = -1;
public $price_strict = false;
public $cities;
public $categories;
public $suspend = 0;
public $group = "";
public $group_ads = 1;
public $send_mail = 1;
public $send_sms_free_mobile = 0;
public $last_id = array();
public $max_id = 0;
public $send_sms_ovh = 0;
public $send_pushbullet = 0;
public $send_notifymyandroid = 0;
public $send_pushover = 0;
public function fromArray(array $values)
{
foreach ($values AS $key => $value) {
$this->$key = $value;
}
if (!is_numeric($this->group_ads)) {
$this->group_ads = 1;
}
/**
* Depuis 3.1, last_id contient les derniers IDs de la liste d'annonce
* et max_id l'ID max trouvé.
*/
if ($this->last_id && is_numeric($this->last_id) && !$this->max_id) {
$this->max_id = $this->last_id;
}
}
public function getCategories()
{
if ($this->categories && is_string($this->categories)) {
return explode(",", $this->categories);
}
if (is_array($this->categories)) {
return $this->categories;
}
return array();
}
public function toArray()
{
return array(
"email" => $this->email,
"id" => $this->id,
"title" => $this->title,
"url" => $this->url,
"interval" => $this->interval,
"time_last_ad" => $this->time_last_ad,
"time_updated" => $this->time_updated,
"price_min" => $this->price_min,
"price_max" => $this->price_max,
"price_strict" => $this->price_strict,
"cities" => $this->cities,
"suspend" => $this->suspend,
"group" => $this->group,
"group_ads" => $this->group_ads,
"categories" => $this->categories,
"send_mail" => $this->send_mail,
"send_sms_free_mobile" => $this->send_sms_free_mobile,
"last_id" => $this->last_id,
"max_id" => (int) $this->max_id,
"send_sms_ovh" => $this->send_sms_ovh,
"send_pushbullet" => $this->send_pushbullet,
"send_notifymyandroid" => $this->send_notifymyandroid,
"send_pushover" => $this->send_pushover
);
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Storage;
interface Alert
{
public function fetchAll();
public function fetchById($id);
public function save(\App\Mail\Alert $alert);
public function delete(\App\Mail\Alert $alert);
}

View File

@ -0,0 +1,141 @@
<?php
namespace App\Storage\Db;
class Alert implements \App\Storage\Alert
{
/**
* @var \mysqli
*/
protected $_connection;
protected $_table = "LBC_Alert";
/**
* @var \App\User\User
*/
protected $_user;
public function __construct(\mysqli $connection, \App\User\User $user)
{
$this->_connection = $connection;
$this->_user = $user;
}
public function fetchAll()
{
$alerts = array();
$alertsDb = $this->_connection->query("SELECT * FROM ".$this->_table
." WHERE user_id = ".$this->_user->getId());
while ($alertDb = $alertsDb->fetch_assoc()) {
$alert = new \App\Mail\Alert();
if (isset($alertDb["last_id"]) && !is_numeric($alertDb["last_id"])) {
$alertDb["last_id"] = json_decode($alertDb["last_id"], true);
if (!is_array($alertDb["last_id"])) {
$alertDb["last_id"] = array();
}
}
$alert->fromArray($alertDb);
$alert->id = $alertDb["idstr"];
$alerts[] = $alert;
}
return $alerts;
}
public function fetchById($id)
{
$alert = null;
$alertDb = $this->_connection->query(
"SELECT * FROM ".$this->_table." WHERE user_id = ".$this->_user->getId()."
AND idstr = '".$this->_connection->real_escape_string($id)."'")
->fetch_assoc();
if ($alertDb) {
$alert = new \App\Mail\Alert();
if (isset($alertDb["last_id"]) && !is_numeric($alertDb["last_id"])) {
$alertDb["last_id"] = json_decode($alertDb["last_id"], true);
if (!is_array($alertDb["last_id"])) {
$alertDb["last_id"] = array();
}
}
$alert->fromArray($alertDb);
$alert->id = $alertDb["idstr"];
}
return $alert;
}
public function save(\App\Mail\Alert $alert, $forceInsert = false)
{
$options = $alert->toArray();
if (is_array($options["last_id"])) {
$options["last_id"] = json_encode($options["last_id"]);
}
if (!$alert->id || $forceInsert) {
$options["user_id"] = $this->_user->getId();
if (!$alert->id) {
$id = sha1(uniqid());
$alert->id = $id;
}
$options["idstr"] = $alert->id;
unset($options["id"]);
$sqlOptions = array();
foreach ($options AS $name => $value) {
if ($value === null) {
$value = "NULL";
} elseif (is_bool($value)) {
$value = (int) $value;
} elseif (!is_numeric($value)) {
$value = "'".$this->_connection->real_escape_string($value)."'";
}
$sqlOptions[$name] = $value;
}
$this->_connection->query("INSERT INTO ".$this->_table.
" (`".implode("`, `", array_keys($options)).
"`, `date_created`) VALUES (".implode(", ", $sqlOptions).", NOW())");
} else {
$idStr = $options["id"];
$sqlOptions = array();
unset($options["id"]);
foreach ($options AS $name => $value) {
if ($value === null) {
$value = "NULL";
} elseif (is_bool($value)) {
$value = (int) $value;
} elseif (!is_numeric($value)) {
$value = "'".$this->_connection->real_escape_string($value)."'";
}
$sqlOptions[] = "`".$name."` = ".$value;
}
$this->_connection->query("UPDATE ".$this->_table." SET
".implode(",", $sqlOptions).
" WHERE idstr = '".$this->_connection->real_escape_string($idStr)."'");
}
return $this;
}
public function delete(\App\Mail\Alert $alert)
{
$this->_connection->query("DELETE FROM ".$this->_table."
WHERE idstr = '".$this->_connection->real_escape_string($alert->id)."'");
return $this;
}
/**
* @param \mysqli $dbConnection
* @return \App\Storage\Db\User
*/
public function setDbConnection($dbConnection)
{
$this->_connection = $dbConnection;
return $this;
}
/**
* @return \mysqli
*/
public function getDbConnection()
{
return $this->_connection;
}
}

View File

@ -0,0 +1,102 @@
<?php
namespace App\Storage\Db;
class User implements \App\Storage\User
{
/**
* @var \mysqli
*/
protected $_connection;
protected $_table = "LBC_User";
public function __construct(\mysqli $connection)
{
$this->_connection = $connection;
}
public function fetchAll()
{
$users = array();
$usersDb = $this->_connection->query("SELECT * FROM ".$this->_table);
while ($userDb = $usersDb->fetch_object()) {
$user = new \App\User\User();
$user->setId($userDb->id)
->setPassword($userDb->password)
->setUsername($userDb->username);
if (!empty($userDb->options)) {
$options = json_decode($userDb->options, true);
if (is_array($options)) {
$user->setOptions($options);
}
}
$users[] = $user;
}
return $users;
}
public function fetchByUsername($username)
{
$user = null;
$userDb = $this->_connection->query(
"SELECT * FROM ".$this->_table." WHERE username = '".
$this->_connection->real_escape_string($username)."'")
->fetch_object();
if ($userDb) {
$user = new \App\User\User();
$user->setId($userDb->id)
->setPassword($userDb->password)
->setUsername($userDb->username);
if (!empty($userDb->options)) {
$options = json_decode($userDb->options, true);
if (is_array($options)) {
$user->setOptions($options);
}
}
}
return $user;
}
public function save(\App\User\User $user)
{
if (!$this->fetchByUsername($user->getUsername())) {
$this->_connection->query("INSERT INTO `".$this->_table.
"` (`username`, `password`, `options`) VALUES (
'".$this->_connection->real_escape_string($user->getUsername())."',
'".$this->_connection->real_escape_string($user->getPassword())."',
'".$this->_connection->real_escape_string(json_encode($user->getOptions()))."'
)");
} else {
$this->_connection->query("UPDATE `".$this->_table."` SET
`password` = '".$this->_connection->real_escape_string($user->getPassword())."',
`options` = '".$this->_connection->real_escape_string(json_encode($user->getOptions()))."'
WHERE id = ".$user->getId());
}
return $this;
}
public function delete(\App\User\User $user)
{
$this->_connection->query("DELETE FROM ".$this->_table." WHERE id = ".$user->getId());
return $this;
}
/**
* @param \mysqli $dbConnection
* @return \App\Storage\Db\User
*/
public function setDbConnection($dbConnection)
{
$this->_connection = $dbConnection;
return $this;
}
/**
* @return \mysqli
*/
public function getDbConnection()
{
return $this->_connection;
}
}

View File

@ -0,0 +1,167 @@
<?php
namespace App\Storage\File;
class Alert implements \App\Storage\Alert
{
protected $_filename;
protected $_header = array(
"email",
"id",
"title",
"url",
"interval",
"time_last_ad",
"time_updated",
"price_min",
"price_max",
"price_strict",
"cities",
"suspend",
"group",
"group_ads",
"categories",
"send_mail",
"send_sms_free_mobile",
"last_id",
"max_id",
"send_sms_ovh",
"send_pushbullet",
"send_notifymyandroid",
"send_pushover"
);
public function __construct($filename)
{
$this->_filename = $filename;
$this->_checkFile();
}
public function fetchAll()
{
$alerts = array();
if (is_file($this->_filename)) {
$fopen = fopen($this->_filename, "r");
if ($header = fgetcsv($fopen, 0, ",", '"')) {
$nb_columns = count($header);
while (false !== $values = fgetcsv($fopen, 0, ",", '"')) {
$alert = new \App\Mail\Alert();
$options = array_combine(
$header,
array_slice($values, 0, count($header))
);
if (isset($options["last_id"]) && !is_numeric($options["last_id"])) {
$options["last_id"] = json_decode($options["last_id"], true);
if (!is_array($options["last_id"])) {
$options["last_id"] = array();
}
}
$alert->fromArray($options);
$alerts[$alert->id] = $alert;
}
}
fclose($fopen);
}
return $alerts;
}
public function fetchById($id)
{
$alert = null;
if (is_file($this->_filename)) {
$fopen = fopen($this->_filename, "r");
if ($header = fgetcsv($fopen, 0, ",", '"')) {
while (false !== $values = fgetcsv($fopen, 0, ",", '"')) {
$options = array_combine(
$header,
array_slice($values, 0, count($header))
);
if ($options["id"] == $id) {
if (isset($options["last_id"]) && !is_numeric($options["last_id"])) {
$options["last_id"] = json_decode($options["last_id"], true);
if (!is_array($options["last_id"])) {
$options["last_id"] = array();
}
}
$alert = new \App\Mail\Alert();
$alert->fromArray($options);
break;
}
}
}
fclose($fopen);
}
return $alert;
}
public function save(\App\Mail\Alert $alert)
{
$alerts = $this->fetchAll();
$fopen = fopen($this->_filename, "a");
flock($fopen, LOCK_EX);
$fpNewFile = fopen($this->_filename.".new", "w");
flock($fpNewFile, LOCK_EX);
fputcsv($fpNewFile, $this->_header, ",", '"');
$updated = false;
foreach ($alerts AS $a) {
if ($a->id == $alert->id) {
$a = $alert;
$updated = true;
}
$data = $a->toArray();
if (is_array($data["last_id"])) {
$data["last_id"] = json_encode($data["last_id"]);
}
fputcsv($fpNewFile, $data, ",", '"');
}
if (!$updated && !$alert->id) {
$alert->id = sha1(uniqid());
fputcsv($fpNewFile, $alert->toArray(), ",", '"');
}
fclose($fpNewFile);
fclose($fopen);
file_put_contents($this->_filename, file_get_contents($this->_filename.".new"));
unlink($this->_filename.".new");
return $this;
}
public function delete(\App\Mail\Alert $alert)
{
$alerts = $this->fetchAll();
$fopen = fopen($this->_filename, "a");
flock($fopen, LOCK_EX);
$fpNewFile = fopen($this->_filename.".new", "w");
flock($fpNewFile, LOCK_EX);
fputcsv($fpNewFile, $this->_header, ",", '"');
unset($alerts[$alert->id]);
foreach ($alerts AS $a) {
fputcsv($fpNewFile, $a->toArray(), ",", '"');
}
fclose($fpNewFile);
fclose($fopen);
file_put_contents($this->_filename, file_get_contents($this->_filename.".new"));
unlink($this->_filename.".new");
return $this;
}
protected function _checkFile()
{
if (empty($this->_filename)) {
throw new \Exception("Un fichier doit être spécifié.");
}
$dir = dirname($this->_filename);
if (!is_file($this->_filename)) {
if (!is_writable($dir)) {
throw new \Exception("Pas d'accès en écriture sur le répertoire '".$dir."'.");
}
} elseif (!is_writable($this->_filename)) {
throw new \Exception("Pas d'accès en écriture sur le fichier '".$this->_filename."'.");
}
}
}

View File

@ -0,0 +1,145 @@
<?php
namespace App\Storage\File;
class User implements \App\Storage\User
{
public function __construct($filename)
{
$this->_filename = $filename;
$this->_checkFile();
}
public function fetchAll()
{
$users = array();
if (is_file($this->_filename)) {
$fopen = fopen($this->_filename, "r");
while (false !== $value = fgets($fopen)) {
$value = trim($value);
$user = new \App\User\User();
$user->setPassword(substr($value, 0, 40))
->setUsername(substr($value, 40));
$this->_loadUserOptions($user);
$users[] = $user;
}
fclose($fopen);
}
return $users;
}
public function fetchByUsername($username)
{
$user = null;
if (is_file($this->_filename)) {
$fopen = fopen($this->_filename, "r");
while (false !== $value = fgets($fopen)) {
$value = trim($value);
if (substr($value, 40) == $username) {
$user = new \App\User\User();
$user->setPassword(substr($value, 0, 40))
->setUsername($username);
$this->_loadUserOptions($user);
break;
}
}
fclose($fopen);
}
return $user;
}
public function save(\App\User\User $user)
{
if (!$this->fetchByUsername($user->getUsername()) || !is_file($this->_filename)) {
$fopen = fopen($this->_filename, "a");
fputs($fopen, $user->getPassword().$user->getUsername()."\n");
fclose($fopen);
} else {
$fopen = fopen($this->_filename, "r");
$fpNewFile = fopen($this->_filename.".new", "w");
flock($fopen, LOCK_EX);
while (false !== $value = fgets($fopen)) {
$value = trim($value);
if (substr($value, 40) == $user->getUsername()) {
$value = $user->getPassword().$user->getUsername();
}
fputs($fpNewFile, $value."\n");
}
fclose($fopen);
fclose($fpNewFile);
file_put_contents($this->_filename, file_get_contents($this->_filename.".new"));
unlink($this->_filename.".new");
$this->_saveUserOptions($user);
}
return $this;
}
public function delete(\App\User\User $user)
{
if (is_file($this->_filename)) {
$fopen = fopen($this->_filename, "r");
$fpNewFile = fopen($this->_filename.".new", "w");
while (false !== $value = fgets($fopen)) {
$value = trim($value);
if (substr($value, 40) != $user->getUsername()) {
fputs($fpNewFile, $value."\n");
}
}
fclose($fopen);
fclose($fpNewFile);
file_put_contents($this->_filename, file_get_contents($this->_filename.".new"));
unlink($this->_filename.".new");
$this->_deleteUserOptions($user);
}
return $this;
}
protected function _checkFile()
{
if (empty($this->_filename)) {
throw new \Exception("Un fichier doit être spécifié.");
}
$dir = dirname($this->_filename);
if (!is_file($this->_filename)) {
if (!is_writable($dir)) {
throw new \Exception("Pas d'accès en écriture sur le répertoire '".$dir."'.");
}
} elseif (!is_writable($this->_filename)) {
throw new \Exception("Pas d'accès en écriture sur le fichier '".$this->_filename."'.");
}
}
protected function _loadUserOptions(\App\User\User $user)
{
$dir = DOCUMENT_ROOT.DS."var".DS."configs";
$filename = $dir.DS."user_".$user->getUsername().".json";
if (is_file($filename)) {
$data = json_decode(trim(file_get_contents($filename)), true);
if ($data && is_array($data)) {
$user->setOptions($data);
}
}
return $this;
}
protected function _saveUserOptions(\App\User\User $user)
{
$dir = DOCUMENT_ROOT.DS."var".DS."configs";
if (!is_dir($dir)) {
mkdir($dir);
}
$filename = $dir.DS."user_".$user->getUsername().".json";
file_put_contents($filename, json_encode($user->getOptions()));
return $this;
}
protected function _deleteUserOptions(\App\User\User $user)
{
$dir = DOCUMENT_ROOT.DS."var".DS."configs";
$filename = $dir.DS."user_".$user->getUsername().".json";
if (is_file($filename)) {
unlink($filename);
}
return $this;
}
}

View File

@ -0,0 +1,14 @@
<?php
namespace App\Storage;
interface User
{
public function fetchAll();
public function fetchByUsername($username);
public function save(\App\User\User $user);
public function delete(\App\User\User $user);
}

View File

@ -0,0 +1,186 @@
<?php
namespace App;
class Updater
{
protected $_tmp_dir;
protected $_destination;
/**
* Adresse pour la récupération de la dernière version
* @var string
*/
protected $_url_version = "https://raw.githubusercontent.com/Blount/LBCAlerte/master/version.php";
/**
* Adresse pour récupérer l'archive ZIP.
* %VERSION% est remplacer parle numéro de version à télécharger.
* @var string
*/
protected $_url_archive = "https://github.com/Blount/LBCAlerte/archive/%VERSION%.zip";
public function __construct()
{
$this->_tmp_dir = DOCUMENT_ROOT."/var/tmp";
$this->_destination = DOCUMENT_ROOT;
}
/**
* @param string $tmp_dir
* @return Updater
*/
public function setTmpDir($tmp_dir)
{
$this->_tmp_dir = $tmp_dir;
return $this;
}
/**
* @return string
*/
public function getTmpDir()
{
return $this->_tmp_dir;
}
/**
* @param string $destination
* @return Updater
*/
public function setDestination($destination)
{
$this->_destination = $destination;
return $this;
}
/**
* @return string
*/
public function getDestination()
{
return $this->_destination;
}
/**
* @param string $url_version
* @return Updater
*/
public function setUrlVersion($url_version)
{
$this->_url_version = $url_version;
return $this;
}
/**
* @return string
*/
public function getUrlVersion()
{
return $this->_url_version;
}
/**
* @param string $url_archive
* @return Updater
*/
public function setUrlArchive($url_archive)
{
$this->_url_archive = $url_archive;
return $this;
}
/**
* @return string
*/
public function getUrlArchive()
{
return $this->_url_archive;
}
public function getLastVersion()
{
$lastVersion = file_get_contents($this->getUrlVersion());
if (preg_match('#return\s+"(.*)"\s*;#imsU', $lastVersion, $m)) {
return $m[1];
}
throw new \Exception("Impossible de récupérer la dernière version.");
}
public function installFiles($version)
{
$tmpZip = $this->_tmp_dir."/latest.zip";
if (!is_dir($this->_tmp_dir)) {
mkdir($this->_tmp_dir);
}
if (!is_writable($this->_tmp_dir)) {
throw new \Exception("Impossible d'écrire dans '".$this->_tmp_dir."'");
}
$archive = str_replace("%VERSION%", $version, $this->_url_archive);
if (!is_file($tmpZip) && !copy($archive, $tmpZip)) {
throw new \Exception("Impossible de récupérer l'archive.");
}
$zip = new \ZipArchive();
if (!$zip->open($tmpZip)) {
throw new \Exception("L'archive semble erronée.");
}
// extraire l'archive
$zip->extractTo($this->_tmp_dir);
$zip->close();
// mise à jour des fichiers.
$this->_copyFiles($this->_tmp_dir."/LBCAlerte-".$version, $this->_destination);
rmdir($this->_tmp_dir."/LBCAlerte-".$version);
unlink($tmpZip);
}
public function update($fromVersion, $toVersion)
{
// exécute les mises à jour
$directory = $this->_destination."/others/update";
if (is_dir($directory)) {
$filenames = scandir($directory);
$filenames_php = array();
foreach ($filenames AS $filename) {
if ($filename != "update.php" && false !== strpos($filename, ".php")) {
$filenames_php[basename($filename, ".php")] = $filename;
}
}
$versions = array_keys($filenames_php);
usort($versions, function ($a1, $a2) {
return version_compare($a1, $a2, "<") ? -1 : 1;
});
foreach ($versions AS $version) {
if (version_compare($fromVersion, $version, "<")
&& version_compare($toVersion, $version, ">=")) {
require $directory."/".$filenames_php[$version];
$class = "Update_".str_replace(".", "", $version);
if (class_exists($class, false)) {
$class = new $class();
$class->update();
}
}
}
}
}
protected function _copyFiles($dir, $to)
{
foreach (scandir($dir) AS $file) {
if ($file == "." || $file == "..") {
continue;
}
$destFile = $to."/".$file;
if (is_file($dir."/".$file)) {
rename($dir."/".$file, $destFile);
} elseif (is_dir($dir."/".$file)) {
if (!is_dir($destFile)) {
mkdir($destFile);
}
$this->_copyFiles($dir."/".$file, $destFile);
rmdir($dir."/".$file);
}
}
}
}

View File

@ -0,0 +1,190 @@
<?php
namespace App\User;
class User
{
protected $_id;
protected $_username;
protected $_password;
protected $_options = array();
protected $_optionsLoaded = false;
public function __construct(array $options = array())
{
if (isset($options["id"])) {
$this->setId($options["id"]);
}
if (isset($options["username"])) {
$this->setUsername($options["username"]);
}
if (isset($options["password"])) {
$this->setPassword($options["password"]);
}
}
/**
* @param int $id
* @return User
*/
public function setId($id)
{
$this->_id = $id;
return $this;
}
/**
* @return int
*/
public function getId()
{
if (!$this->_id) {
return md5($this->_username);
}
return $this->_id;
}
/**
* @param string $username
* @return User
*/
public function setUsername($username)
{
$this->_username = $username;
return $this;
}
/**
* @return string
*/
public function getUsername()
{
return $this->_username;
}
/**
* @param string $password
* @return User
*/
public function setPassword($password)
{
$this->_password = $password;
return $this;
}
/**
* @return string
*/
public function getPassword()
{
return $this->_password;
}
/**
* Retourne vrai si la notification SMS Free Mobile est activée.
* @return boolean
*/
public function hasSMSFreeMobile()
{
return false != $this->getOption("notification.freeMobile");
}
/**
* Retourne vrai si la notification SMS OVH est activée.
* @return boolean
*/
public function hasSMSOvh()
{
return false != $this->getOption("notification.ovh");
}
/**
* Retourne vrai si la notification Pushbullet est activée.
* @return boolean
*/
public function hasPushbullet()
{
return false != $this->getOption("notification.pushbullet");
}
/**
* Retourne vrai si la notification NotifyMyAndroid est activée.
* @return boolean
*/
public function hasNotifyMyAndroid()
{
return false != $this->getOption("notification.notifymyandroid");
}
/**
* Retourne vrai si la notification Pushover est activée.
* @return boolean
*/
public function hasPushover()
{
return false != $this->getOption("notification.pushover");
}
/**
* Indique si l'utilisateur est administrateur.
* @return boolean
*/
public function isAdmin()
{
return $this->getUsername() == "admin";
}
public function getOption($name, $default = null)
{
if (strpos($name, ".")) {
$options = explode(".", $name);
$nbOptions = count($options);
$current = $this->_options;
for ($i = 0; $i < $nbOptions; $i++) {
if (is_array($current) && isset($current[$options[$i]])) {
$current = $current[$options[$i]];
} else {
break;
}
}
if ($i == $nbOptions) {
return $current;
}
return $default;
}
return isset($this->_options[$name])?$this->_options[$name]:$default;
}
public function setOption($name, $value)
{
if (strpos($name, ".")) {
$options = explode(".", $name);
$nbOptions = count($options);
$current = $value;
for ($i = $nbOptions - 1; $i >= 0; $i--) {
$current = array($options[$i] => $current);
}
$this->_options = array_replace_recursive($this->_options, $current);
} else {
$this->_options[$name] = $value;
}
return $this;
}
public function getOptions()
{
return $this->_options;
}
public function setOptions(array $options)
{
$this->_options = $options;
return $this;
}
public function mergeOptions(array $options)
{
$this->_options = array_replace_recursive($this->_options, $options);
return $this;
}
}

View File

@ -0,0 +1,45 @@
<?php
$values = array(
"url" => "", "price_min" => "", "price_max" => "", "price_strict" => false,
"cities" => "", "categories" => array()
);
$categoryCollection = new \Lbc\CategoryCollection();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
foreach ($_POST AS $name => $value) {
if (is_array($value)) {
$_POST[$name] = array_map("trim", $_POST[$name]);
} else {
$_POST[$name] = trim($_POST[$name]);
}
}
$values = array_merge($values, $_POST);
if (empty($values["url"])) {
$errors["url"] = "Ce champ est obligatoire.";
}
if ($values["price_min"] && $values["price_min"] != (int)$values["price_min"]) {
$errors["price"] = "Valeur de \"prix min\" non valide. ";
}
if ($values["price_max"] && $values["price_max"] != (int)$values["price_max"]) {
$errors["price"] .= "Valeur de \"prix max\" non valide.";
}
if (empty($errors)) {
$query = array("mod" => "rss", "a" => "refresh", "url" => $values["url"]);
if (!empty($values["price_min"])) {
$query["price_min"] = (int)$values["price_min"];
}
if (!empty($values["price_max"])) {
$query["price_max"] = (int)$values["price_max"];
}
if (!empty($values["cities"])) {
$query["cities"] = $values["cities"];
}
if (!empty($values["categories"]) && is_array($values["categories"])) {
$query["categories"] = $values["categories"];
}
$query["price_strict"] = isset($values["price_strict"])?
(int)(bool)$values["price_strict"]:0;
header("LOCATION: ./?".http_build_query($query));
}
}

View File

@ -0,0 +1,98 @@
<?php
if (!isset($_GET["url"])) {
return;
}
$disableLayout = true;
$logFile = DOCUMENT_ROOT."/var/logs/rss.log";
use \FeedWriter\RSS2;
try {
$parser = \AdService\ParserFactory::factory($_GET["url"]);
} catch (\AdService\Exception $e) {
echo "Cette adresse ne semble pas valide.";
exit;
}
if (false !== strpos($_GET["url"], "leboncoin.fr")) {
$_GET["url"] = rtrim(preg_replace("#(o|sp)=[0-9]*&?#", "", $_GET["url"]), "?&");
}
// nettoyage cache
$files = array_diff(scandir(DOCUMENT_ROOT."/var/feeds"), array(".", ".."));
foreach ($files AS $file) {
$file = DOCUMENT_ROOT."/var/feeds/".$file;
$mtime = filemtime($file);
if (($mtime + 20 * 60) < time()) {
unlink($file);
}
}
header("Content-Type: application/rss+xml", true);
$logger = Logger::getLogger("main");
$id = sha1($_SERVER["REQUEST_URI"]);
$cache_filename = DOCUMENT_ROOT."/var/feeds/".$id.".xml";
if (is_file($cache_filename)) {
readfile($cache_filename);
return;
}
$params = $_GET;
if (isset($params["cities"])) {
$params["cities"] = array_map("trim", explode("\n", mb_strtolower($params["cities"])));
}
$content = $client->request($_GET["url"]);
$filter = new \AdService\Filter($params);
$siteConfig = \AdService\SiteConfigFactory::factory($_GET["url"]);
$ads = $parser->process(
$content,
$filter,
parse_url($_GET["url"], PHP_URL_SCHEME)
);
$title = $siteConfig->getOption("site_name");
$urlParams = parse_url($_GET["url"]);
if (!empty($urlParams["query"])) {
parse_str($urlParams["query"], $aQuery);
if (!empty($aQuery["q"])) {
$title .= " - ".$aQuery["q"];
}
}
$feeds = new RSS2;
$feeds->setTitle($siteConfig->getOption("site_name"));
$feeds->setLink($siteConfig->getOption("site_url"));
$feeds->setSelfLink(
!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on"?"https":"http".
"://".$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"]
);
$feeds->setDescription("Flux RSS de la recherche : ".$_GET["url"]);
$feeds->setChannelElement("language", "fr-FR");
// The date when this feed was lastly updated. The publication date is also set.
$feeds->setDate(date(DATE_RSS, time()));
$feeds->setChannelElement("pubDate", date(\DATE_RSS, strtotime("2013-04-06")));
$feeds->addGenerator();
if (count($ads)) {
foreach ($ads AS $ad) {
$item = $feeds->createNewItem();
$item->setTitle($ad->getTitle());
$item->setLink($ad->getLink());
$item->setDescription(require DOCUMENT_ROOT."/app/rss/views/rss-ad.phtml");
if ($ad->getDate()) {
$item->setDate($ad->getDate());
}
$item->setId(md5($ad->getId()));
$feeds->addItem($item);
}
}
$content = $feeds->generateFeed();
file_put_contents($cache_filename, $content);
echo $content;

View File

@ -0,0 +1,70 @@
<form action="" method="post">
<h2>Génération d'un flux RSS</h2>
<dl>
<dt><label for="url">
Indiquer l'adresse de recherche</label></dt>
<dd><input type="text" id="url" name="url" value="<?php
echo $values["url"]; ?>" size="75" placeholder="Ex: <?php
echo htmlspecialchars("https://www.leboncoin.fr/ventes_immobilieres/offres/champagne_ardenne/?f=a&th=1&pe=7&ret=1");
?>" /></dd>
</dl>
<?php $isOpen = $values["price_min"] || $values["price_max"]
|| $values["price_strict"] || !empty($values["cities"]); ?>
<h2 id="morefilters" class="formbox">Filtres supplémentaires <span>(cliquez pour <?php
echo $isOpen ? "fermer" : "ouvrir"
?>)</span></h2>
<dl id="morefilters-content" style="display: <?php
echo $isOpen ? "block" : "none"
?>;">
<dt>
<label>Filtre sur le prix</label>
<dt>
<dd>
<label for="price_min">
Prix min :
<input type="text" id="price_min" name="price_min" value="<?php
echo $values["price_min"]; ?>" size="6" />
</label>
<label for="price_max">
Prix max :
<input type="text" id="price_max" name="price_max" value="<?php
echo $values["price_max"]; ?>" size="6" />
</label>
<?php if (isset($errors["price"])) : ?>
<p class="error"><?php echo $errors["price"]; ?></p>
<?php endif; ?>
</dd>
<dt style="margin-bottom: 10px;">
<input type="hidden" name="price_strict" value="0" />
<label for="price_strict">
<input type="checkbox" id="price_strict" name="price_strict" value="1"<?php
echo $values["price_strict"]?' checked="checked"':''
?> style="margin-left: 0;" />
cochez cette case pour exclure les annonces sans prix d'indiqué de votre recherche.
</label>
</dt>
<dt><label for="cities">Filtre sur les villes ou départements (un par ligne)</label></dt>
<dd>
<textarea id="cities" name="cities" cols="30" rows="10"><?php
echo htmlspecialchars($values["cities"]) ?></textarea>
</dd>
<dt><label>Filtre multi-catégorie</label></dt>
<dd class="categories">
<p class="warning"><span>Attention : </span>
ce filtre ne doit être utilisé que pour les recherches sur "toutes les catégories".</p>
<?php $i = 1; ?>
<?php foreach ($categoryCollection->fetchAll() AS $group => $categories) : ?>
<div class="categories-list categories-list-<?php echo $i++; ?>">
<h3><?php echo htmlspecialchars($group); ?></h3>
<?php foreach ($categories AS $id => $category) : ?>
<label for="category-<?php echo $id; ?>"><input id="category-<?php
echo $id; ?>" type="checkbox" name="categories[]" value="<?php
echo htmlspecialchars($category); ?>" /><?php
echo htmlspecialchars($category); ?></label>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
</dd>
</dl>
<p><input type="submit" value="Générer le flux" /></p>
</form>

View File

@ -0,0 +1,45 @@
<?php
ob_start();
?>
<?php if ($ad->getDate()) : ?>
Publié le <strong><?php echo date("d/m/Y H:i", $ad->getDate()); ?></strong>
<br />
<br />
<?php endif; ?>
<strong>Nom</strong> : <?php echo $ad->getTitle(); ?>
<?php if ($ad->getPrice()) : ?>
&nbsp;&nbsp;&nbsp;&nbsp;<strong>Prix</strong> : <?php echo number_format($ad->getPrice(), 0, ',', ' '); ?> <?php echo $ad->getCurrency(); ?>
<?php endif; ?>
<?php if ($ad->getCategory()) : ?>
<br />
<strong>Catégorie</strong> : <?php echo $ad->getCategory(); ?>
<?php endif; ?>
<br />
<?php if ($ad->getCountry()) : ?>
<strong>Département</strong> : <?php echo $ad->getCountry(); ?>
&nbsp;&nbsp;&nbsp;&nbsp;
<?php endif; ?>
<?php if ($ad->getCity()) : ?><strong>Ville</strong> : <a href="https://maps.google.fr/?z=9&q=<?php
echo htmlspecialchars($ad->getCountry().' '.$ad->getCity());
?>" title="Localiser sur Google Map" target="_blank"><?php echo $ad->getCity(); ?></a>
<?php endif; ?>
<?php if ($siteConfig->getOption("pro_visible")) : ?>
<br />Annonce de <?php echo $ad->getProfessional()?'professionnel':'particulier.'; ?>
<?php endif; ?>
<br />
<?php if ($ad->getUrgent()) : ?>
<strong style="color: #FF8900;">urgent</strong>
<?php endif; ?>
<?php if ($ad->getThumbnailLink()) : ?>
<br /><img src="<?php echo str_replace('/thumbs/', '/images/', $ad->getThumbnailLink()); ?>"
alt="" style="max-width: 600px; float: left; display: block;" />
<?php else : ?>
<br />Pas de photo disponible.
<?php endif; ?>
<?php
return ob_get_clean();

View File

@ -0,0 +1,123 @@
<?php
$params = array(
"notification" => $userAuthed->getOption("notification"),
"unique_ads" => $userAuthed->getOption("unique_ads", false)
);
if (!is_array($params["notification"])) {
$params["notification"] = array();
}
$form_values["notification"] = array_replace_recursive(array(
"freeMobile" => array(
"user" => "",
"key" => "",
),
"notifymyandroid" => array(
"token" => "",
),
"pushbullet" => array(
"token" => "",
),
"ovh" => array(
"account" => "",
"login" => "",
"password" => "",
"from" => "",
"to" => "",
),
"pushover" => array(
"token" => "",
"user_key" => "",
),
), $params["notification"]);
$errors = array();
$errorsTest = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$params = array_merge($params, $_POST);
// test config Free Mobile
foreach ($params["notification"] AS $section => $options) {
if (is_array($options)) {
$hasValue = false;
foreach ($options AS $name => $value) {
if (empty($value)) {
$errors["notification"][$section][$name] = "Ce champ doit être renseigné.";
} else {
$hasValue = true;
}
}
if (!$hasValue) {
unset($errors["notification"][$section]);
$params["notification"][$section] = false;
}
}
}
if (empty($errors["notification"])) {
unset($errors["notification"]);
}
if (empty($errors)) {
if (!empty($_POST["testFreeMobile"])) {
$sms = \Message\AdapterFactory::factory("freeMobile", $params["notification"]["freeMobile"]);
try {
$sms->send("La notification SMS est fonctionnelle.");
} catch (Exception $e) {
$errorsTest["freeMobile"] = "Erreur lors de l'envoi du SMS : (".$e->getCode().") ".$e->getMessage();
}
} elseif (!empty($_POST["testPushbullet"])) {
if (empty($_POST["notification"]["pushbullet"]["token"])) {
$errors["notification"]["pushbullet"]["token"] = "Veuillez renseigner la clé d'identification. ";
} else {
$sender = \Message\AdapterFactory::factory("pushbullet", $_POST["notification"]["pushbullet"]);
try {
$sender->send("La notification Pushbullet est fonctionnelle");
} catch (Exception $e) {
$errorsTest["pushbullet"] = "Erreur lors de l'envoi de la notification : (".$e->getCode().") ".$e->getMessage();
}
}
} elseif (!empty($_POST["testOvh"])) {
$sender = \Message\AdapterFactory::factory("SmsOvh", $params["notification"]["ovh"]);
try {
$sender->send("La notification SMS est fonctionnelle.");
} catch (Exception $e) {
$errorsTest["ovh"] = "Erreur lors de l'envoi du SMS : (".$e->getCode().") ".$e->getMessage();
}
} elseif (!empty($_POST["testNotifyMyAndroid"])) {
if (empty($_POST["notification"]["notifymyandroid"]["token"])) {
$errors["notification"]["notifymyandroid"]["token"] = "Veuillez renseigner la clé d'identification.";
} else {
$sender = \Message\AdapterFactory::factory("notifymyandroid", $_POST["notification"]["notifymyandroid"]);
try {
$sender->send("La notification NotifyMyAndroid est fonctionnelle", array(
"title" => "Test alerte"
));
} catch (Exception $e) {
$errorsTest["notifymyandroid"] = "Erreur lors de l'envoi de la notification : (".$e->getCode().") ".$e->getMessage();
}
}
} elseif (!empty($_POST["testPushover"])) {
if (empty($_POST["notification"]["pushover"]["token"])) {
$errors["notification"]["pushover"]["token"] = "Veuillez renseigner la clé application.";
} elseif (empty($_POST["notification"]["pushover"]["user_key"])) {
$errors["notification"]["pushover"]["user_key"] = "Veuillez renseigner la clé utilisateur.";
} else {
$sender = \Message\AdapterFactory::factory("pushover", $_POST["notification"]["pushover"]);
try {
$sender->send("La notification Pushover est fonctionnelle");
} catch (Exception $e) {
$errorsTest["pushover"] = "Erreur lors de l'envoi de la notification : (".$e->getCode().") ".$e->getMessage();
}
}
} else {
$userAuthed->mergeOptions($params);
$userStorage->save($userAuthed);
$_SESSION["userSettingsSaved"] = true;
header("LOCATION: ./?mod=user&a=settings"); exit;
}
}
}
$userSettingsSaved = isset($_SESSION["userSettingsSaved"]) && true === $_SESSION["userSettingsSaved"];
unset($_SESSION["userSettingsSaved"]);

View File

@ -0,0 +1,250 @@
<form action="" method="post" autocomplete="off">
<?php if (!empty($errors)) : ?>
<p class="error" style="font-size: 1.3em; background: #AB0000; color: #FFF; text-align: center; line-height: 200%;">
Il y a au moins une erreur présente dans le formulaire.</p>
<?php elseif (!empty($errorsTest)) : ?>
<p class="error" style="font-size: 1.3em; background: #AB0000; color: #FFF; text-align: center; line-height: 200%;">
Le test d'envoi a échoué. Voir ci-dessous pour le message d'erreur.</p>
<?php elseif ($userSettingsSaved) : ?>
<p style="font-size: 1.3em; background: #00AB00; color: #FFF; text-align: center; line-height: 200%;">
Les paramètres ont été enregistrés.</p>
<?php endif;?>
<h2>Options générales</h2>
<dl>
<dt style="margin-bottom: 10px;">
<input type="hidden" name="unique_ads" value="0" />
<label for="unique_ads">
<input type="checkbox" id="unique_ads" name="unique_ads" value="1"<?php
echo $params["unique_ads"] ?' checked="checked"':''
?> style="margin-left: 0;" />
Cochez la case pour ne pas recevoir les annonces remontées (évite les doublons).
</label>
</dt>
</dl>
<h2 id="configFreeMobile" class="formbox">Configuration SMS via Free Mobile</h2>
<dl id="configFreeMobile-content" style="display: <?php echo !empty($form_values["notification"]["freeMobile"]["user"]) ? "block" : "none"; ?>;">
<dt>
<label for="free_mobile_user">ID utilisateur</label>
</dt>
<dd>
<input type="text" id="free_mobile_user" name="notification[freeMobile][user]" value="<?php
echo htmlspecialchars($form_values["notification"]["freeMobile"]["user"]);
?>" />
<?php if (isset($errors["notification"]["freeMobile"]["user"])) : ?>
<p class="error"><?php echo $errors["notification"]["freeMobile"]["user"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="free_mobile_key">Clé d'identification</label>
</dt>
<dd>
<input type="text" id="free_mobile_key" name="notification[freeMobile][key]" value="<?php
echo htmlspecialchars($form_values["notification"]["freeMobile"]["key"]);
?>" />
<?php if (isset($errors["notification"]["freeMobile"]["key"])) : ?>
<p class="error"><?php echo $errors["notification"]["freeMobile"]["key"]; ?></p>
<?php endif; ?>
</dd>
<dt style="border: none;">
<input type="submit" name="testFreeMobile" value="Effectuer un test d'envoi SMS" />
</dt>
<?php if (empty($errors) && !empty($_POST["testFreeMobile"])) : ?>
<dd>
<?php if (isset($errorsTest["freeMobile"])) : ?>
<p style="font-weight: bold; color: #AB0000;"><?php
echo htmlspecialchars($errorsTest["freeMobile"]);
?></p>
<?php else: ?>
<p style="font-weight: bold; color: #333399;">Vous devriez recevoir un SMS contenant le message suivant:
« La notification SMS est fonctionnelle ».</p>
<p style="font-weight: bold; color: #339933;">Pensez à confirmer la configuration en cliquant sur "Enregistrer".</p>
<?php endif; ?>
</dd>
<?php endif; ?>
</dl>
<h2 id="configPushbullet" class="formbox">Configuration alerte via Pushbullet</h2>
<dl id="configPushbullet-content" style="display: <?php echo !empty($form_values["notification"]["pushbullet"]["token"]) ? "block" : "none"; ?>;">
<dt>
<label for="pushbullet_token">Clé du service</label>
</dt>
<dd>
<input type="text" id="pushbullet_token" name="notification[pushbullet][token]" value="<?php
echo htmlspecialchars($form_values["notification"]["pushbullet"]["token"]);
?>" />
<?php if (isset($errors["notification"]["pushbullet"]["token"])) : ?>
<p class="error"><?php echo $errors["notification"]["pushbullet"]["token"]; ?></p>
<?php endif; ?>
</dd>
<dt style="border: none;">
<input type="submit" name="testPushbullet" value="Effectuer un test d'envoi de message" />
</dt>
<?php if (empty($errors) && !empty($_POST["testPushbullet"])) : ?>
<dd>
<?php if (isset($errorsTest["pushbullet"])) : ?>
<p style="font-weight: bold; color: #AB0000;"><?php
echo htmlspecialchars($errorsTest["pushbullet"]);
?></p>
<?php else: ?>
<p style="font-weight: bold; color: #333399;">Vous devriez recevoir une notification contenant le message suivant:
« La notification Pushbullet est fonctionnelle ».</p>
<p style="font-weight: bold; color: #339933;">Pensez à confirmer la configuration en cliquant sur "Enregistrer".</p>
<?php endif; ?>
</dd>
<?php endif; ?>
</dl>
<h2 id="configOvh" class="formbox">Configuration SMS via OVH Telecom</h2>
<dl id="configOvh-content" style="display: <?php echo !empty($form_values["notification"]["ovh"]["account"]) ? "block" : "none"; ?>;">
<dt>
<label for="ovh_account">Numéro de compte</label>
</dt>
<dd>
<input type="text" id="ovh_account" name="notification[ovh][account]" value="<?php
echo htmlspecialchars($form_values["notification"]["ovh"]["account"]);
?>" placeholder="De la forme : sms-xxxxxxxx-x" />
<?php if (isset($errors["notification"]["ovh"]["account"])) : ?>
<p class="error"><?php echo $errors["notification"]["ovh"]["account"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="ovh_login">Utilisateur</label>
</dt>
<dd>
<input type="text" id="ovh_login" name="notification[ovh][login]" value="<?php
echo htmlspecialchars($form_values["notification"]["ovh"]["login"]);
?>" />
<?php if (isset($errors["notification"]["ovh"]["login"])) : ?>
<p class="error"><?php echo $errors["notification"]["ovh"]["login"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="ovh_password">Mot de passe</label>
</dt>
<dd>
<input type="text" id="ovh_password" name="notification[ovh][password]" value="<?php
echo htmlspecialchars($form_values["notification"]["ovh"]["password"]);
?>" />
<?php if (isset($errors["notification"]["ovh"]["password"])) : ?>
<p class="error"><?php echo $errors["notification"]["ovh"]["password"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="ovh_from">Expéditeur</label>
</dt>
<dd>
<input type="text" id="ovh_from" name="notification[ovh][from]" value="<?php
echo htmlspecialchars($form_values["notification"]["ovh"]["from"]);
?>" />
<?php if (isset($errors["notification"]["ovh"]["from"])) : ?>
<p class="error"><?php echo $errors["notification"]["ovh"]["from"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="ovh_to">Destinataire</label>
</dt>
<dd>
<input type="text" id="ovh_to" name="notification[ovh][to]" value="<?php
echo htmlspecialchars($form_values["notification"]["ovh"]["to"]);
?>" placeholder="Forme international (Ex: +33605040301)" />
<?php if (isset($errors["notification"]["ovh"]["to"])) : ?>
<p class="error"><?php echo $errors["notification"]["ovh"]["to"]; ?></p>
<?php endif; ?>
</dd>
<dt style="border: none;">
<input type="submit" name="testOvh" value="Effectuer un test d'envoi SMS" />
</dt>
<?php if (empty($errors) && !empty($_POST["testOvh"])) : ?>
<dd>
<?php if (isset($errorsTest["ovh"])) : ?>
<p style="font-weight: bold; color: #AB0000;"><?php
echo htmlspecialchars($errorsTest["ovh"]);
?></p>
<?php else: ?>
<p style="font-weight: bold; color: #333399;">Vous devriez recevoir un SMS contenant le message suivant:
« La notification SMS est fonctionnelle ».</p>
<p style="font-weight: bold; color: #339933;">Pensez à confirmer la configuration en cliquant sur "Enregistrer".</p>
<?php endif; ?>
</dd>
<?php endif; ?>
</dl>
<h2 id="configNotifyMyAndroid" class="formbox">Configuration alerte via NotifyMyAndroid</h2>
<dl id="configNotifyMyAndroid-content" style="display: <?php echo !empty($form_values["notification"]["notifymyandroid"]["token"]) ? "block" : "none"; ?>;">
<dt>
<label for="notifymyandroid_token">Clé du service</label>
</dt>
<dd>
<input type="text" id="notifymyandroid_token" name="notification[notifymyandroid][token]" value="<?php
echo htmlspecialchars($form_values["notification"]["notifymyandroid"]["token"]);
?>" />
<?php if (isset($errors["notification"]["notifymyandroid"]["token"])) : ?>
<p class="error"><?php echo $errors["notification"]["notifymyandroid"]["token"]; ?></p>
<?php endif; ?>
</dd>
<dt style="border: none;">
<input type="submit" name="testNotifyMyAndroid" value="Effectuer un test d'envoi de message" />
</dt>
<?php if (empty($errors) && !empty($_POST["testNotifyMyAndroid"])) : ?>
<dd>
<?php if (isset($errorsTest["notifymyandroid"])) : ?>
<p style="font-weight: bold; color: #AB0000;"><?php
echo htmlspecialchars($errorsTest["notifymyandroid"]);
?></p>
<?php else: ?>
<p style="font-weight: bold; color: #333399;">Vous devriez recevoir une notification contenant le message suivant:
« La notification NotifyMyAndroid est fonctionnelle ».</p>
<p style="font-weight: bold; color: #339933;">Pensez à confirmer la configuration en cliquant sur "Enregistrer".</p>
<?php endif; ?>
</dd>
<?php endif; ?>
</dl>
<h2 id="configPushover" class="formbox">Configuration alerte via Pushover</h2>
<dl id="configPushover-content" style="display: <?php echo !empty($form_values["notification"]["pushover"]["token"]) ? "block" : "none"; ?>;">
<dt>
<label for="pushover_token">Clé application</label>
</dt>
<dd>
<input type="text" id="pushover_token" name="notification[pushover][token]" value="<?php
echo htmlspecialchars($form_values["notification"]["pushover"]["token"]);
?>" />
<?php if (isset($errors["notification"]["pushover"]["token"])) : ?>
<p class="error"><?php echo $errors["notification"]["pushover"]["token"]; ?></p>
<?php endif; ?>
</dd>
<dt>
<label for="pushover_token">Clé utilisateur</label>
</dt>
<dd>
<input type="text" id="pushover_token" name="notification[pushover][user_key]" value="<?php
echo htmlspecialchars($form_values["notification"]["pushover"]["user_key"]);
?>" />
<?php if (isset($errors["notification"]["pushover"]["user_key"])) : ?>
<p class="error"><?php echo $errors["notification"]["pushover"]["user_key"]; ?></p>
<?php endif; ?>
</dd>
<dt style="border: none;">
<input type="submit" name="testPushover" value="Effectuer un test d'envoi de message" />
</dt>
<?php if (empty($errors) && !empty($_POST["testPushover"])) : ?>
<dd>
<?php if (isset($errorsTest["pushover"])) : ?>
<p style="font-weight: bold; color: #AB0000;"><?php
echo htmlspecialchars($errorsTest["pushover"]);
?></p>
<?php else: ?>
<p style="font-weight: bold; color: #333399;">Vous devriez recevoir une notification contenant le message suivant:
« La notification Pushover est fonctionnelle ».</p>
<p style="font-weight: bold; color: #339933;">Pensez à confirmer la configuration en cliquant sur "Enregistrer".</p>
<?php endif; ?>
</dd>
<?php endif; ?>
</dl>
<p><input type="submit" value="Enregistrer" />
| <a href="?mod=user&amp;a=settings">annuler les modifications</a></p>
</form>

188
sources/bootstrap.php Normal file
View File

@ -0,0 +1,188 @@
<?php
define("DOCUMENT_ROOT", __DIR__);
define("DS", DIRECTORY_SEPARATOR);
// Define application environment
defined("APPLICATION_ENV")
|| define("APPLICATION_ENV", (getenv("APPLICATION_ENV") ? getenv("APPLICATION_ENV") : "production"));
// Define application environment
define("APPLICATION_VERSION", require DOCUMENT_ROOT."/version.php");
set_include_path(
__DIR__."/lib".PATH_SEPARATOR.get_include_path()
);
require_once "Http/Client/Curl.php";
require_once "Config/Lite.php";
require_once "Log4php/Logger.php";
class Bootstrap
{
/**
* @var Config_Lite
*/
protected $_config;
/**
* @var HttpClientCurl
*/
protected $_client;
protected function initAutoload()
{
spl_autoload_register(function ($className) {
$filename = ltrim(str_replace("\\", "/", $className), "/");
if (false !== strpos($filename, "App/")) {
$filename = __DIR__."/app/models/".
str_replace("App/", "", $filename).".php";
} else {
$filename = __DIR__."/lib/".$filename.".php";
}
if (is_file($filename)) {
require_once $filename;
}
});
}
protected function initPHPConfig()
{
mb_internal_encoding("UTF-8");
if (function_exists("date_default_timezone_set")) {
date_default_timezone_set("Europe/Paris");
}
if (APPLICATION_ENV == "development") {
ini_set("display_errors", true);
ini_set("error_reporting", -1);
}
}
protected function initLogger()
{
Logger::configure(array(
"rootLogger" => array(
"appenders" => array("default"),
"level" => APPLICATION_ENV == "development"?"debug":"info"
),
"appenders" => array(
"default" => array(
"class" => "LoggerAppenderRollingFile",
"layout" => array(
"class" => "LoggerLayoutPattern",
"params" => array(
"conversionPattern" => "%date %-5level %msg%n"
)
),
"params" => array(
"file" => DOCUMENT_ROOT."/var/log/info.log",
"maxFileSize" => "3MB",
"maxBackupIndex" => 5,
"append" => true
)
)
)
));
}
protected function initConfig()
{
// valeurs par défaut.
$this->_config->set("proxy", "ip", "");
$this->_config->set("proxy", "port", "");
$this->_config->set("proxy", "user", "");
$this->_config->set("proxy", "password", "");
$this->_config->set("http", "user_agent", "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.6) Gecko/20100628 Ubuntu/10.04 (lucid) Firefox/3.6.6");
$this->_config->set("general", "check_start", 7);
$this->_config->set("general", "check_end", 24);
$this->_config->set("general", "version", 0);
$this->_config->set("general", "baseurl", "");
$this->_config->set("storage", "type", "files");
// lit la configuration du fichier.
try {
$this->_config->read();
} catch (Config_Lite_Exception_Runtime $e) {
return;
}
if (isset($_SERVER["HTTP_HOST"])) {
$current_base_url = $this->_config->get("general", "baseurl", "");
$base_url = "http";
if (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] != "off") {
$base_url .= "s";
}
$base_url .= "://".$_SERVER["HTTP_HOST"]."/";
if (!empty($_SERVER["REQUEST_URI"])) {
$request_uri = trim($_SERVER["REQUEST_URI"], "/");
if (false !== $pos = strpos($request_uri, "?")) {
$request_uri = mb_substr($request_uri, 0, $pos);
}
if (false !== strpos($request_uri, ".php")) {
$request_uri = substr($request_uri, 0, strrpos($request_uri, "/"));
}
if ($request_uri) {
$base_url .= trim($request_uri, "/")."/";
}
}
if ($base_url != $current_base_url) {
$this->_config->set("general", "baseurl", $base_url);
$this->_config->save();
}
}
}
public function getClient()
{
if (!$this->_client) {
$client = new HttpClientCurl();
$proxy = $this->_config->get("proxy", null, array());
if (!empty($proxy["ip"])) {
$client->setProxyIp($proxy["ip"]);
if (!empty($proxy["port"])) {
$client->setProxyPort($proxy["port"]);
}
}
if ($userAgent = $this->_config->get("http", "user_agent", "")) {
$client->setUserAgent($userAgent);
}
}
return $client;
}
public function __construct()
{
}
public function bootstrap(Config_Lite $config)
{
$this->_config = $config;
foreach (get_class_methods($this) AS $method) {
if (0 === strpos($method, "init")) {
$this->$method();
}
}
}
}
$config = new Config_Lite(DOCUMENT_ROOT."/var/config.ini");
$bootstrap = new Bootstrap();
$bootstrap->bootstrap($config);
$userAuthed = null;
// initialise le client HTTP.
$client = $bootstrap->getClient();
// si stockage en base de données, on initialise la connexion
if ("db" == $config->get("storage", "type", "files")) {
$options = array_merge(array(
"host" => "",
"user" => "",
"password" => "",
"dbname" => ""
), $config->get("storage", "options"));
$dbConnection = new mysqli($options["host"], $options["user"],
$options["password"], $options["dbname"]);
unset($options);
}

2
sources/check.php Normal file
View File

@ -0,0 +1,2 @@
<?php
require __DIR__."/app/mail/scripts/check.php";

95
sources/index.php Normal file
View File

@ -0,0 +1,95 @@
<?php
header('Content-Type: text/html; charset=utf-8');
require __DIR__."/bootstrap.php";
$module = "default";
if (isset($_GET["mod"])) {
$module = $_GET["mod"];
}
$action = "index";
if (isset($_GET["a"])) {
$action = $_GET["a"];
}
if (!$currentVersion = $config->get("general", "version")) {
if ($module != "install") {
$module = "install";
}
} elseif (isset($_GET["url"])) { // rendre compatible avec l'ancien système de flux RSS
$module = "rss";
$action = "refresh";
}
if ($module != "install") {
$storageType = $config->get("storage", "type", "files");
if ($storageType == "db") {
$userStorage = new \App\Storage\Db\User($dbConnection);
} else {
$userStorage = new \App\Storage\File\User(DOCUMENT_ROOT."/var/users.db");
}
// identification nécessaire
if ($module == "rss" && $action == "refresh") {
$auth = new Auth\Session($userStorage);
if (!$userAuthed = $auth->authenticate()) {
$auth = new Auth\Basic($userStorage);
if (!$userAuthed = $auth->authenticate()) {
header('WWW-Authenticate: Basic realm="Identification"');
header('HTTP/1.0 401 Unauthorized');
echo "Non autorisé.";
exit;
}
}
} else {
$auth = new Auth\Session($userStorage);
if (!$userAuthed = $auth->authenticate()) {
$module = "default";
$action = "login";
}
}
$upgradeStarted = version_compare($currentVersion, APPLICATION_VERSION, "<");
if ($upgradeStarted) {
if ($userAuthed && $userAuthed->isAdmin()) {
if ($module != "admin" || $action != "upgrade") {
header("LOCATION: ./?mod=admin&a=upgrade");
exit;
}
} elseif ($action != "login") {
require DOCUMENT_ROOT."/app/default/views/upgrade.phtml";
return;
}
}
}
$init = DOCUMENT_ROOT."/app/".$module."/init.php";
$script = DOCUMENT_ROOT."/app/".$module."/scripts/".$action.".php";
$view = DOCUMENT_ROOT."/app/".$module."/views/".$action.".phtml";
$layout = DOCUMENT_ROOT."/app/".$module."/views/layout.phtml";
if (is_file($init)) {
require $init;
}
if (is_file($script)) {
require $script;
}
if (!is_file($layout)) {
$layout = DOCUMENT_ROOT."/app/default/views/layout.phtml";
}
ob_start();
if (is_file($view)) {
require $view;
}
$content = ob_get_clean();
if (isset($disableLayout) && $disableLayout == true) {
echo $content;
} else {
require $layout;
}

View File

@ -0,0 +1,287 @@
<?php
namespace AdService;
class Ad
{
protected $_id;
protected $_link;
protected $_link_mobile;
protected $_title;
protected $_description;
protected $_price;
protected $_currency = "";
protected $_date;
protected $_category;
protected $_country;
protected $_city;
protected $_professional;
protected $_thumbnail_link;
protected $_urgent;
/**
* @param int $id
* @return \AdService\Ad
*/
public function setId($id)
{
$this->_id = $id;
return $this;
}
/**
* @return int
*/
public function getId()
{
return $this->_id;
}
/**
* @param string $link
* @return \AdService\Ad
*/
public function setLink($link)
{
$this->_link = $link;
return $this;
}
/**
* @return string
*/
public function getLink()
{
return $this->_link;
}
/**
* @param string $link
* @return \AdService\Ad
*/
public function setLinkMobile($link)
{
$this->_link_mobile = $link;
return $this;
}
/**
* @return string
*/
public function getLinkMobile()
{
return $this->_link_mobile;
}
/**
* @param string $title
* @return \AdService\Ad
*/
public function setTitle($title)
{
$this->_title = $title;
return $this;
}
/**
* @return string
*/
public function getTitle()
{
return $this->_title;
}
/**
* @param string $description
* @return \AdService\Ad
*/
public function setDescription($description)
{
$this->_description = $description;
return $this;
}
/**
* @return string
*/
public function getDescription()
{
return $this->_description;
}
/**
* @param int $price
* @return \AdService\Ad
*/
public function setPrice($price)
{
// $this->_price = (int) preg_replace('/[^0-9]*/', '', $price);
$this->_price = $price;
return $this;
}
/**
* @return int
*/
public function getPrice()
{
return $this->_price;
}
/**
* @param string $currency
* @return Ad
*/
public function setCurrency($currency)
{
$this->_currency = $currency;
return $this;
}
/**
* @return string
*/
public function getCurrency()
{
return $this->_currency;
}
/**
* @param Zend_Date $date
* @return \AdService\Ad
*/
public function setDate($date)
{
$this->_date = $date;
return $this;
}
/**
* @return string
*/
public function getDate()
{
return $this->_date;
}
/**
* @param string $category
* @return \AdService\Ad
*/
public function setCategory($category)
{
$this->_category = $category;
return $this;
}
/**
* @return string
*/
public function getCategory()
{
return $this->_category;
}
/**
* @param string $county
* @return \AdService\Ad
*/
public function setCountry($county)
{
$this->_country = $county;
return $this;
}
/**
* @return string
*/
public function getCountry()
{
return $this->_country;
}
/**
* @param string $city
* @return \AdService\Ad
*/
public function setCity($city)
{
$this->_city = $city;
return $this;
}
/**
* @return string
*/
public function getCity()
{
return $this->_city;
}
/**
* @param bool $professional
* @return \AdService\Ad
*/
public function setProfessional($professional)
{
$this->_professional = $professional;
return $this;
}
/**
* @return bool
*/
public function getProfessional()
{
return $this->_professional;
}
/**
* @param string $thumbail
* @return \AdService\Ad
*/
public function setThumbnailLink($thumbail)
{
$this->_thumbnail_link = $thumbail;
return $this;
}
/**
* @return string
*/
public function getThumbnailLink()
{
return $this->_thumbnail_link;
}
/**
* @param bool $urgent
* @return \AdService\Ad
*/
public function setUrgent($urgent)
{
$this->_urgent = (bool)$urgent;
return $this;
}
/**
* @return bool
*/
public function getUrgent()
{
return $this->_urgent;
}
}

View File

@ -0,0 +1,8 @@
<?php
namespace AdService;
class Exception extends \Exception
{
}

View File

@ -0,0 +1,188 @@
<?php
namespace AdService;
class Filter
{
protected $min_id = 0;
protected $exclude_ids = array();
protected $price_min = -1;
protected $price_max = -1;
protected $price_strict = false;
protected $cities = "";
protected $categories = array();
public function __construct(array $options = array())
{
$this->setFromArray($options);
}
public function isValid(Ad $ad)
{
if (!$ad->getPrice() && $this->price_strict) {
return false;
}
if ($ad->getPrice()) {
if ($this->price_min != -1 && $ad->getPrice() < $this->price_min
|| $this->price_max != -1 && $ad->getPrice() > $this->price_max) {
return false;
}
}
$city = mb_strtolower($ad->getCity());
$country = mb_strtolower($ad->getCountry());
if ($this->cities && !in_array($city, $this->cities) && !in_array($country, $this->cities)) {
return false;
}
if ($this->categories && !in_array($ad->getCategory(), $this->categories)) {
return false;
}
return true;
}
public function setFromArray(array $options)
{
foreach ($options AS $option => $value) {
$method = "set".str_replace(" ", "", ucwords(
str_replace("_", " ", $option)));
if (method_exists($this, $method)) {
$this->$method($value);
}
}
}
/**
* @param int $min_id
* @return Filter
*/
public function setMinId($min_id)
{
$this->min_id = $min_id;
return $this;
}
/**
* @return int
*/
public function getMinId()
{
return $this->min_id;
}
/**
* @param array $exclude_ids
* @return Filter
*/
public function setExcludeIds($exclude_ids)
{
$this->exclude_ids = $exclude_ids;
return $this;
}
/**
* @return array
*/
public function getExcludeIds()
{
return $this->exclude_ids;
}
/**
* @param int $price_min
* @return Filter
*/
public function setPriceMin($price_min)
{
$this->price_min = $price_min;
return $this;
}
/**
* @return int
*/
public function getPriceMin()
{
return $this->price_min;
}
/**
* @param int $price_max
* @return Filter
*/
public function setPriceMax($price_max)
{
$this->price_max = $price_max;
return $this;
}
/**
* @return int
*/
public function getPriceMax()
{
return $this->price_max;
}
/**
* @param bool $price_strict
* @return Filter
*/
public function setPriceStrict($price_strict)
{
$this->price_strict = $price_strict;
return $this;
}
/**
* @return bool
*/
public function getPriceStrict()
{
return $this->price_strict;
}
/**
* @param array $cities
* @return Filter
*/
public function setCities(array $cities)
{
$this->cities = $cities;
return $this;
}
/**
* @return array
*/
public function getCities()
{
return $this->cities;
}
/**
* @param array $categories
* @return Filter
*/
public function setCategories(array $categories)
{
$this->categories = $categories;
return $this;
}
/**
* @return array
*/
public function getCategories()
{
return $this->categories;
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace AdService\Parser;
use AdService\Filter;
abstract class AbstractParser extends \DOMDocument
{
public function __construct()
{
libxml_use_internal_errors(true);
}
/**
* @param string $content
* @param Filter $filter
*/
abstract public function process($content, Filter $filter = null);
}

View File

@ -0,0 +1,177 @@
<?php
namespace AdService\Parser;
use AdService\Filter;
use AdService\Ad;
class Lbc extends AbstractParser
{
protected static $months = array(
"jan" => 1, "fév" => 2, "mars" => 3, "avr" => 4,
"mai" => 5, "juin" => 6, "juillet" => 7, "août" => 8,
"sept" => 9, "oct" => 10, "nov" => 11,
"déc" => 12
);
protected $scheme;
public function process($content, Filter $filter = null, $scheme = "http") {
if (!$content) {
return;
}
$this->scheme = $scheme;
$this->loadHTML($content);
$timeToday = strtotime(date("Y-m-d")." 23:59:59");
$dateYesterday = $timeToday - 24*3600;
$ads = array();
if ($filter) {
$exclude_ids = $filter->getExcludeIds();
/**
* Afin de garder une rétrocompatibilité, on prend en compte
* que $exclude_ids peut être numérique.
*/
if (!is_numeric($exclude_ids) && !is_array($exclude_ids)) {
unset($exclude_ids);
}
}
$adNodes = $this->getElementsByTagName("a");
foreach ($adNodes AS $result) {
// est-ce bien une annonce ?
if (false === strpos($result->getAttribute("class"), "list_item")) {
continue;
}
$ad = new Ad();
$ad->setProfessional(false)->setUrgent(false);
// pas d'ID, pas d'annonce
if (!preg_match('/([0-9]+)\.htm.*/', $result->getAttribute("href"), $m)) {
continue;
}
// permet d'éliminer les annonces déjà envoyées.
if (isset($exclude_ids)) {
if (is_numeric($exclude_ids)) {
/**
* Si $exclude_ids est numérique, alors détection
* à l'ancienne. Quand on rencontre l'ID de la
* dernière annonce, on stoppe la boucle.
*/
if ($m[1] == $exclude_ids) {
break;
}
} elseif (in_array($m[1], $exclude_ids)) {
continue;
}
}
// permet d'éliminer les annonces déjà envoyées.
if ($filter && $m[1] <= $filter->getMinId()) {
continue;
}
$ad->setLink($this->formatLink($result->getAttribute("href")))
->setId($m[1])
->setTitle($result->getAttribute("title"))
->setLinkMobile(str_replace(
array("http://www.", "https://www."),
array("http://mobile.", "https://mobile."),
$ad->getLink()
));
// recherche de l'image
foreach ($result->getElementsByTagName("span") AS $node) {
if ($src = $node->getAttribute("data-imgsrc")) {
$ad->setThumbnailLink($this->formatLink($src));
}
}
$i = 0;
foreach ($result->getElementsByTagName("p") AS $node) {
$class = (string) $node->getAttribute("class");
if (false !== strpos($class, "item_supp")) {
$value = trim($node->nodeValue);
if ($i == 0) { // catégorie
if (false !== strpos($value, "(pro)")) {
$ad->setProfessional(true);
}
$ad->setCategory(trim(str_replace("(pro)", "", $value)));
} elseif ($i == 1) { // localisation
if (false !== strpos($value, "/")) {
$value = explode("/", $value);
$ad->setCountry(trim($value[1]))
->setCity(trim($value[0]));
} else {
$ad->setCountry(trim($value));
}
} elseif ($i == 2) { // date de l'annonce + urgent
$spans = $node->getElementsByTagName("span");
if ($spans->length > 0) {
$ad->setUrgent(true);
$node->removeChild($spans->item(0));
$value = trim($node->nodeValue);
}
$dateStr = preg_replace("#\s+#", " ", $value);
$aDate = explode(' ', $dateStr);
$aDate[1] = trim($aDate[1], ",");
if (false !== strpos($dateStr, 'Aujourd')) {
$time = strtotime(date("Y-m-d")." 00:00:00");
} elseif (false !== strpos($dateStr, 'Hier')) {
$time = strtotime(date("Y-m-d")." 00:00:00");
$time = strtotime("-1 day", $time);
} else {
if (!isset(self::$months[$aDate[1]])) {
continue;
}
$time = strtotime(date("Y")."-".self::$months[$aDate[1]]."-".$aDate[0]);
}
$aTime = explode(":", $aDate[count($aDate) - 1]);
$time += (int)$aTime[0] * 3600 + (int)$aTime[1] * 60;
if ($timeToday < $time) {
$time = strtotime("-1 year", $time);
}
$ad->setDate($time);
}
$i++;
}
}
// recherche du prix
foreach ($result->getElementsByTagName("h3") AS $node) {
$class = (string) $node->getAttribute("class");
if (false !== strpos($class, "item_price")) {
if (preg_match("#[0-9 ]+#", $node->nodeValue, $m)) {
$ad->setPrice((int)str_replace(" ", "", trim($m[0])));
}
}
}
// exclure les annonces ne correspondant pas au filtre.
if ($filter && !$filter->isValid($ad)) {
continue;
}
$ads[$ad->getId()] = $ad;
}
return $ads;
}
protected function formatLink($link)
{
if (0 === strpos($link, "//")) {
$link = $this->scheme.":".$link;
}
return $link;
}
}

View File

@ -0,0 +1,137 @@
<?php
namespace AdService\Parser;
use AdService\Filter;
use AdService\Ad;
class Olx extends AbstractParser
{
protected static $months = array(
"jan" => 1, "fév" => 2, "mars" => 3, "апр." => 4,
"mai" => 5, "juin" => 6, "juillet" => 7, "août" => 8,
"sept" => 9, "oct" => 10, "nov" => 11,
"déc" => 12
);
public function process($content, Filter $filter = null) {
if (!$content) {
return;
}
$content = str_replace("<br/>", " ", $content);
$this->loadHTML($content);
$timeToday = strtotime(date("Y-m-d")." 23:59:59");
$dateYesterday = $timeToday - 24*3600;
$ads = array();
$tables = $this->getElementsByTagName("table");
$tableOffers = null;
foreach ($tables AS $table) {
if (false !== strpos($table->getAttribute("id"), "offers_table")) {
$tableOffers = $table;
break;
}
}
if (!$tableOffers) {
return array();
}
$adNodes = $tableOffers->getElementsByTagName("td");
foreach ($adNodes AS $adNode) {
if (false === strpos($adNode->getAttribute("class"), "offer")) {
continue;
}
$ad = new Ad();
$ad->setUrgent(false);
// aucun indicateur pour savoir si c'est un pro ou non.
$ad->setProfessional(false);
// permet d'éliminer les annonces déjà envoyées.
// @todo pour le moment, pas possible. Les IDs ne semblent pas
// numérique et incrémentals.
// if ($filter && $m[1] <= $filter->getMinId()) {
// continue;
// }
$rows = $adNode->getElementsByTagName("tr");
if (0 == $rows->length) {
continue;
}
$columns = $adNode->getElementsByTagName("td");
$row2_p = $rows->item(1)->getElementsByTagName("p");
// analyse de la date
$dateStr = preg_replace("#\s+#", " ", trim($row2_p->item(1)->nodeValue));
if (!$dateStr) {
continue;
}
$aDate = explode(' ', $dateStr);
if (false !== strpos($dateStr, 'Сегодня')) { // aujourd'hui
$time = strtotime(date("Y-m-d")." 00:00:00");
} elseif (false !== strpos($dateStr, 'Вчера')) {
$time = strtotime(date("Y-m-d")." 00:00:00");
$time = strtotime("-1 day", $time);
} else {
if (!isset(self::$months[$aDate[1]])) {
continue;
}
$time = strtotime(date("Y")."-".self::$months[$aDate[1]]."-".$aDate[0]);
}
$timeStr = $aDate[count($aDate) - 1];
if (false !== $pos = mb_strpos($dateStr, ":")) {
$time += (int)mb_substr($dateStr, $pos - 2, 2) * 3600;
$time += (int)mb_substr($dateStr, $pos + 1, 2) * 60;
if ($timeToday < $time) {
$time = strtotime("-1 year", $time);
}
}
$ad->setDate($time);
// image
$img = $columns->item(0)->getElementsByTagName("img");
if ($img->length) {
$ad->setThumbnailLink(str_replace("94x72", "644x461", $img->item(0)->getAttribute("src")));
}
// titre + lien
$link = $adNode->getElementsByTagName("h3")->item(0)->getElementsByTagName("a")->item(0);
if ($link) {
$ad->setTitle(trim($link->nodeValue));
$ad->setLink($link->getAttribute("href"));
}
// urgent
if (false !== strpos($adNode->nodeValue, "Срочно")) {
$ad->setUrgent(true);
}
// lieu
$ad->setCity(trim($row2_p->item(0)->nodeValue));
// catégorie
$ad->setCategory(trim($columns->item(1)->getElementsByTagName("p")->item(0)->nodeValue));
if (!preg_match("#ID([^.]+)\.html#", $ad->getLink(), $m)) {
continue;
}
$ad->setId(base_convert($m[1], 32, 10));
$priceColumn = trim($columns->item(2)->nodeValue);
if (preg_match('#(?<price>[0-9\s]+)\s+(?<currency>грн|\$|€)#imsU', $priceColumn, $m)) {
$ad->setPrice((int) str_replace(" ", "", $m["price"]))
->setCurrency($m["currency"]);
}
if ($filter && !$filter->isValid($ad)) {
continue;
}
$ads[$ad->getId()] = $ad;
}
return $ads;
}
}

View File

@ -0,0 +1,125 @@
<?php
namespace AdService\Parser;
use AdService\Filter;
use AdService\Ad;
class Seloger extends AbstractParser
{
public function process($content, Filter $filter = null) {
if (!$content) {
return;
}
// pourquoi est-ce nécessaire ?! Je n'ai pas encore trouvé la raison.
$content = utf8_decode($content);
$this->loadHTML($content);
$timeToday = strtotime(date("Y-m-d")." 23:59:59");
$dateYesterday = $timeToday - 24*3600;
$ads = array();
$sections = $this->getElementsByTagName("section");
$section_results = null;
foreach ($sections AS $section) {
if (false !== strpos($section->getAttribute("class"), "liste_resultat")) {
$section_results = $section;
break;
}
}
if (!$section_results) {
return array();
}
if ($filter) {
$exclude_ids = $filter->getExcludeIds();
/**
* Afin de garder une rétrocompatibilité, on prend en compte
* que $exclude_ids peut être numérique.
*/
if (!is_numeric($exclude_ids) && !is_array($exclude_ids)) {
unset($exclude_ids);
}
}
$adNodes = $section_results->getElementsByTagName("article");
foreach ($adNodes AS $adNode) {
if (!$id = (int) $adNode->getAttribute("data-listing-id")) {
continue;
}
// permet d'éliminer les annonces déjà envoyées.
if (isset($exclude_ids)) {
if (is_numeric($exclude_ids)) {
/**
* Si $exclude_ids est numérique, alors détection
* à l'ancienne. Quand on rencontre l'ID de la
* dernière annonce, on stoppe la boucle.
*/
if ($id == $exclude_ids) {
break;
}
} elseif (in_array($id, $exclude_ids)) {
continue;
}
}
$ad = new Ad();
$ad->setUrgent(false)
->setId($id);
// aucun indicateur pour savoir si c'est un pro ou non.
$ad->setProfessional(false);
// image
$imgs = $adNode->getElementsByTagName("img");
if ($imgs->length) {
foreach ($imgs AS $img) {
if (false !== strpos($img->getAttribute("class"), "listing_photo")) {
$ad->setThumbnailLink(
str_replace(
array("c175", "c250"),
"b600",
$img->getAttribute("src"))
);
break;
}
}
}
// titre + lien + lieu
$link = $adNode->getElementsByTagName("h2")->item(0)
->getElementsByTagName("a")->item(0);
if ($link) {
$city = $link->getElementsByTagName("span")->item(0);
if ($city) {
// lieu
$ad->setCity(trim($city->nodeValue));
}
$ad->setTitle(trim($link->nodeValue));
$ad->setLink($link->getAttribute("href"));
}
$links = $adNode->getElementsByTagName("a");
if ($links->length) {
foreach ($links AS $link) {
$classCSS = $link->getAttribute("class");
if (false !== strpos($classCSS, "amount")) {
$ad->setPrice((int) preg_replace("#[^0-9]*#", "", $link->nodeValue));
}
}
}
if ($filter && !$filter->isValid($ad)) {
continue;
}
$ads[$ad->getId()] = $ad;
}
return $ads;
}
}

View File

@ -0,0 +1,24 @@
<?php
namespace AdService;
class ParserFactory
{
/**
* @param string $url
* @return \AdService\Parser\AbstractParser
*/
public static function factory($url)
{
if (false !== strpos($url, "leboncoin.fr")) {
return new Parser\Lbc();
}
if (false !== strpos($url, "olx.ua")) {
return new Parser\Olx();
}
if (false !== strpos($url, "seloger.com")) {
return new Parser\Seloger();
}
throw new Exception("No parser found");
}
}

View File

@ -0,0 +1,46 @@
<?php
namespace AdService\SiteConfig;
abstract class AbstractSiteConfig
{
/**
* Nom du site
* @var string
*/
protected $site_name = "";
/**
* URL du site
* @var string
*/
protected $site_url = "";
/**
* Les devises acceptées par le site.
* @var array
*/
protected $currencies = array("");
/**
* Indique si l'information d'une annonce pro ou particulier est disponible
* dans la liste d'annonce.
* @var bool
*/
protected $pro_visible = true;
/**
* Indique si le site fourni une date par annonce.
* @var bool
*/
protected $has_date = true;
/**
* @param string $name
* @return mixed
*/
public function getOption($name)
{
return isset($this->$name) ? $this->$name : null;
}
}

View File

@ -0,0 +1,9 @@
<?php
namespace AdService\SiteConfig;
class Lbc extends AbstractSiteConfig
{
protected $site_name = "LeBonCoin";
protected $site_url = "https://www.leboncoin.fr";
}

View File

@ -0,0 +1,11 @@
<?php
namespace AdService\SiteConfig;
class Olx extends AbstractSiteConfig
{
protected $site_name = "Olx";
protected $site_url = "http://olx.ua";
protected $currencies = array("", "\$", "грн");
protected $pro_visible = false;
}

View File

@ -0,0 +1,11 @@
<?php
namespace AdService\SiteConfig;
class Seloger extends AbstractSiteConfig
{
protected $site_name = "SeLoger";
protected $site_url = "http://www.seloger.com";
protected $pro_visible = false;
protected $has_date = false;
}

View File

@ -0,0 +1,33 @@
<?php
namespace AdService;
class SiteConfigFactory
{
protected static $instances;
/**
* @param string $url
* @param bool $singleton en général, c'est la même config pour tous.
* @return \AdService\SiteConfig\AbstractSiteConfig
*/
public static function factory($url, $singleton=true)
{
if (false !== strpos($url, "leboncoin.fr")) {
$className = 'AdService\SiteConfig\Lbc';
} elseif (false !== strpos($url, "olx.ua")) {
$className = 'AdService\SiteConfig\Olx';
} elseif (false !== strpos($url, "www.seloger.com")) {
$className = 'AdService\SiteConfig\Seloger';
} else {
throw new Exception("No config found");
}
if ($singleton) {
if (!isset(self::$instances[$className])) {
self::$instances[$className] = new $className;
}
return self::$instances[$className];
}
return new $className;
}
}

View File

@ -0,0 +1,70 @@
<?php
namespace Auth;
abstract class AuthAbstract
{
protected $_username;
protected $_password;
/**
*
* @var App\Storage\User
*/
protected $_storage;
public function __construct(\App\Storage\User $storage)
{
$this->_storage = $storage;
}
/**
* @param string $username
* @return Basic
*/
public function setUsername($username)
{
$this->_username = $username;
return $this;
}
/**
* @return string
*/
public function getUsername()
{
return $this->_username;
}
/**
* @param string $password
* @return Basic
*/
public function setPassword($password)
{
$this->_password = $password;
return $this;
}
/**
* @return string
*/
public function getPassword()
{
return $this->_password;
}
public function authenticate()
{
if (!$this->_username || !$this->_password) {
return null;
}
$user = $this->_storage->fetchByUsername($this->_username);
if ($user && $user->getPassword() == $this->_password) {
return $user;
}
return null;
}
public function clear() {}
}

View File

@ -0,0 +1,19 @@
<?php
namespace Auth;
require_once __DIR__."/Abstract.php";
class Basic extends AuthAbstract
{
public function __construct(\App\Storage\User $storage)
{
if (!$this->_username && isset($_SERVER["PHP_AUTH_USER"])) {
$this->setUsername($_SERVER["PHP_AUTH_USER"]);
}
if (!$this->_password && isset($_SERVER["PHP_AUTH_PW"])) {
$this->setPassword(sha1($_SERVER["PHP_AUTH_PW"]));
}
parent::__construct($storage);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace Auth;
require_once __DIR__."/Abstract.php";
class Session extends AuthAbstract
{
public function __construct(\App\Storage\User $storage)
{
session_name("lbcalerte");
session_start();
if (isset($_SESSION["lbcauth"])) {
if (isset($_SESSION["lbcauth"]["username"])) {
$this->_username = $_SESSION["lbcauth"]["username"];
}
if (isset($_SESSION["lbcauth"]["password"])) {
$this->_password = $_SESSION["lbcauth"]["password"];
}
}
parent::__construct($storage);
}
public function __destruct()
{
session_write_close();
}
public function clear()
{
unset($_SESSION["lbcauth"]);
}
public function authenticate()
{
if ($user = parent::authenticate()) {
$_SESSION["lbcauth"] = array(
"username" => $user->getUsername(),
"password" => $user->getPassword()
);
return $user;
}
return null;
}
}

838
sources/lib/Config/Lite.php Normal file
View File

@ -0,0 +1,838 @@
<?php
/**
* Config_Lite (Config/Lite.php)
*
* PHP version 5
*
* @file Config/Lite.php
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version SVN: $Id$
* @link https://github.com/pce/config_lite
*/
require_once 'Config/Lite/Exception.php';
require_once 'Config/Lite/Exception/InvalidArgument.php';
require_once 'Config/Lite/Exception/Runtime.php';
require_once 'Config/Lite/Exception/UnexpectedValue.php';
/**
* Config_Lite Class
*
* read and save ini text files.
* Config_Lite has the native PHP function
* `parse_ini_file' under the hood.
* The API is inspired by Python's ConfigParser.
* A "Config_Lite" file consists of
* "name = value" entries and sections,
* "[section]"
* followed by "name = value" entries
*
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @link https://github.com/pce/config_lite
*/
class Config_Lite implements ArrayAccess, IteratorAggregate, Countable, Serializable
{
/**
* sections, holds the config sections
*
* @var array
*/
protected $sections;
/**
* filename
*
* @var string
*/
protected $filename;
/**
* _booleans - alias of bool in a representable Configuration String Format
*
* @var array
*/
private $_booleans = array('1' => true, 'on' => true,
'true' => true, 'yes' => true,
'0' => false, 'off' => false,
'false' => false, 'no' => false);
/**
* line-break chars, default *x: "\n", windows: "\r\n"
*
* @var string
*/
protected $linebreak = "\n";
/**
* parseSections - if true, sections will be processed
*
* @var bool
*/
protected $processSections = true;
/**
* quote Strings - if true,
* writes ini files with doublequoted strings
*
* @var bool
*/
protected $quoteStrings = true;
/**
* the read method parses the optional given filename
* or already setted filename.
*
* this method uses the native PHP function
* parse_ini_file behind the scenes.
*
* @param string $filename Filename
*
* @return void
* @throws Config_Lite_Exception_Runtime when file not found
* @throws Config_Lite_Exception_Runtime when file is not readable
* @throws Config_Lite_Exception_Runtime when parse ini file failed
*/
public function read($filename = null)
{
if (null === $filename) {
$filename = $this->filename;
} else {
$this->filename = $filename;
}
if (!file_exists($filename)) {
throw new Config_Lite_Exception_Runtime('file not found: ' . $filename);
}
if (!is_readable($filename)) {
throw new Config_Lite_Exception_Runtime(
'file not readable: ' . $filename
);
}
$this->sections = parse_ini_file($filename, $this->processSections);
if (false === $this->sections) {
throw new Config_Lite_Exception_Runtime(
'failure, can not parse the file: ' . $filename
);
}
}
/**
* save the object to the already setted filename
* (active record style)
*
* @return bool
*/
public function save()
{
return $this->write($this->filename, $this->sections);
}
/**
* sync the file to the object
*
* like `save',
* but after written the data, reads the data back into the object.
* The method is inspired by QTSettings.
* Ideal for testing.
*
* @return void
* @throws Config_Lite_Exception_Runtime when file is not set,
* write or readable
*/
public function sync()
{
if (!isset($this->filename)) {
throw new Config_Lite_Exception_Runtime('no filename set.');
}
if (!is_array($this->sections)) {
$this->sections = array();
}
if ($this->write($this->filename, $this->sections)) {
$this->read($this->filename);
}
}
/**
* detect Type "bool" by String Value to keep those "untouched"
*
* @param string $value value
*
* @return bool
*/
protected function isBool($value)
{
return in_array($value, $this->_booleans);
}
/**
* normalize a Value by determining the Type
*
* @param string $value value
*
* @return string
*/
protected function normalizeValue($value)
{
if (is_bool($value)) {
$value = $this->toBool($value);
return $value;
} elseif (is_numeric($value)) {
return $value;
}
if ($this->quoteStrings) {
$value = '"' . $value . '"';
}
return $value;
}
/**
* generic write ini config file, to save use `save'.
*
* writes the global options and sections with normalized Values,
* that means "bool" values to human readable representation,
* doublequotes strings and numeric values without any quotes.
* prepends a php exit if suffix is php,
* it is valid to write an empty Config file,
* this method is used by save and is public for explicit usage,
* eg. if you do not want to hold the whole configuration in the object.
*
* @param string $filename filename
* @param array $sectionsarray array with sections
*
* @return bool
* @throws Config_Lite_Exception_Runtime when file is not writeable
* @throws Config_Lite_Exception_Runtime when write failed
*/
public function write($filename, $sectionsarray)
{
$content = $this->buildOutputString($sectionsarray);
if (false === file_put_contents($filename, $content, LOCK_EX)) {
throw new Config_Lite_Exception_Runtime(
sprintf(
'failed to write file `%s\' for writing.', $filename
)
);
}
return true;
}
/**
* Generated the output of the ini file, suitable for echo'ing or
* writing back to the ini file.
*
* @param string $sectionsarray array of ini data
*
* @return string
*/
protected function buildOutputString($sectionsarray)
{
$content = '';
$sections = '';
$globals = '';
if (!empty($sectionsarray)) {
// 2 loops to write `globals' on top, alternative: buffer
foreach ($sectionsarray as $section => $item) {
if (!is_array($item)) {
$value = $this->normalizeValue($item);
$globals .= $section . ' = ' . $value . $this->linebreak;
}
}
$content .= $globals;
foreach ($sectionsarray as $section => $item) {
if (is_array($item)) {
$sections .= $this->linebreak
. "[" . $section . "]" . $this->linebreak;
foreach ($item as $key => $value) {
if (is_array($value)) {
foreach ($value as $arrkey => $arrvalue) {
$arrvalue = $this->normalizeValue($arrvalue);
$arrkey = $key . '[' . $arrkey . ']';
$sections .= $arrkey . ' = ' . $arrvalue
. $this->linebreak;
}
} else {
$value = $this->normalizeValue($value);
$sections .= $key . ' = ' . $value . $this->linebreak;
}
}
}
}
$content .= $sections;
}
return $content;
}
/**
* converts string to a representable Config Bool Format
*
* @param string $value value
*
* @return string
* @throws Config_Lite_Exception_UnexpectedValue when format is unknown
*/
public function toBool($value)
{
if ($value === true) {
return 'yes';
}
return 'no';
}
/**
* returns a stripslashed string
*
* @param string $sec Section
* @param string $key Key
* @param mixed $default default return value
*
* @return string
* @throws Config_Lite_Exception_Runtime when config is empty
* and no default value is given
* @throws Config_Lite_Exception_UnexpectedValue key not found
* and no default value is given
*/
public function getString($sec, $key, $default = null)
{
if ((null === $this->sections) && (null === $default)) {
throw new Config_Lite_Exception_Runtime(
'configuration seems to be empty, no sections.'
);
}
if ((null === $sec) && array_key_exists($key, $this->sections)) {
return stripslashes($this->sections[$key]);
}
if (array_key_exists($key, $this->sections[$sec])) {
return stripslashes($this->sections[$sec][$key]);
}
if (null !== $default) {
return $default;
}
throw new Config_Lite_Exception_UnexpectedValue(
'key not found, no default value given.'
);
}
/**
* get an option by section, a global option or all sections and options
*
* to get an option by section, call get with a section and the option.
* To get a global option call `get' with null as section.
* Just call `get' without any parameters to get all sections and options.
* The third parameter is an optional default value to return,
* if the option is not set, this is practical when dealing with
* editable files, to keep an application stable with default settings.
*
* @param string $sec Section|null - null to get global option
* @param string $key Key
* @param mixed $default return default value if is $key is not set
*
* @return mixed
* @throws Config_Lite_Exception when config is empty
* and no default value is given
* @throws Config_Lite_Exception_UnexpectedValue key not found
* and no default value is given
*/
public function get($sec = null, $key = null, $default = null)
{
// handle get without parameters, because we can
if ((null === $sec) && (null === $key) && (null === $default)) {
return $this; // arrayaccess or $this->sections;
}
if ((null !== $sec) && array_key_exists($sec, $this->sections)
&& isset($this->sections[$sec][$key])
) {
return $this->sections[$sec][$key];
}
// global value
if ((null === $sec) && array_key_exists($key, $this->sections)) {
return $this->sections[$key];
}
// section
if ((null === $key) && array_key_exists($sec, $this->sections)) {
return $this->sections[$sec];
}
// all sections
if (null === $sec && array_key_exists($sec, $this->sections)) {
return $this->sections;
}
if (null !== $default) {
return $default;
}
throw new Config_Lite_Exception_UnexpectedValue(
'key not found, no default value given.'
);
}
/**
* returns a boolean for strict equality comparison
*
* returns "on", "yes", 1, "true" as TRUE
* and no given value or "off", "no", 0, "false" as FALSE
*
* @param string $sec Section
* @param string $key Key
* @param bool $default return default value if is $key is not set
*
* @return bool
* @throws Config_Lite_Exception_Runtime when the configuration is empty
* and no default value is given
* @throws Config_Lite_Exception_InvalidArgument when is not a boolean
* and no default array is given
* @throws Config_Lite_Exception_UnexpectedValue when key not found
* and no default array is given
*/
public function getBool($sec, $key, $default = null)
{
if ((null === $this->sections) && (null === $default)) {
throw new Config_Lite_Exception_Runtime(
'configuration seems to be empty (no sections),'
. 'and no default value given.'
);
}
if ((null === $sec)) {
if (array_key_exists($key, $this->sections)) {
if (empty($this->sections[$key])) {
return false;
}
$value = strtolower($this->sections[$key]);
if (!in_array($value, $this->_booleans) && (null === $default)) {
throw new Config_Lite_Exception_InvalidArgument(
sprintf(
'Not a boolean: %s, and no default value given.',
$value
)
);
} else {
return $this->_booleans[$value];
}
}
}
if (array_key_exists($key, $this->sections[$sec])) {
if (empty($this->sections[$sec][$key])) {
return false;
}
$value = strtolower($this->sections[$sec][$key]);
if (!in_array($value, $this->_booleans) && (null === $default)) {
throw new Config_Lite_Exception_InvalidArgument(
sprintf(
'Not a boolean: %s, and no default value given.',
$value
)
);
} else {
return $this->_booleans[$value];
}
}
if (null !== $default) {
return $default;
}
throw new Config_Lite_Exception_UnexpectedValue(
'option not found, no default value given.'
);
}
/**
* returns an array of options of the given section
*
* @param string $sec Section
* @param array $default return default array if $sec is not set
*
* @return array
* @throws Config_Lite_Exception_Runtime when config is empty
* and no default array is given
* @throws Config_Lite_Exception_UnexpectedValue when key not found
* and no default array is given
*/
public function getSection($sec, $default = null)
{
if ((null === $this->sections) && (null === $default)) {
throw new Config_Lite_Exception_Runtime(
'configuration seems to be empty, no sections.'
);
}
if (isset($this->sections[$sec])) {
return $this->sections[$sec];
}
if ((null !== $default) && is_array($default)) {
return $default;
}
throw new Config_Lite_Exception_UnexpectedValue(
'section not found, no default array given.'
);
}
/**
* returns true if the given section exists, otherwise false
*
* @param string $sec Section
*
* @return bool
*/
public function hasSection($sec)
{
if (isset($this->sections[$sec]) && is_array($this->sections[$sec])) {
return true;
}
return false;
}
/**
* tests if a section or an option of a section exists
*
* @param string $sec Section
* @param string $key Key
*
* @return bool
*/
public function has($sec, $key=null)
{
if (!$this->hasSection($sec)) {
return false;
}
if ((null !== $key) && isset($this->sections[$sec][$key])) {
return true;
}
return false;
}
/**
* remove a section or an option of a section
*
* @param string $sec Section
* @param string $key Key
*
* @return void
* @throws Config_Lite_Exception_UnexpectedValue when given Section not exists
*/
public function remove($sec, $key=null)
{
if (null === $key) {
$this->removeSection($sec);
return;
}
// global value
if (null === $sec && $key !== null) {
if (!isset($this->sections[$key])) {
throw new Config_Lite_Exception_UnexpectedValue(
'No such global Value.'
);
return;
}
unset($this->sections[$key]);
return;
}
if (!isset($this->sections[$sec])) {
throw new Config_Lite_Exception_UnexpectedValue('No such Section.');
}
unset($this->sections[$sec][$key]);
}
/**
* remove section by name
*
* @param string $sec Section
*
* @return void
* @throws Config_Lite_Exception_UnexpectedValue when given Section not exists
*/
public function removeSection($sec)
{
if (!isset($this->sections[$sec])) {
throw new Config_Lite_Exception_UnexpectedValue('No such Section.');
}
unset($this->sections[$sec]);
}
/**
* removes all sections and global options
*
* @return void
*/
public function clear()
{
$this->sections = array();
}
/**
* like set, but adds slashes to the value
*
* creates new section if necessary and overrides existing keys.
*
* @param string $sec Section
* @param string $key Key
* @param mixed $value Value
*
* @return $this
* @throws Config_Lite_Exception_InvalidArgument when given key is an array
*/
public function setString($sec, $key, $value = null)
{
if (null !== $value) {
$value = addslashes($value);
}
$this->set($sec, $key, $value);
return $this;
}
/**
* to add key/value pairs
*
* creates new section if necessary and overrides existing keys.
* To set a global, "sectionless" value, call set with null as section.
*
* @param string $sec Section
* @param string $key Key
* @param mixed $value Value
*
* @throws Config_Lite_Exception when given key is an array
* @return $this
*/
public function set($sec, $key, $value = null)
{
if (!is_array($this->sections)) {
$this->sections = array();
}
if (is_array($key) || is_array($sec)) {
throw new Config_Lite_Exception_InvalidArgument(
'string key expected, but array given.'
);
}
if (null === $sec) {
$this->sections[$key] = $value;
} else {
$this->sections[$sec][$key] = $value;
}
return $this;
}
/**
* set a given array with key/value pairs to a section,
* creates a new section if necessary.
*
* @param string $sec Section
* @param array $pairs Keys and Values as Array ('key' => 'value')
*
* @throws Config_Lite_Exception_InvalidArgument array $pairs expected
* @return $this
*/
public function setSection($sec, $pairs)
{
if (!is_array($this->sections)) {
$this->sections = array();
}
if (!is_array($pairs)) {
throw new Config_Lite_Exception_InvalidArgument('array expected.');
}
$this->sections[$sec] = $pairs;
return $this;
}
/**
* filename to read or save
*
* the full filename with suffix, ie. `[PATH/]<ApplicationName>.ini'.
* you can also set the filename as parameter to the constructor.
*
* @param string $filename Filename
*
* @return $this
*/
public function setFilename($filename)
{
$this->filename = $filename;
return $this;
}
/**
* returns the current filename
*
* @return string
*/
public function getFilename()
{
return $this->filename;
}
/**
* set the line break (newline) chars
*
* line-break defaults to Unix Newline "\n",
* set to support other linebreaks, eg. windows user
* textfiles "\r\n"
*
* @param string $linebreakchars chars
*
* @return $this
*/
public function setLinebreak($linebreakchars)
{
$this->linebreak = $linebreakchars;
return $this;
}
/**
* Sets whether or not sections should be processed
*
* If true, values for each section will be placed into
* a sub-array for the section. If false, all values will
* be placed in the global scope.
*
* @param bool $processSections - if true, sections will be processed
*
* @return $this
*/
public function setProcessSections($processSections)
{
$this->processSections = $processSections;
return $this;
}
/**
* Sets whether or not to doubleQuote
*
* If true, everything but bool and numeric
* values get doublequoted.
*
* @param bool $quoteStrings - if true, Strings get doubleQuoted
*
* @return $this
*/
public function setQuoteStrings($quoteStrings)
{
$this->quoteStrings = $quoteStrings;
return $this;
}
/**
* text presentation of the config object
*
* since a empty config is valid,
* it would return a empty string in that case.
*
* @throws Config_Lite_Exception_Runtime
* @return string
*/
public function __toString()
{
return $this->buildOutputString($this->sections);
}
/**
* implemented for interface ArrayAccess
*
* @param string $offset section, implemented by ArrayAccess
* @param mixed $value KVP, implemented by ArrayAccess
*
* @return void
*/
public function offsetSet($offset, $value)
{
$this->sections[$offset] = $value;
}
/**
* implemented for interface ArrayAccess
*
* @param string $offset - section, implemented by ArrayAccess
*
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->sections[$offset]);
}
/**
* implemented for interface ArrayAccess
*
* @param string $offset - section, implemented by ArrayAccess
*
* @return void
*/
public function offsetUnset($offset)
{
unset($this->sections[$offset]);
}
/**
* implemented for interface ArrayAccess
*
* @param string $offset - section, implemented by ArrayAccess
*
* @return mixed
*/
public function offsetGet($offset)
{
if (array_key_exists($offset, $this->sections)) {
return $this->sections[$offset];
}
return null;
}
/**
* implemented for interface IteratorAggregate
*
* @see http://www.php.net/~helly/php/ext/spl/interfaceIterator.html
* @return Iterator
*/
public function getIterator()
{
return new ArrayIterator($this->sections);
}
/**
* implemented for interface Countable
*
* @see http://php.net.countable
* @return int
*/
public function count()
{
return count($this->sections);
}
/**
* implemented for interface Serializable
*
* @see http://php.net/manual/en/class.serializable.php
* @return int
*/
public function serialize()
{
return serialize($this->sections);
}
/**
* implemented for interface Serializable
*
* @param string $serializedData for instance
*
* @return void
*/
public function unserialize($serializedData)
{
$sections = unserialize($serializedData);
$this->sections = $sections;
}
/**
* takes an optional filename, if the file exists, also reads it.
*
* the `save' and `read' methods relies on a setted filename,
* but you can also use `setFilename' to set the filename.
*
* @param string $filename - "INI Style" Text Config File
*/
public function __construct($filename = null)
{
$this->sections = array();
if (null !== $filename) {
$this->setFilename($filename);
if (file_exists($filename)) {
$this->read($filename);
}
}
}
}

View File

@ -0,0 +1,34 @@
<?php
/**
* Config_Lite_Exception (Config/Lite/Exception.php)
*
* PHP version 5
*
* @file Config/Lite/Exception.php
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version SVN: $Id$
* @link https://github.com/pce/config_lite
*/
/**
* Config_Lite_Exception
*
* Interface implemented by Exceptions
*
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: 0.1.5
* @link https://github.com/pce/config_lite
*/
interface Config_Lite_Exception
{
}

View File

@ -0,0 +1,35 @@
<?php
/**
* Config_Lite_Exception_InvalidArgument (Config/Lite/Exception/InvalidArgument.php)
*
* PHP version 5
*
* @file Config/Lite/Exception/InvalidArgument.php
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version SVN: $Id$
* @link https://github.com/pce/config_lite
*/
/**
* Config_Lite_Exception_InvalidArgument
*
* implements Config_Lite_Exception
*
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: 0.1.5
* @link https://github.com/pce/config_lite
*/
class Config_Lite_Exception_InvalidArgument
extends RuntimeException
implements Config_Lite_Exception
{
}

View File

@ -0,0 +1,36 @@
<?php
/**
* Config_Lite_Exception_Runtime (Config/Lite/Exception/Runtime.php)
*
* PHP version 5
*
* @file Config/Lite/Exception/Runtime.php
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version SVN: $Id$
* @link https://github.com/pce/config_lite
*/
/**
* Config_Lite_Exception_Runtime
*
* implements Config_Lite_Exception
*
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: 0.1.5
* @link https://github.com/pce/config_lite
*/
class Config_Lite_Exception_Runtime
extends RuntimeException
implements Config_Lite_Exception
{
}

View File

@ -0,0 +1,36 @@
<?php
/**
* Config_Lite_Exception_UnexpectedValue (Config/Lite/Exception/UnexpectedValue.php)
*
* PHP version 5
*
* @file Config/Lite/Exception/UnexpectedValue.php
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version SVN: $Id$
* @link https://github.com/pce/config_lite
*/
/**
* Config_Lite_Exception_UnexpectedValue
*
* implements Config_Lite_Exception
*
* @category Configuration
* @package Config_Lite
* @author Patrick C. Engel <pce@php.net>
* @copyright 2010-2011 <pce@php.net>
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: 0.1.5
* @link https://github.com/pce/config_lite
*/
class Config_Lite_Exception_UnexpectedValue
extends UnexpectedValueException
implements Config_Lite_Exception
{
}

View File

@ -0,0 +1,38 @@
<?php
namespace FeedWriter;
/*
* Copyright (C) 2012 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* 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/>.
*/
/**
* Wrapper for creating ATOM feeds
*
* @package UniversalFeedWriter
*/
class Atom extends Feed
{
/**
* {@inheritdoc}
*/
function __construct()
{
parent::__construct(Feed::ATOM);
}
}

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

View File

@ -0,0 +1,869 @@
<?php
namespace FeedWriter;
use \DateTime;
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
* Copyright (C) 2010-2013 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* 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/>.
*/
// RSS 0.90 Officially obsoleted by 1.0
// RSS 0.91, 0.92, 0.93 and 0.94 Officially obsoleted by 2.0
// So, define constants for RSS 1.0, RSS 2.0 and ATOM
/**
* Universal Feed Writer class
*
* Generate RSS 1.0, RSS2.0 and ATOM Feeds
*
* @package UniversalFeedWriter
* @author Anis uddin Ahmad <anisniit@gmail.com>
* @link http://www.ajaxray.com/projects/rss
*/
abstract class Feed
{
const RSS1 = 'RSS 1.0';
const RSS2 = 'RSS 2.0';
const ATOM = 'ATOM';
/**
* Collection of all channel elements
*/
private $channels = array();
/**
* Collection of items as object of \FeedWriter\Item class.
*/
private $items = array();
/**
* Store some other version wise data
*/
private $data = array();
/**
* The tag names which have to encoded as CDATA
*/
private $CDATAEncoding = array();
/**
* Collection of XML namespaces
*/
private $namespaces = array();
/**
* Contains the format of this feed.
*/
private $version = null;
/**
* Constructor
*
* If no version is given, a feed in RSS 2.0 format will be generated.
*
* @param constant the version constant (RSS1/RSS2/ATOM).
*/
protected function __construct($version = FeedWriter::RSS2)
{
$this->version = $version;
// Setting default encoding
$this->encoding = 'utf-8';
// Setting default value for essential channel elements
$this->channels['title'] = $version . ' Feed';
$this->channels['link'] = 'http://www.ajaxray.com/blog';
// Add some default XML namespaces
$this->namespaces['content'] = 'http://purl.org/rss/1.0/modules/content/';
$this->namespaces['wfw'] = 'http://wellformedweb.org/CommentAPI/';
$this->namespaces['atom'] = 'http://www.w3.org/2005/Atom';
$this->namespaces['rdf'] = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#';
$this->namespaces['rss1'] = 'http://purl.org/rss/1.0/';
$this->namespaces['dc'] = 'http://purl.org/dc/elements/1.1/';
$this->namespaces['sy'] = 'http://purl.org/rss/1.0/modules/syndication/';
//Tag names to encode in CDATA
$this->CDATAEncoding = array('description', 'content:encoded', 'summary');
}
// Start # public functions ---------------------------------------------
/**
* Adds a channel element indicating the program used to generate the feed.
*
* @return void
*/
public function addGenerator()
{
if ($this->version == Feed::ATOM)
$this->setChannelElement('atom:generator', 'FeedWriter', array('uri' => 'https://github.com/mibe/FeedWriter'));
else if ($this->version == Feed::RSS2)
$this->setChannelElement('generator', 'FeedWriter');
else
die('The generator element is not supported in RSS1 feeds.');
return $this;
}
/**
* Add a XML namespace to the internal list of namespaces. After that,
* custom channel elements can be used properly to generate a valid feed.
*
* @access public
* @param string namespace prefix
* @param string namespace name (URI)
* @return void
* @link http://www.w3.org/TR/REC-xml-names/
*/
public function addNamespace($prefix, $uri)
{
$this->namespaces[$prefix] = $uri;
return $this;
}
/**
* Add a channel element to the feed.
*
* @access public
* @param string name of the channel tag
* @param string content of the channel tag
* @param bool TRUE if this element can appear multiple times
* @return void
*/
public function setChannelElement($elementName, $content, $multiple = false)
{
if ($multiple === TRUE)
$this->channels[$elementName][] = $content;
else
$this->channels[$elementName] = $content;
return $this;
}
/**
* Set multiple channel elements from an array. Array elements
* should be 'channelName' => 'channelContent' format.
*
* @access public
* @param array array of channels
* @return void
*/
public function setChannelElementsFromArray($elementArray)
{
if (!is_array($elementArray))
return;
foreach ($elementArray as $elementName => $content)
{
$this->setChannelElement($elementName, $content);
}
return $this;
}
/**
* Get the appropriate MIME type string for the current feed.
*
* @access public
* @return string
*/
public function getMIMEType()
{
switch($this->version)
{
case Feed::RSS2 : $mimeType = "application/rss+xml";
break;
case Feed::RSS1 : $mimeType = "application/rdf+xml";
break;
case Feed::ATOM : $mimeType = "application/atom+xml";
break;
default : $mimeType = "text/xml";
}
return $mimeType;
}
/**
* Print the actual RSS/ATOM file
*
* Sets a Content-Type header and echoes the contents of the feed.
* Should only be used in situations where direct output is desired;
* if you need to pass a string around, use generateFeed() instead.
*
* @access public
* @param bool FALSE if the specific feed media type should be sent.
* @return void
*/
public function printFeed($useGenericContentType = false)
{
$contentType = "text/xml";
if (!$useGenericContentType)
{
$contentType = $this->getMIMEType();
}
header("Content-Type: " . $contentType);
echo $this->generateFeed();
}
/**
* Generate the feed.
*
* @access public
* @return string
*/
public function generateFeed()
{
return $this->makeHeader()
. $this->makeChannels()
. $this->makeItems()
. $this->makeFooter();
}
/**
* Create a new Item.
*
* @access public
* @return object instance of Item class
*/
public function createNewItem()
{
$Item = new Item($this->version);
return $Item;
}
/**
* Add a FeedItem to the main class
*
* @access public
* @param Item instance of Item class
* @return void
*/
public function addItem(Item $feedItem)
{
if ($feedItem->getVersion() != $this->version)
die('Feed type mismatch: This instance can handle ' . $this->version . ' feeds only, but item with type ' . $feedItem->getVersion() . ' given.');
$this->items[] = $feedItem;
return $this;
}
// Wrapper functions -------------------------------------------------------------------
/** Set the 'encoding' feed attribute
* @access public
* @param string value of 'encoding' feed attribute
* @return void
*/
public function setEncoding($encoding)
{
$this->encoding = $encoding;
return $this;
}
/**
* Set the 'title' channel element
*
* @access public
* @param string value of 'title' channel tag
* @return void
*/
public function setTitle($title)
{
return $this->setChannelElement('title', $title);
}
/**
* Set the date when the ATOM feed was lastly updated.
*
* This adds the 'updated' element to the feed. The value of the date parameter
* can be either an instance of the DateTime class, an integer containing a UNIX
* timestamp or a string which is parseable by PHP's 'strtotime' function.
*
* Not supported in RSS1 feeds.
*
* @access public
* @param DateTime|int|string Date which should be used.
* @return void
*/
public function setDate($date)
{
if ($this->version == Feed::RSS1)
die('The publication date is not supported in RSS1 feeds.');
// The feeds have different date formats.
$format = $this->version == Feed::ATOM ? \DATE_ATOM : \DATE_RSS;
if ($date instanceof DateTime)
$date = $date->format($format);
else if(is_numeric($date) && $date >= 0)
$date = date($format, $date);
else if (is_string($date))
$date = date($format, strtotime($date));
else
die('The given date was not an instance of DateTime, a UNIX timestamp or a date string.');
if ($this->version == Feed::ATOM)
$this->setChannelElement('updated', $date);
else
$this->setChannelElement('lastBuildDate', $date);
return $this;
}
/**
* Set the 'description' channel element
*
* @access public
* @param string value of 'description' channel tag
* @return void
*/
public function setDescription($description)
{
if ($this->version != Feed::ATOM)
$this->setChannelElement('description', $description);
return $this;
}
/**
* Set the 'link' channel element
*
* @access public
* @param string value of 'link' channel tag
* @return void
*/
public function setLink($link)
{
return $this->setChannelElement('link', $link);
}
/**
* Set custom 'link' channel elements.
*
* In ATOM feeds, only one link with alternate relation and the same combination of
* type and hreflang values.
*
* @access public
* @param string URI of this link
* @param string relation type of the resource
* @param string media type of the target resource
* @param string language of the resource
* @param string human-readable information about the resource
* @param int length of the resource in bytes
* @link https://www.iana.org/assignments/link-relations/link-relations.xml
* @link https://tools.ietf.org/html/rfc4287#section-4.1.1
*/
public function setAtomLink($href, $rel = null, $type = null, $hreflang = null, $title = null, $length = null)
{
$data = array('href' => $href);
if ($rel != null)
{
if (!is_string($rel) || empty($rel))
die('rel parameter must be a string and a valid relation identifier.');
$data['rel'] = $rel;
}
if ($type != null)
{
// Regex used from RFC 4287, page 41
if (!is_string($type) || preg_match('/.+\/.+/', $type) != 1)
die('type parameter must be a string and a MIME type.');
$data['type'] = $type;
}
if ($hreflang != null)
{
// Regex used from RFC 4287, page 41
if (!is_string($hreflang) || preg_match('/[A-Za-z]{1,8}(-[A-Za-z0-9]{1,8})*/', $hreflang) != 1)
die('hreflang parameter must be a string and a valid language code.');
$data['hreflang'] = $hreflang;
}
if ($title != null)
{
if (!is_string($title) || empty($title))
die('title parameter must be a string and not empty.');
$data['title'] = $title;
}
if ($length != null)
{
if (!is_int($length) || $length < 0)
die('length parameter must be a positive integer.');
$data['length'] = (string)$length;
}
// ATOM spec. has some restrictions on atom:link usage
// See RFC 4287, page 12 (4.1.1)
if ($this->version == Feed::ATOM)
{
foreach($this->channels as $key => $value)
{
if ($key != 'atom:link')
continue;
// $value is an array , so check every element
foreach($value as $linkItem)
{
// Only one link with relation alternate and same hreflang & type is allowed.
if (@$linkItem['rel'] == 'alternate' && @$linkItem['hreflang'] == $hreflang && @$linkItem['type'] == $type)
die('The feed must not contain more than one link element with a relation of "alternate"'
. ' that has the same combination of type and hreflang attribute values.');
}
}
}
return $this->setChannelElement('atom:link', $data, true);
}
/**
* Set an 'atom:link' channel element with relation=self attribute.
* Needs the full URL to this feed.
*
* @link http://www.rssboard.org/rss-profile#namespace-elements-atom-link
* @access public
* @param string URL to this feed
* @return void
*/
public function setSelfLink($url)
{
return $this->setAtomLink($url, 'self', $this->getMIMEType());
}
/**
* Set the 'image' channel element
*
* @access public
* @param string title of image
* @param string link url of the image
* @param string path url of the image
* @return void
*/
public function setImage($title, $link, $url)
{
return $this->setChannelElement('image', array('title'=>$title, 'link'=>$link, 'url'=>$url));
}
/**
* Set the 'about' channel element. Only for RSS 1.0
*
* @access public
* @param string value of 'about' channel tag
* @return void
*/
public function setChannelAbout($url)
{
$this->data['ChannelAbout'] = $url;
return $this;
}
/**
* Generate an UUID.
*
* The UUID is based on an MD5 hash. If no key is given, a unique ID as the input
* for the MD5 hash is generated.
*
* @author Anis uddin Ahmad <admin@ajaxray.com>
* @param string optional key on which the UUID is generated
* @param string an optional prefix
* @return string the formated UUID
*/
public static function uuid($key = null, $prefix = '')
{
$key = ($key == null) ? uniqid(rand()) : $key;
$chars = md5($key);
$uuid = substr($chars,0,8) . '-';
$uuid .= substr($chars,8,4) . '-';
$uuid .= substr($chars,12,4) . '-';
$uuid .= substr($chars,16,4) . '-';
$uuid .= substr($chars,20,12);
return $prefix . $uuid;
}
// End # public functions ----------------------------------------------
// Start # private functions ----------------------------------------------
/**
* Returns all used XML namespace prefixes in this instance.
* This includes all channel elements and feed items.
* Unfortunately some namespace prefixes are not included,
* because they are hardcoded, e.g. rdf.
*
* @access private
* @return array Array with namespace prefix as value.
*/
private function getNamespacePrefixes()
{
$prefixes = array();
// Get all tag names from channel elements...
$tags = array_keys($this->channels);
// ... and now all names from feed items
foreach ($this->items as $item)
$tags = array_merge($tags, array_keys($item->getElements()));
// Look for prefixes in those tag names
foreach($tags as $tag)
{
$elements = explode(':', $tag);
if (count($elements) != 2)
continue;
$prefixes[] = $elements[0];
}
return array_unique($prefixes);
}
/**
* Returns the XML header and root element, depending on the feed type.
*
* @access private
* @return void
*/
private function makeHeader()
{
$out = '<?xml version="1.0" encoding="'.$this->encoding.'" ?>' . PHP_EOL;
$prefixes = $this->getNamespacePrefixes();
$attributes = array();
$tagName = '';
$defaultNamespace = '';
if($this->version == Feed::RSS2)
{
$tagName = 'rss';
$attributes['version'] = '2.0';
}
elseif($this->version == Feed::RSS1)
{
$tagName = 'rdf:RDF';
$prefixes[] = 'rdf';
$defaultNamespace = $this->namespaces['rss1'];
}
else if($this->version == Feed::ATOM)
{
$tagName = 'feed';
$defaultNamespace = $this->namespaces['atom'];
// Ugly hack to remove the 'atom' value from the prefixes array.
$prefixes = array_flip($prefixes);
unset($prefixes['atom']);
$prefixes = array_flip($prefixes);
}
// Iterate through every namespace prefix and add it to the element attributes.
foreach($prefixes as $prefix)
{
if (!isset($this->namespaces[$prefix]))
die('Unknown XML namespace prefix: \'' . $prefix . '\'. Use the addNamespace method to add support for this prefix.');
else
$attributes['xmlns:' . $prefix] = $this->namespaces[$prefix];
}
// Include default namepsace, if required
if (!empty($defaultNamespace))
$attributes['xmlns'] = $defaultNamespace;
$out .= $this->makeNode($tagName, '', $attributes, true);
return $out;
}
/**
* Closes the open tags at the end of file
*
* @access private
* @return void
*/
private function makeFooter()
{
if($this->version == Feed::RSS2)
{
return '</channel>' . PHP_EOL . '</rss>';
}
elseif($this->version == Feed::RSS1)
{
return '</rdf:RDF>';
}
else if($this->version == Feed::ATOM)
{
return '</feed>';
}
}
/**
* Creates a single node in XML format
*
* @access private
* @param string name of the tag
* @param mixed tag value as string or array of nested tags in 'tagName' => 'tagValue' format
* @param array Attributes (if any) in 'attrName' => 'attrValue' format
* @param string True if the end tag should be omitted. Defaults to false.
* @return string formatted xml tag
*/
private function makeNode($tagName, $tagContent, $attributes = null, $omitEndTag = false)
{
$nodeText = '';
$attrText = '';
if(is_array($attributes) && count($attributes) > 0)
{
foreach ($attributes as $key => $value)
{
$value = htmlspecialchars($value);
$attrText .= " $key=\"$value\"";
}
}
if(is_array($tagContent) && $this->version == Feed::RSS1)
{
$attrText = ' rdf:parseType="Resource"';
}
$attrText .= (in_array($tagName, $this->CDATAEncoding) && $this->version == Feed::ATOM) ? ' type="html"' : '';
$nodeText .= "<{$tagName}{$attrText}>";
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? '<![CDATA[' : '';
if(is_array($tagContent))
{
foreach ($tagContent as $key => $value)
{
$nodeText .= $this->makeNode($key, $value);
}
}
else
{
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? $this->sanitizeCDATA($tagContent) : htmlspecialchars($tagContent);
}
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? ']]>' : '';
if (!$omitEndTag)
$nodeText .= "</$tagName>";
$nodeText .= PHP_EOL;
return $nodeText;
}
/**
* Make the channels.
*
* @access private
* @return void
*/
private function makeChannels()
{
$out = '';
//Start channel tag
switch ($this->version)
{
case Feed::RSS2:
$out .= '<channel>' . PHP_EOL;
break;
case Feed::RSS1:
$out .= (isset($this->data['ChannelAbout']))? "<channel rdf:about=\"{$this->data['ChannelAbout']}\">" : "<channel rdf:about=\"{$this->channels['link']}\">";
break;
}
//Print Items of channel
foreach ($this->channels as $key => $value)
{
// ATOM feed needs some special handling
if ($this->version == Feed::ATOM)
{
// Strip all ATOM namespace prefixes from tags. Not needed here, because the ATOM namespace name is
// used as default namespace.
if (strncmp($key, 'atom', 4) == 0)
$key = substr($key, 5);
if ($key == 'link')
{
if (is_array($value))
{
// $value is an array containing multiple atom:link element attributes
foreach($value as $attributes)
{
// $attributes contains actually the node attributes, not the value.
$out .= $this->makeNode($key, '', $attributes);
}
}
else
{
// ATOM prints link element as href attribute
$out .= $this->makeNode($key, '', array('href' => $value));
//Add the id for ATOM
$out .= $this->makeNode('id', Feed::uuid($value, 'urn:uuid:'));
}
}
else
$out .= $this->makeNode($key, $value);
}
else
{
if ($key == 'atom:link')
{
// $value is an array containing multiple atom:link element attributes
foreach($value as $attributes)
{
// $attributes contains actually the node attributes, not the value.
$out .= $this->makeNode($key, '', $attributes);
}
}
else
{
$out .= $this->makeNode($key, $value);
}
}
}
//RSS 1.0 have special tag <rdf:Seq> with channel
if($this->version == Feed::RSS1)
{
$out .= "<items>" . PHP_EOL . "<rdf:Seq>" . PHP_EOL;
foreach ($this->items as $item)
{
$thisItems = $item->getElements();
$out .= "<rdf:li resource=\"{$thisItems['link']['content']}\"/>" . PHP_EOL;
}
$out .= "</rdf:Seq>" . PHP_EOL . "</items>" . PHP_EOL . "</channel>" . PHP_EOL;
}
return $out;
}
/**
* Prints formatted feed items
*
* @access private
* @return void
*/
private function makeItems()
{
$out = '';
foreach ($this->items as $item)
{
$thisItems = $item->getElements();
// the argument is printed as rdf:about attribute of item in rss 1.0
$out .= $this->startItem($thisItems['link']['content']);
foreach ($thisItems as $feedItem)
{
$name = $feedItem['name'];
// Strip all ATOM namespace prefixes from tags when feed is an ATOM feed.
// Not needed here, because the ATOM namespace name is used as default namespace.
if ($this->version == Feed::ATOM && strncmp($name, 'atom', 4) == 0)
$name = substr($name, 5);
$out .= $this->makeNode($name, $feedItem['content'], $feedItem['attributes']);
}
$out .= $this->endItem();
}
return $out;
}
/**
* Make the starting tag of channels
*
* @access private
* @param string The vale of about tag which is used for RSS 1.0 only.
* @return void
*/
private function startItem($about = false)
{
$out = '';
if($this->version == Feed::RSS2)
{
$out .= '<item>' . PHP_EOL;
}
else if($this->version == Feed::RSS1)
{
if($about)
{
$out .= "<item rdf:about=\"$about\">" . PHP_EOL;
}
else
{
throw new Exception("link element is not set - It's required for RSS 1.0 to be used as the about attribute of the item tag.");
}
}
else if($this->version == Feed::ATOM)
{
$out .= "<entry>" . PHP_EOL;
}
return $out;
}
/**
* Closes feed item tag
*
* @access private
* @return void
*/
private function endItem()
{
if($this->version == Feed::RSS2 || $this->version == Feed::RSS1)
{
return '</item>' . PHP_EOL;
}
else if($this->version == Feed::ATOM)
{
return '</entry>' . PHP_EOL;
}
}
/**
* Sanitizes data which will be later on returned as CDATA in the feed.
*
* A "]]>" respectively "<![CDATA" in the data would break the CDATA in the
* XML, so the brackets are converted to a HTML entity.
*
* @access private
* @param string Data to be sanitized
* @return string Sanitized data
*/
private function sanitizeCDATA($text)
{
$text = str_replace("]]>", "]]&gt;", $text);
$text = str_replace("<![CDATA[", "&lt;![CDATA[", $text);
return $text;
}
// End # private functions ----------------------------------------------
} // end of class Feed

View File

@ -0,0 +1,392 @@
<?php
namespace FeedWriter;
use \DateTime;
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
* Copyright (C) 2010-2013 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* 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/>.
*/
/**
* Universal Feed Writer
*
* Item class - Used as feed element in Feed class
*
* @package UniversalFeedWriter
* @author Anis uddin Ahmad <anisniit@gmail.com>
* @link http://www.ajaxray.com/projects/rss
*/
class Item
{
/**
* Collection of feed item elements
*/
private $elements = array();
/**
* Contains the format of this feed.
*/
private $version;
/**
* Is used as a suffix when multiple elements have the same name.
**/
private $_cpt = 0;
/**
* Constructor
*
* @param constant (RSS1/RSS2/ATOM) RSS2 is default.
*/
function __construct($version = Feed::RSS2)
{
$this->version = $version;
}
/**
* Return an unique number
* @access private
* @return int
**/
private function cpt() {
return $this->_cpt++;
}
/**
* Add an element to elements array
*
* @access public
* @param string The tag name of an element
* @param string The content of tag
* @param array Attributes(if any) in 'attrName' => 'attrValue' format
* @param boolean Specifies if an already existing element is overwritten.
* @param boolean Specifies if multiple elements of the same name are allowed.
* @return void
*/
public function addElement($elementName, $content, $attributes = null, $overwrite = FALSE, $allowMultiple = FALSE)
{
$key = $elementName;
// return if element already exists & if overwriting is disabled
// & if multiple elements are not allowed.
if (isset($this->elements[$elementName]) && !$overwrite) {
if (!$allowMultiple)
return;
$key .= '-' . $this->cpt();
}
$this->elements[$key]['name'] = $elementName;
$this->elements[$key]['content'] = $content;
$this->elements[$key]['attributes'] = $attributes;
return $this;
}
/**
* Set multiple feed elements from an array.
* Elements which have attributes cannot be added by this method
*
* @access public
* @param array array of elements in 'tagName' => 'tagContent' format.
* @return void
*/
public function addElementArray($elementArray)
{
if (!is_array($elementArray))
return;
foreach ($elementArray as $elementName => $content)
{
$this->addElement($elementName, $content);
}
return $this;
}
/**
* Return the collection of elements in this feed item
*
* @access public
* @return array
*/
public function getElements()
{
return $this->elements;
}
/**
* Return the type of this feed item
*
* @access public
* @return string The feed type, as defined in Feed.php
*/
public function getVersion()
{
return $this->version;
}
// Wrapper functions ------------------------------------------------------
/**
* Set the 'description' element of feed item
*
* @access public
* @param string The content of 'description' or 'summary' element
* @return void
*/
public function setDescription($description)
{
$tag = ($this->version == Feed::ATOM) ? 'summary' : 'description';
return $this->addElement($tag, $description);
}
/**
* Set the 'content' element of the feed item
* For ATOM feeds only
*
* @access public
* @param string Content for the item (i.e., the body of a blog post).
* @return void
*/
public function setContent($content)
{
if ($this->version != Feed::ATOM)
die('The content element is supported in ATOM feeds only.');
return $this->addElement('content', $content, array('type' => 'html'));
}
/**
* Set the 'title' element of feed item
*
* @access public
* @param string The content of 'title' element
* @return void
*/
public function setTitle($title)
{
return $this->addElement('title', $title);
}
/**
* Set the 'date' element of the feed item.
*
* The value of the date parameter can be either an instance of the
* DateTime class, an integer containing a UNIX timestamp or a string
* which is parseable by PHP's 'strtotime' function.
*
* @access public
* @param DateTime|int|string Date which should be used.
* @return void
*/
public function setDate($date)
{
if(!is_numeric($date))
{
if ($date instanceof DateTime)
$date = $date->getTimestamp();
else
{
$date = strtotime($date);
if ($date === FALSE)
die('The given date string was not parseable.');
}
}
else if ($date < 0)
die('The given date is not an UNIX timestamp.');
if($this->version == Feed::ATOM)
{
$tag = 'updated';
$value = date(\DATE_ATOM, $date);
}
elseif($this->version == Feed::RSS2)
{
$tag = 'pubDate';
$value = date(\DATE_RSS, $date);
}
else
{
$tag = 'dc:date';
$value = date("Y-m-d", $date);
}
return $this->addElement($tag, $value);
}
/**
* Set the 'link' element of feed item
*
* @access public
* @param string The content of 'link' element
* @return void
*/
public function setLink($link)
{
if($this->version == Feed::RSS2 || $this->version == Feed::RSS1)
{
$this->addElement('link', $link);
}
else
{
$this->addElement('link','',array('href'=>$link));
$this->addElement('id', Feed::uuid($link,'urn:uuid:'));
}
return $this;
}
/**
* Attach a external media to the feed item.
* Not supported in RSS 1.0 feeds.
*
* See RFC 4288 for syntactical correct MIME types.
*
* Note that you should avoid the use of more than one enclosure in one item,
* since some RSS aggregators don't support it.
*
* @access public
* @param string The URL of the media.
* @param integer The length of the media.
* @param string The MIME type attribute of the media.
* @param boolean Specifies, if multiple enclosures are allowed
* @return void
* @link https://tools.ietf.org/html/rfc4288
*/
public function addEnclosure($url, $length, $type, $multiple = TRUE)
{
if ($this->version == Feed::RSS1)
die('Media attachment is not supported in RSS1 feeds.');
// the length parameter should be set to 0 if it can't be determined
// see http://www.rssboard.org/rss-profile#element-channel-item-enclosure
if (!is_numeric($length) || $length < 0)
die('The length parameter must be an integer and greater or equals to zero.');
// Regex used from RFC 4287, page 41
if (!is_string($type) || preg_match('/.+\/.+/', $type) != 1)
die('type parameter must be a string and a MIME type.');
$attributes = array('length' => $length, 'type' => $type);
if ($this->version == Feed::RSS2)
{
$attributes['url'] = $url;
$this->addElement('enclosure', '', $attributes, FALSE, $multiple);
}
else
{
$attributes['href'] = $url;
$attributes['rel'] = 'enclosure';
$this->addElement('atom:link', '', $attributes, FALSE, $multiple);
}
return $this;
}
/**
* Alias of addEnclosure, for backward compatibility. Using only this
* method ensure that the 'enclosure' element will be present only once.
*
* @access public
* @param string The URL of the media.
* @param integer The length of the media.
* @param string The MIME type attribute of the media.
* @return void
* @link https://tools.ietf.org/html/rfc4288
*
**/
public function setEnclosure($url, $length, $type) {
return $this->addEnclosure($url, $length, $type, false);
}
/**
* Set the 'author' element of feed item.
* Not supported in RSS 1.0 feeds.
*
* @access public
* @param string The author of this item
* @param string Optional email address of the author
* @param string Optional URI related to the author
* @return void
*/
public function setAuthor($author, $email = null, $uri = null)
{
switch($this->version)
{
case Feed::RSS1: die('The author element is not supported in RSS1 feeds.');
break;
case Feed::RSS2:
if ($email != null)
$author = $email . ' (' . $author . ')';
$this->addElement('author', $author);
break;
case Feed::ATOM:
$elements = array('name' => $author);
// Regex from RFC 4287 page 41
if ($email != null && preg_match('/.+@.+/', $email) == 1)
$elements['email'] = $email;
if ($uri != null)
$elements['uri'] = $uri;
$this->addElement('author', $elements);
break;
}
return $this;
}
/**
* Set the unique identifier of the feed item
*
* @access public
* @param string The unique identifier of this item
* @param boolean The value of the 'isPermaLink' attribute in RSS 2 feeds.
* @return void
*/
public function setId($id, $permaLink = false)
{
if ($this->version == Feed::RSS2)
{
if (!is_bool($permaLink))
die('The permaLink parameter must be boolean.');
$permaLink = $permaLink ? 'true' : 'false';
$this->addElement('guid', $id, array('isPermaLink' => $permaLink));
}
else if ($this->version == Feed::ATOM)
{
$this->addElement('id', Feed::uuid($id,'urn:uuid:'), NULL, TRUE);
}
else
die('A unique ID is not supported in RSS1 feeds.');
return $this;
}
} // end of class Item

View File

@ -0,0 +1,41 @@
This package can be used to generate feeds in either RSS 1.0, RSS 2.0 or ATOM
formats.
There are three main classes that abstract the feed information and another to
encapsulate the feed items information.
Applications can create feed writer object, several feed item objects, set
several types of properties of either feeds and feed items, and add items to
the feed.
Once a feed is fully composed with its items, the feed writer class can generate
the necessary XML structure to describe the feed in the RSS or ATOM formats.
The feed is generated as part of the current feed output.
Requirements
============
PHP >= 5.3
If you don't have 5.3 available on your system, there's a version supporting
PHP >= 5.0 in the "legacy-php-5.0" branch.
Documentation
=============
The documentation can be found in the "gh-pages" branch or on GitHub Pages:
http://mibe.github.io/FeedWriter/
Authors
=======
(in chronological order)
Anis uddin Ahmad
Michael Bemmerl
Phil Freo
Paul Ferrett
Brennen Bearnes
Michael Robinson

View File

@ -0,0 +1,37 @@
<?php
namespace FeedWriter;
/*
* Copyright (C) 2012 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* 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/>.
*/
/**
* Wrapper for creating RSS1 feeds
*
* @package UniversalFeedWriter
*/
class RSS1 extends Feed
{
/**
* {@inheritdoc}
*/
function __construct()
{
parent::__construct(Feed::RSS1);
}
}

View File

@ -0,0 +1,37 @@
<?php
namespace FeedWriter;
/*
* Copyright (C) 2012 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* 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/>.
*/
/**
* Wrapper for creating RSS2 feeds
*
* @package UniversalFeedWriter
*/
class RSS2 extends Feed
{
/**
* {@inheritdoc}
*/
function __construct()
{
parent::__construct(Feed::RSS2);
}
}

View File

@ -0,0 +1,41 @@
{
"name": "mibe/feedwriter",
"description": "Generate feeds in either RSS 1.0, RSS 2.0 or ATOM formats",
"keywords": ["RSS"],
"homepage": "https://github.com/mibe/FeedWriter",
"type": "library",
"license": "GPL-3.0",
"authors": [
{
"name": "Anis uddin Ahmad"
},
{
"name": "Michael Bemmerl",
"email": "mail@mx-server.de"
},
{
"name": "Phil Freo"
},
{
"name": "Paul Ferrett"
},
{
"name": "Brennen Bearnes"
},
{
"name": "Michael Robinson",
"email": "mike@pagesofinterest.net"
}
],
"minimum-stability": "dev",
"autoload": {
"classmap": [
"ATOM.php",
"Feed.php",
"Item.php",
"RSS1.php",
"RSS2.php"
]
}
}

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