New version from scratch

This commit is contained in:
Knah Tsaeb 2023-06-21 11:42:36 +02:00
parent 2516b7ad5d
commit c3364cd419
180 changed files with 11803 additions and 18468 deletions

8
.gitignore vendored
View file

@ -1,5 +1,5 @@
cache/* cache/
!cache/index.html
.project
.settings
composer.lock composer.lock
datas/config.json
datas/soshot.sqlite
vendor/

View file

@ -1,5 +0,0 @@
AddDefaultCharset UTF-8
Options -Indexes
DirectoryIndex index.php index.html
FileETag none
SetOutputFilter DEFLATE

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. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

170
README.md Normal file
View file

@ -0,0 +1,170 @@
# !!!! Be careful !!!!
## Use at your own risk
Soshot make webshot of internet page with headless machine.
## Ideas
- If webshot exist in desired size, serve them, if not, verif if complete exist, if exist, crop and resize, save and serve
- If webshot not exist get information of page and add in the queue
- Cron job take a webshot of complete page and save them (1920 x complete lenth)
- Crop image and resize desired format (1920x1080, 1280x720, 160x90 ...), save and serve
SoShot always make complete webshot (1920x page lenght) + first demande size.
Size use 16/9 ratio :
- fav = define by config (default 48px)
- og = define by the website himself (no resize or crop)
- thumb = 160x90
- hd = 1280x720
- full = 1920x1080
- complete = 1920xpage height
## Requirements
- PHP 8.*
- Sqlite3
- PDO
- Composer
- Imagick
- PHP-GD
- CRON
- Chrome / Chromium
## Installation
Make directory on your web server and go in
`
mkdir /var/www/soshot && cd /var/www/soshot
`
Clone git repo
`
git clone https://forge.leslibres.org/Knah-Tsaeb/Soshot.git .
`
Install dependencies
`
composer install --no-dev
`
Configure your web server to serve in "public" directory
Go to web page
https://shoshot.your-domain.tld
## Configuration
You can use a web interface (if option "use web gui" is set to true), https://shoshot.your-domain.tld/backend?page=settings
Or you can modify config file /datas/config.json.
#### Accept only request from 127.0.0.1
Default : true
ShoShot only work for local machine, return 404 if use with remote machine.
#### Use web gui
Default : false
Soshot only work with endpoint /api. Return 404 if endpoint is not /api
#### Use log
Default : true
Not implemented yet.
#### Always make PDF
Default : false
If true, SoShot make a complete webshot and PDF of page.
#### Favicon size
Default : 48
Define size of favicon.
#### Permit type of webshot
Default : none
Select authorized size or type of webshot.
#### Cache expiration (for web GUI) in hour
Default : 12
Not implemented yet.
#### Maximum work per batch
Default : 5
Foreach cron task as launch, SoShot make 5 webshot.
#### Api key
Default : random string, lenght 12
!!! DANGER !!!
If you change key, all previous generation will be invalid. Soshot re make all previous generation.
#### Password
Default : null
Password for admin interface. No min or max character.
Add cron task
`
sudo crontab -u www-data -e
`
`
php /var/www/soshot/bin/thumbShoter.php
`
## Usage
For generating webshot the entry point is https://shoshot.your-domain.tld/api?
You need to define 3 parameters :
- type (fav, og, pdf, thumb, hd, full, complete)
- hmac (hash_hmac('sha1', url of page, your Api key);)
- url (url of page encode with url_encode)
Example : https://shoshot.your-domain.tld/api?type=fav&hmac=44a2b3f1bc43895c23779f4e71558e9976a4daf2&url=https%3A%2F%2Ffr.wikipedia.org%2Fwiki%2FLogiciel_libre
## License
GNU General Public License v3.0
See LICENSE file for more detail.
**Thanks**
- [W3c](https://www.w3schools.com/w3css/) for w3.css
- [Fork Awesome](https://forkaweso.me/Fork-Awesome/) for icon
- [embed/embed](https://github.com/oscarotero/Embed) for embed (fav and og)
- [hassankhan/config](https://github.com/hassankhan/config) for config (config mananger)
- [chrome-php/chrome](https://github.com/chrome-php/chrome) for chrome-php (wrapper for chrome dev-tool)
- [stefangabos/zebra_image](https://github.com/stefangabos/Zebra_Image) for zebra-image (resize and manipulate image)
- [guzzlehttp/psr7](https://github.com/guzzle/psr7) for psr7 (PSR7 implement)

207
app/Controllers/Backend.php Normal file
View file

@ -0,0 +1,207 @@
<?php
namespace App\Controllers;
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
use App\DataBase\DataBase;
use App\Utils\Page;
use App\Utils\ShowImg;
use Noodlehaus\Config;
class Backend {
private $start = 0;
private $end = 15;
private $max = 15;
private $runningJob = false;
private $page = 'infos';
private $params;
private $conf;
private $title = 'Settings';
private $passwordRequired = false;
public function index($params, $conf) {
if (isset($params->loginPassword)) {
if (!Login::login($params->loginPassword, $conf->password)) {
$content = $this->showLogin();
return $content;
}
}
if (!Login::isLogin()) {
$content = $this->showLogin();
return $content;
}
if (!empty($params->page)) {
$this->page = $params->page;
}
if (file_exists(__DIR__ . '/../../cache/tmp/chrome-php-socket')) {
$this->runningJob = true;
}
if (!empty($params->showImg)) {
$img = new ShowImg($params->type, $params->showImg);
exit();
}
$this->conf = $conf;
$this->params = $params;
if ($this->page === 'settings') {
if (isset($_SESSION['firstRun']) && $_SESSION['firstRun'] === 1) {
$conf->webPage = false;
$this->title = 'Install';
$this->conf->key = bin2hex(random_bytes(12));
$this->passwordRequired = "required";
}
if (isset($this->params->token) && Page::verifToken($this->params->token)) {
$this->conf = $this->setOption($params);
}
}
ob_start();
require_once __DIR__ . '/../../tpl/nav.php';
if ($this->page === 'infos') {
$this->showInfos();
} else {
$this->showSettings();
}
require_once __DIR__ . '/../../tpl/footer.php';
$content = ob_get_contents();
ob_end_clean();
return $content;
}
private function showInfos() {
if (!empty($this->params->start)) {
$this->start = $this->params->start;
}
if (!empty($this->params->end)) {
$this->end = $this->max + $this->start;
}
$conx = new DataBase();
$genList = $conx->getList($this->start, $this->end);
$total = $conx->getTotal();
$start = $this->start;
$max = $this->max;
$next = $start + $max;
$previous = $start - ($max);
if (count($genList) < $this->max) {
$next = $start;
}
if ($previous < 0) {
$previous = 0;
}
require __DIR__ . '/../../tpl/infos.php';
}
private function showSettings() {
if (!empty($this->params->start)) {
$this->start = $this->params->start;
}
if (!empty($this->params->end)) {
$this->end = $this->max + $this->start;
}
if ($this->start < 0) {
$this->start = 0;
}
$conx = new DataBase();
$genList = $conx->getList($this->start, $this->end);
$total = $conx->getTotal();
$start = $this->start;
$max = $this->max;
$token = Page::genToken();
require __DIR__ . '/../../tpl/settings.php';
}
private function setOption($post) {
if (!file_exists(__DIR__ . '/../../datas/config.json')) {
file_put_contents(__DIR__ . '/../../datas/config.json', json_encode([]));
unset($_SESSION['login']);
unset($_SESSION['firstRun']);
}
$userConfig = __DIR__ . '/../../datas/config.json';
$uConfig = new Config($userConfig);
if (empty($post->onlyLocalServer)) {
$uConfig['onlyLocalServer'] = false;
} else {
$uConfig['onlyLocalServer'] = true;
}
if (empty($post->webPage)) {
$uConfig['webPage'] = false;
} else {
$uConfig['webPage'] = true;
}
if (empty($post->log)) {
$uConfig['log'] = false;
} else {
$uConfig['log'] = true;
}
if (empty($post->alwaysMakePdf)) {
$uConfig['alwaysMakePdf'] = false;
} else {
$uConfig['alwaysMakePdf'] = true;
}
if (!empty($post->icoSize)) {
$uConfig['icoSize'] = (int)$post->icoSize;
}
if (!empty($post->expireCache)) {
$uConfig['expireCache'] = (int)$post->expireCache;
}
if (!empty($post->maxGenPerBatch)) {
$uConfig['maxGenPerBatch'] = (int)$post->maxGenPerBatch;
}
if (!empty($post->permitType)) {
$uConfig['permitType'] = $post->permitType;
} else {
$uConfig['permitType'] = [];
}
if (!empty($post->password)) {
$uConfig['password'] = password_hash($post->password, PASSWORD_DEFAULT);
}
if (!empty($post->key)) {
$uConfig['key'] = $post->key;
}
$uConfig->toFile($userConfig);
$newConfig = new Config($userConfig);
return (object)$newConfig->all();
}
private function showLogin() {
ob_start();
$token = Page::genToken();
require_once __DIR__ . '/../../tpl/login.php';
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}

View file

@ -0,0 +1,8 @@
<?php
namespace App\Controllers;
class GenHmac {
function index($params, $conf) {
echo hash_hmac('sha1', $params->url, $conf['key']);
}
}

16
app/Controllers/Home.php Normal file
View file

@ -0,0 +1,16 @@
<?php
namespace App\Controllers;
use App\Utils\Hmac;
class Home {
public function index() {
ob_start();
require __DIR__ . '/../../tpl/home.php';
$content = ob_get_contents();
ob_end_clean();
return $content;
}
}

20
app/Controllers/Login.php Normal file
View file

@ -0,0 +1,20 @@
<?php
namespace App\Controllers;
class Login {
static function isLogin() {
if (isset($_SESSION['login']) && $_SESSION['login'] === 1) {
return true;
}
return false;
}
static function login($password, $hash) {
if (password_verify($password, $hash)) {
$_SESSION['login'] = 1;
return true;
}
return false;
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace App\Controllers;
class Logout {
public function index() {
session_start();
session_destroy();
header("Location:/");
exit();
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace App\Controllers;
use App\Soshot\GetThumb;
use App\Soshot\GetFav;
use App\Soshot\GetOg;
use App\Utils\Error;
class Result {
public function index($params, $conf) {
if (
!isset($params->type) ||
!isset($params->hmac) ||
!isset($params->url)
) {
$error = new Error();
$error->index((object)['status' => 400, 'message' => 'Missing parameters']);
}
if (!in_array($params->type, $conf->permitType)) {
$error = new Error();
$error->index((object)['status' => 400, 'message' => 'Wrong type']);
}
if ($params->type === 'fav') {
$favicon = new GetFav($params, $conf);
$favicon->show();
} elseif ($params->type === 'og') {
$favicon = new GetOg($params, $conf);
$favicon->show();
} else {
$result = new GetThumb($params, $conf);
$result->show();
}
}
}

134
app/DataBase/DataBase.php Normal file
View file

@ -0,0 +1,134 @@
<?php
namespace App\DataBase;
use Exception;
use PDO;
if (!function_exists('n_print')) {
function n_print($data, $name = '') {
print_r($data, 1);
}
}
class DataBase {
private $dataBase = __DIR__ . '/../../datas/soshot.sqlite';
private $db;
private $params = [
'id' => '',
'url' => '',
'complete' => '',
'full' => '',
'hd' => '',
'thumb' => '',
'fav' => '',
'og' => '',
'pdf' => '',
'created' => ''
];
function __construct($params = null) {
try {
if (!file_exists($this->dataBase)) {
$this->db = new PDO('sqlite:' . $this->dataBase);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // ERRMODE_WARNING | ERRMODE_EXCEPTION | ERRMODE_SILENT
$this->db->query("CREATE TABLE IF NOT EXISTS soshot (
id string PRIMARY KEY NOT NULL,
url text,
complete tinyint,
full tinyint,
hd tinyint,
thumb tinyint,
fav tinyint,
og tinyint,
pdf tinyint,
created DATETIME
);");
} else {
$this->db = new PDO('sqlite:' . $this->dataBase);
$this->db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // ERRMODE_WARNING | ERRMODE_EXCEPTION | ERRMODE_SILENT
}
} catch (Exception $e) {
echo $e->getMessage();
die();
}
if (!empty($params)) {
$this->setParams($params);
}
return $this;
}
public function setParams($params) {
$this->params = (object)$this->params;
$this->params->id = $params->hmac;
$this->params->url = $params->url;
$this->params->type = $params->type;
$this->params->created = date("Y-m-d H:i:s");
$this->params = $this->params;
}
public function addUpdate($update, $type = '') {
if (!empty($type)) {
$this->params->type = $type;
}
if ($this->testExit($this->params->id)) {
$this->update($update);
} else {
$this->insert($update);
}
}
public function insert($update) {
$stmt = $this->db->prepare("INSERT INTO soshot (id, url, " . $this->params->type . ", created) VALUES
(:id, :url, :" . $this->params->type . ", :created)");
//$stmt->debugDumpParams();
$result = $stmt->execute(array(
'id' => $this->params->id,
'url' => $this->params->url,
$this->params->type => $update,
'created' => $this->params->created
));
}
private function update($update) {
$stmt = $this->db->prepare("UPDATE soshot
SET " . $this->params->type . "=:" . $this->params->type . "
WHERE id=:id;");
$result = $stmt->execute([
':' . $this->params->type => $update,
':id' => $this->params->id
]);
//$stmt->debugDumpParams();
}
private function testExit($id) {
$stmt = $this->db->prepare("SELECT id FROM soshot WHERE id=:id LIMIT 1;");
$stmt->execute(array(':id' => $id));
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
if (!empty($result)) {
return true;
}
return false;
}
public function getTotal() {
$stmt = $this->db->prepare("SELECT COUNT(id) AS nb FROM soshot ");
$stmt->execute();
$result = $stmt->fetch();
return $result['nb'];
}
public function getList($start, $end) {
$stmt = $this->db->prepare("SELECT * FROM soshot ORDER BY created DESC limit :start, :end;");
$stmt->execute(array(':start' => $start, ':end' => $end));
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
return $result;
}
}

71
app/Router.php Normal file
View file

@ -0,0 +1,71 @@
<?php
namespace App;
use App\Utils\Error;
class Router {
private $routes;
private $params = [];
private $requestMethod;
private $path;
public function __construct() {
$this->routes = [];
}
public function addRoute($paths, $controller, $method = 'GET') {
if (!is_array($paths)) {
$paths = [$paths];
}
foreach ($paths as $path) {
$this->routes[$path] = [
'controller' => $controller,
'method' => $method
];
}
}
public function match() {
$path = $_SERVER['REQUEST_URI'];
$parts = parse_url($path);
$this->path = $parts['path'];
$this->requestMethod = $_SERVER['REQUEST_METHOD'];
if (isset($this->routes[$this->path])) {
return true;
}
return false;
}
public function render($conf) {
if ($this->requestMethod === 'GET') {
$this->params = (object)$_GET;
} elseif ($this->requestMethod === 'POST') {
$this->params = (object)$_POST;
} else {
$error = new Error();
$error->index((object)['status' => 405, 'message' => 'Method not allowed']);
}
if ($conf->webPage === false && $this->path !== '/api') {
$error = new Error();
$error->index((object)['status' => 404, 'message' => 'The page that you have requested could not be found.']);
}
if ($this->path === '/debug') {
require_once __DIR__ . '/../bin/thumbShoter.php';
exit();
}
$className = '\\' . $this->routes[$this->path]['controller'];
$controllerInstance = new $className();
$content = $controllerInstance->index($this->params, $conf);
if (in_array($className, ['\App\Controllers\Home', '\App\Controllers\Backend']) && empty($this->params->showImg)) {
require_once __DIR__ . '/../tpl/bone.php';
}
}
}

86
app/Soshot/GetFav.php Normal file
View file

@ -0,0 +1,86 @@
<?php
namespace App\Soshot;
use App\Soshot\GetThumb;
use App\Utils\ConvertIco;
use Embed\Embed;
use Zebra_Image;
class GetFav extends GetThumb {
public function makeFavicon() {
if (!is_dir($this->filePath)) {
mkdir($this->demande->filePath);
}
try {
$embed = new Embed();
$info = $embed->get($this->demande->url);
if (!is_null($info->favicon)) {
if (!$favicon = @file_get_contents($info->favicon)) {
copy(__DIR__ . '/../../src/images/error_fav.png', $this->demande->requestImg);
$this->db->addUpdate(2);
return true;
}
} elseif (!is_null($info->icon)) {
if (!$favicon = @file_get_contents($info->icon)) {
copy(__DIR__ . '/../../src/images/error_fav.png', $this->demande->requestImg);
$this->db->addUpdate(2);
return true;
}
} else {
copy(__DIR__ . '/../../src/images/error_fav.png', $this->demande->requestImg);
$this->db->addUpdate(2);
return true;
}
file_put_contents($this->demande->requestImg, $favicon);
$realMimeType = mime_content_type($this->demande->requestImg);
if ($realMimeType === 'image/vnd.microsoft.icon') {
ConvertIco::convert($this->demande, $this->conf->icoSize);
}
if ($realMimeType === 'image/svg+xml') {
ConvertIco::convert($this->demande, $this->conf->icoSize);
}
$image = new Zebra_Image();
$image->source_path = $this->demande->requestImg;
$image->target_path = $this->demande->requestImg;
$image->preserve_time = false;
$image->enlarge_smaller_images = false;
$image->resize($this->conf->icoSize, $this->conf->icoSize, ZEBRA_IMAGE_CROP_TOPLEFT);
} catch (\Exception $e) {
$this->db->addUpdate(2);
copy(__DIR__ . '/../../src/images/error_fav.png', $this->demande->requestImg);
return true;
}
if (!is_file($this->demande->requestImg)) {
copy(__DIR__ . '/../../src/images/error_fav.png', $this->demande->requestImg);
$this->db->addUpdate(2);
return true;
} else {
$this->db->addUpdate(1);
}
}
public function show() {
if (!file_exists($this->requestImg) && $this->type === 'fav') {
$this->makeFavicon();
}
//n_print($this);
//echo '<img src="data:image/png;base64,'.base64_encode(file_get_contents($this->requestImg)).'">';
header("Content-type: image/png");
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
echo file_get_contents($this->requestImg);
exit();
}
}

68
app/Soshot/GetOg.php Normal file
View file

@ -0,0 +1,68 @@
<?php
namespace App\Soshot;
use App\Soshot\GetThumb;
use Embed\Embed;
use App\Utils\ConvertToPng;
class GetOg extends GetThumb {
public function makeOg() {
if (!is_dir($this->filePath)) {
mkdir($this->demande->filePath);
}
try {
$embed = new Embed();
$info = $embed->get($this->demande->url);
if (!is_null($info->image)) {
if (!$image = file_get_contents($info->image)) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2);
return true;
}
} else {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2);
return true;
}
if (empty($image)) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2);
return true;
}
file_put_contents($this->demande->requestImg, $image);
if (in_array(mime_content_type($this->demande->requestImg), ['image/jpg', 'image/jpeg', 'image/bmp', 'image/webp'])) {
ConvertToPng::convertToPng($this->demande);
}
} catch (\Exception $e) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2);
}
if (!is_file($this->demande->requestImg)) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2);
} else {
$this->db->addUpdate(1);
}
}
public function show() {
if (file_exists($this->requestImg) && $this->type === 'og') {
} else {
$this->makeOg();
}
//echo '<img src="data:' . mime_content_type($this->requestImg) . ';base64,' . base64_encode(file_get_contents($this->requestImg)) . '">';
header("Content-type: " . mime_content_type($this->requestImg));
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
echo file_get_contents($this->requestImg);
exit();
}
}

129
app/Soshot/GetThumb.php Normal file
View file

@ -0,0 +1,129 @@
<?php
namespace App\Soshot;
use App\DataBase\DataBase;
use App\Utils\Hmac;
use App\Utils\Error;
use App\Utils\ResizeToDemande;
class GetThumb {
protected $params;
protected $type;
protected $filePath;
protected $receiveHmac;
protected $requestImg;
protected $queuePath = __DIR__ . '/../../cache/queue/';
protected $complete;
protected $conf;
protected $db;
protected $demande;
function __construct($params, $conf) {
$hmac = new Hmac($conf->key);
$this->conf = $conf;
$this->receiveHmac = $params->hmac;
if ($hmac->checkHmac($this->receiveHmac, $params->url) === false) {
$message = (object) ['status' => 404, 'message' => 'Wrong Hmac'];
$error = new Error();
$error->index($message);
}
$this->params = $params;
$this->type = $params->type;
$this->filePath = $hmac->makeFilePath($this->receiveHmac);
if ($this->type === 'pdf') {
$this->requestImg = $this->filePath . $this->receiveHmac . '_' . $this->type . '.pdf';
} else {
$this->requestImg = $this->filePath . $this->receiveHmac . '_' . $this->type . '.png';
}
$this->complete = __DIR__ . '/../../cache/img/' . substr($this->params->hmac, 0, 4) . '/' . $this->params->hmac . '_complete.png';
$this->demande = (object)[
'url' => $this->params->url,
'hmac' => $this->params->hmac,
'filePath' => $this->filePath,
'requestImg' => $this->requestImg,
'type' => $this->params->type
];
$this->db = new DataBase($this->demande);
return $this;
}
public function show() {
if ($this->type === 'pdf' && file_exists($this->requestImg)) {
header("Content-type:application/pdf");
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
header("Content-Disposition:attachment;filename=\"archive.pdf\"");
readfile($this->requestImg);
echo file_get_contents($this->requestImg);
exit();
} else if (file_exists($this->requestImg) && in_array($this->type, ['complete', 'full', 'hd', 'thumb'])) {
header("Content-type: image/png");
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
echo file_get_contents($this->requestImg);
exit();
}
if (file_exists($this->complete) && in_array($this->type, ['complete', 'full', 'hd', 'thumb'])) {
if (ResizeToDemande::makeDemande((object)[
'complete' => $this->complete,
'filePath' => $this->requestImg,
'type' => $this->type
])) {
$this->db->addUpdate(1);
header("Content-type: image/png");
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
echo file_get_contents($this->requestImg);
exit();
} else {
// @todo log
}
exit();
} else {
$json = json_encode([
'type' => $this->params->type,
'hmac' => $this->params->hmac,
'url' => $this->params->url,
'filePath' => $this->requestImg,
'complete' => __DIR__ . '/../../cache/img/' . substr($this->params->hmac, 0, 4) . '/' . $this->params->hmac . '_complete.png'
]);
$completeDemande = (object)[
'url' => $this->params->url,
'hmac' => $this->params->hmac,
'filePath' => $this->filePath,
'requestImg' => $this->requestImg,
'type' => 'complete'
];
$complete = new DataBase($completeDemande);
$complete->addUpdate(3);
if ($this->conf->alwaysMakePdf === true) {
$complete->addUpdate(3, 'pdf');
}
$this->addQueue($json);
header("Content-type: image/png");
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
if ($this->type === 'fav') {
echo file_get_contents(__DIR__ . '/../../src/images/error_fav.png');
} else {
echo file_get_contents(__DIR__ . '/../../src/images/loadingGen.png');
}
exit();
}
}
private function addQueue($json) {
$file = $this->queuePath . $this->receiveHmac . '.json';
$this->db->addUpdate(3);
if (!file_exists($file)) {
file_put_contents($file, $json);
}
}
}

186
app/Soshot/MakeThumb.php Normal file
View file

@ -0,0 +1,186 @@
<?php
namespace App\Soshot;
use App\DataBase\DataBase;
use App\Utils\ResizeToDemande;
use HeadlessChromium\BrowserFactory;
use HeadlessChromium\Page;
use HeadlessChromium\Exception\BrowserConnectionFailed;
use HeadlessChromium\Exception\OperationTimedOut;
use Noodlehaus\Config;
if (!function_exists('n_print')) {
function n_print($data, $name = '') {
print_r($data, 1);
}
}
class MakeThumb {
private $queuePath = __DIR__ . '/../../cache/queue/';
private $thumbPath = __DIR__ . '/../../cache/img/';
private $fileSocket = __DIR__ . '/../../cache/tmp/chrome-php-socket';
private $fileList = [];
private $maxGenPerBatch = 2;
private $demandes = [];
private $open = false;
private $conf;
private $db;
function __construct() {
$this->conf = (object)Config::load([__DIR__ . '/../../datas/config.default.json', '?' . __DIR__ . '/../../datas/config.json'])->all();
$this->maxGenPerBatch = $this->conf->maxGenPerBatch;
foreach (array_slice(glob($this->queuePath . "*.json"), 0, $this->maxGenPerBatch) as $filename) {
$this->fileList[] = $filename;
}
foreach ($this->fileList as $demande) {
$this->demandes[] = json_decode(file_get_contents($demande));
}
$this->db = new DataBase();
}
public function compute() {
foreach ($this->demandes as $demande) {
$this->db->setParams($demande);
// todo verif permit type
if ($this->testComplete($demande->complete) && $demande->type !== 'pdf') {
if (ResizeToDemande::makeDemande($demande)) {
$this->deleteQueue($demande->hmac);
$this->db->addUpdate(1);
}
} else {
$this->makeComplete($demande);
if ($demande->type !== 'pdf') {
if (!ResizeToDemande::makeDemande($demande)) {
// todo log
}
}
$this->deleteQueue($demande->hmac);
$this->db->addUpdate(1);
$completeDemande = (object)[
'hmac' => $demande->hmac,
'url' => $demande->url,
'type' => 'complete'
];
$complete = new DataBase($completeDemande);
$complete->addUpdate(1);
}
$this->open = true;
if ($this->open === true) {
$this->makeComplete(null, true);
}
}
}
private function deleteQueue($hmac) {
if (file_exists($this->queuePath . $hmac . '.json')) {
unlink($this->queuePath . $hmac . '.json');
}
}
private function testComplete($complete) {
if (file_exists($complete)) {
return true;
}
return false;
}
private function makeComplete($demande, $close = false) {
if (file_exists($this->fileSocket)) {
$socket = \file_get_contents($this->fileSocket);
try {
$browser = BrowserFactory::connectToBrowser($socket);
} catch (BrowserConnectionFailed $e) {
$browser = $this->openBrowser();
}
} else {
$factory = new BrowserFactory('chromium');
$browser = $factory->createBrowser([
'userAgent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'keepAlive' => true,
'headless' => true,
'windowSize' => [1920, 1080],
//'connectionDelay' => 0.8, // add 0.8 second of delay between each instruction sent to chrome,
//'debugLogger' => 'php://stdout',
]);
\file_put_contents($this->fileSocket, $browser->getSocketUri(), LOCK_EX);
}
if ($close === true) {
$socket = \file_get_contents($this->fileSocket);
$browser = BrowserFactory::connectToBrowser($socket);
$browser->close();
unlink($this->fileSocket);
return true;
}
$dir = $this->thumbPath . substr($demande->hmac, 0, 4) . '/';
if (!is_dir($dir)) {
mkdir($dir);
}
$page = $browser->createPage();
$page->navigate($demande->url)->waitForNavigation(Page::DOM_CONTENT_LOADED, 15000);
sleep(4);
try {
$page->screenshot([
'captureBeyondViewport' => true,
'clip' => $page->getFullPageClip(),
])->saveToFile($demande->complete);
if ($demande->type === 'pdf' || $this->conf->alwaysMakePdf === true) {
if ($this->conf->alwaysMakePdf === true) {
$pdfFile = str_replace($demande->type, 'pdf', $demande->filePath);
$pdfFile = str_replace('png', 'pdf', $pdfFile);
} else {
$pdfFile = $demande->filePath;
}
$page->pdf([
'printBackground' => true,
'displayHeaderFooter' => true,
'paperWidth' => 8.268,
'paperHeight' => 11.693,
'scale' => 1
])->saveToFile($pdfFile);
if ($this->conf->alwaysMakePdf === true) {
$this->db->addUpdate(1, 'pdf');
}
}
$this->db->addUpdate(1);
} catch (OperationTimedOut $e) {
// todo log
$socket = \file_get_contents($this->fileSocket);
$browser = BrowserFactory::connectToBrowser($socket);
$browser->close();
unlink($this->fileSocket);
copy(__DIR__ . '/../../src/images/error_thumb.png', $demande->filePath);
$this->db->addUpdate(2);
}
}
private function openBrowser() {
$factory = new BrowserFactory('chromium');
// Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
$browser = $factory->createBrowser([
'userAgent' => 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'keepAlive' => true,
'headless' => true,
'windowSize' => [1920, 1080],
]);
\file_put_contents($this->fileSocket, $browser->getSocketUri(), LOCK_EX);
return $browser;
}
}

28
app/Utils/ConvertIco.php Normal file
View file

@ -0,0 +1,28 @@
<?php
namespace App\Utils;
use Imagick;
class ConvertIco {
static function convert($demande, $size) {
rename($demande->requestImg, $demande->requestImg . '.ico');
$icoFile = $demande->requestImg . '.ico';
if (empty(Imagick::queryFormats("ICO"))) {
throw new \Exception('Unsupported format');
}
$im = new Imagick($icoFile);
$targetWidth = $targetHeight = $size;
if ($im->getImageWidth() <> $targetWidth || $im->getImageHeight() <> $targetHeight) {
$im->cropThumbnailImage($targetWidth, $targetHeight);
}
$im->writeImage($demande->requestImg);
unlink($icoFile);
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Utils;
class ConvertStatus {
static function convertToIcon($status) {
if ($status === 1) {
echo '<i class="fa fa-check w3-text-green" aria-hidden="true"></i>';
} elseif ($status === 2) {
echo '<i class="fa fa-check w3-text-red" aria-hidden="true"></i>';
} elseif ($status === 3) {
echo '<i class="fa fa-clock-o w3-text-orange" aria-hidden="true"></i>';
}else {
echo '<i class="fa fa-ban w3-text-red" aria-hidden="true"></i>';
}
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace App\Utils;
class ConvertToPng {
static function convertToPng($demande) {
rename($demande->requestImg, $demande->requestImg . '.tmp');
$tmpFile = $demande->requestImg . '.tmp';
if (!imagepng(imagecreatefromstring(file_get_contents($tmpFile)), $demande->requestImg)) {
}
unlink($tmpFile);
}
}

11
app/Utils/Domains.php Normal file
View file

@ -0,0 +1,11 @@
<?php
namespace App\Utils;
class Domains {
static function getDomain($url) {
$sourceUrl = parse_url($url);
return $sourceUrl['host'];
}
}

14
app/Utils/Error.php Normal file
View file

@ -0,0 +1,14 @@
<?php
namespace App\Utils;
class Error {
private $errorType = [];
function index(object $error) {
http_response_code($error->status);
echo "<h1>404 Not Found</h1>";
echo "$error->message";
exit();
}
}

36
app/Utils/Hmac.php Normal file
View file

@ -0,0 +1,36 @@
<?php
namespace App\Utils;
class Hmac {
private $key;
private $basePath = __DIR__ . '/../../cache/img/';
private $filePath;
private $hashPath;
public function __construct($key) {
$this->key = $key;
}
public function makeHmac($url) {
return hash_hmac('sha1', $url, $this->key);
}
private function makeHashPath($hashUrl) {
$this->hashPath = substr($hashUrl, 0, 4) . '/';
return $this->hashPath;
}
public function makeFilePath($hmac) {
$this->filePath = $this->basePath . $this->makeHashPath($hmac);
return $this->filePath;
}
public function checkHmac($receiveHmac, $url) {
if ($receiveHmac === $this->makeHmac($url, $this->key)) {
return true;
} else {
return false;
}
}
}

37
app/Utils/Page.php Normal file
View file

@ -0,0 +1,37 @@
<?php
namespace App\Utils;
class Page {
static function active($test, $attend, $class) {
if ($test === $attend) {
return $class;
}
}
static function checked($test, $attend) {
if ($test === $attend) {
return 'checked';
}
}
static function selected($test, $attend) {
if (in_array($test, $attend)) {
return 'selected';
}
}
static function genToken() {
$token = sha1(uniqid(rand(), true) . '_' . mt_rand());
$_SESSION['token'] = $token;
return $token;
}
static function verifToken($token) {
if ($token === $_SESSION['token']) {
return true;
}
return false;
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace App\Utils;
use Zebra_Image;
class ResizeToDemande {
static function makeDemande($demande) {
// todo add 640 360
$image = new Zebra_Image();
$image->source_path = $demande->complete;
$image->target_path = $demande->filePath;
$image->preserve_time = false;
$image->enlarge_smaller_images = false;
if ($demande->type === 'full') {
$image->resize(1920, 1080, ZEBRA_IMAGE_CROP_TOPLEFT);
return true;
}
if ($demande->type === 'hd') {
$image->resize(1280, 720, ZEBRA_IMAGE_CROP_TOPLEFT);
return true;
}
if ($demande->type === 'thumb') {
$image->resize(160, 90, ZEBRA_IMAGE_CROP_TOPLEFT);
return true;
}
return false;
}
}

24
app/Utils/ShowImg.php Normal file
View file

@ -0,0 +1,24 @@
<?php
namespace App\Utils;
class ShowImg {
private $thumbPath = __DIR__ . '/../../cache/img/';
function __construct($type, $hmac) {
$img = $this->thumbPath . substr($hmac, 0, 4) . '/' . $hmac . '_' . $type . '.png';
header("Content-type: image/png");
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
if (file_exists($img)) {
echo file_get_contents($img);
} else {
// todo not gen
echo file_get_contents(__DIR__ . '/../../src/images/error_thumb.png');
}
exit();
}
}

View file

@ -1,2 +0,0 @@
Allow from none
Deny from all

View file

@ -1,14 +0,0 @@
#!/bin/bash
queueDir="../cache/cronTask/"
for file in $queueDir*.hash
do
if [ -f $file ];
then
while read site hashUrl thumbSize sizeNameDir onlyThumb
do
bash thumb_server.sh "$site" "$hashUrl" "$thumbSize" "$sizeNameDir" "$onlyThumb" "0"
rm $file
done < $file
fi
done

View file

View file

@ -1,16 +0,0 @@
#!/bin/bash
while [ 1 ]
do
clear
echo "#####################################################"
echo "#####################################################"
echo "#### Request thumbshot (thumb_server.sh) : " $(ps ax | grep -v grep | grep thumb_server.sh | wc -l) && # count thumb_server.sh process
echo "#### Nb of thumbshot are made now (phantomjs) : " $(ps ax | grep -v grep | grep phantomjs | wc -l) && # count phantomjs process
echo "#### Nb of test error now (curl) : " $(ps ax | grep -v grep | grep curl | wc -l) # count thumb_server.sh => curl process
echo "#### Nb of optimize operation (optipng) : " $(ps ax | grep -v grep | grep optipng | wc -l) # count thumb_server.sh => curl process
echo "#####################################################"
echo "########### PRESS CTRL+C FOR STOP MONITOR ###########"
echo "#####################################################"
sleep 3 # 3 second between two refresh
done

Binary file not shown.

Binary file not shown.

View file

@ -1,28 +0,0 @@
"use strict";
var page = require('webpage').create(),
system = require('system'),
address, output;
if (system.args.length < 2) {
console.log('Usage: rasterize.js URL filename [paperwidth*paperheight|paperformat] [zoom]');
console.log(' paper (pdf output) examples: "5in*7.5in", "10cm*20cm", "A4", "Letter"');
console.log(' image (png/jpg output) examples: "1920px" entire page, window width 1920px');
console.log(' "800px*600px" window, clipped to 800x600');
phantom.exit(1);
} else {
address = system.args[1];
output = system.args[2];
page.viewportSize = { width: 1280, height: 1024};
page.open(address, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit(1);
} else {
window.setTimeout(function () {
page.render(output);
phantom.exit();
}, 200);
}
});
}

View file

@ -1,6 +0,0 @@
#/bin/bash
cd ../cache/tmp/
pwd
rm *.lock
rm *.png
rm *.jpg

View file

@ -1,4 +0,0 @@
#!/bin/bash
kill -TERM $(ps ax | grep -v grep | grep thumb_server.sh | awk '{print $1}')
kill -TERM $(ps ax | grep -v grep | grep phantomjs | awk '{print $1}')
kill -TERM $(ps ax | grep -v grep | grep optipng | awk '{print $1}')

16
bin/thumbShoter.php Normal file
View file

@ -0,0 +1,16 @@
<?php
namespace App\Bin;
session_start();
require_once __DIR__ . '/../vendor/autoload.php';
use App\Models\MakeThumb;
if(file_exists(__DIR__ . '/../cache/tmp/chrome-php-socket')){
echo 'Work in progress';
exit();
}
$makeThumb = new MakeThumb;
$makeThumb->compute();

View file

@ -1,195 +0,0 @@
#!/bin/bash
# inspirated source http://www.cambus.net/creating-thumbnails-using-phantomjs-and-imagemagick/ for global idea
# https://gist.github.com/rsvp/1171304 for httpstatus code
# All info at http://forge.leslibres.org/projects/soshot
site=$1 # url for thumbshot
hashUrl=$2 # hash(url) is the name of final image
thumbSize=$3 # size of thumb widthxheight ex : 190x90
sizeNameDir=$4 # name of size dir
renderType=$5 # make only thumbshot / thumbshot + realSize / thumbshot + complete / thumbshot + complete + realSize
waitForResult=$6 # if true we try to make soon as possible or add to queue
noErrorLog=$7
##########################################
##### DON'T EDIT THIS PARAM USE #####
##### cache/config/serverOptions.php #####
##### for overwrite options #####
##########################################
maxThread=1 # max parralle work. For me the best is nb core - 1
timeOut=120 # default time out, after this time the site are declared in error
log=false # log all generation success and error
randomSleep=`echo $((RANDOM%40))`
optimizeTool='' # external tool form optimize png
maxQueue=50 # max process in queue
currentProcess=$(ps ax | grep -v grep | grep thumb_server.sh | wc -l)
firstLevel=${hashUrl:0:2}
secondLevel=${hashUrl:2:2}
startPath=$sizeNameDir/$firstLevel/$secondLevel/
getArch=$(getconf LONG_BIT)
#echo $getArch
if [ -f "../cache/config/serverOptions.php" ]
then
source "../cache/config/serverOptions.php"
fi
if [ $currentProcess -gt $maxQueue ]
then
rm "../cache/tmp/$hashUrl.lock"
exit
fi
if [ "$site" = "manual" ]
then
site=$(cat "../cache/tmp/manual.txt")
echo '' > "../cache/tmp/manual.txt"
fi
mkdir -p "../cache/img/$startPath"
if [ ! $waitForResult ]
then
sleep $randomSleep
while [[ `ps -ax | grep -v grep | grep phantomjs | wc -l` -ge $maxThread ]]
do
sleep $randomSleep
done
fi
start_time=`date +%s`
if [ $getArch -eq 64 ]
then
timeout $timeOut nice -n 5 ./phantomjs_x64 --disk-cache=false --local-storage-path=../cache/tmp --ignore-ssl-errors=true --web-security=false rasterize.js "$site" "../cache/tmp/$hashUrl.png"
exitStatus=$?
else
timeout $timeOut nice -n 5 ./phantomjs_x86 --disk-cache=false --local-storage-path=../cache/tmp --ignore-ssl-errors=true --web-security=false rasterize.js "$site" "../cache/tmp/$hashUrl.png"
exitStatus=$?
fi
#echo $exitStatus
if [ $exitStatus -eq 124 ]
then
echo 0
cp "000.png" "../cache/img/$startPath""$hashUrl""_thumb.png" && cp "000.png" "../cache/img/$startPath""$hashUrl.png" && cp "000.png" "../cache/img/$startPath""$hashUrl""_complete.png"
rm "../cache/tmp/$hashUrl.lock"
exit
fi
if [[ ! -f "../cache/tmp/$hashUrl.png" ]]
then
echo 0
errorCode=`echo $(curl -k -L --write-out %{http_code} --silent -S --connect-timeout $timeOut \--no-keepalive --output /dev/null $site)`
if [ $site == 'manual' ]
then
errorCode='manual'
fi
#echo $errorCode
case $errorCode in
000) cp "000.png" "../cache/img/$startPath""$hashUrl""_thumb.png" && cp "000.png" "../cache/img/$startPath""$hashUrl.png" && cp "000.png" "../cache/img/$startPath""$hashUrl""_complete.png";;
200) cp "error.png" "../cache/img/$startPath""$hashUrl""_thumb.png" && cp "error.png" "../cache/img/$startPath""$hashUrl.png" && cp "error.png" "../cache/img/$startPath""$hashUrl""_complete.png";;
404) cp "404.png" "../cache/img/$startPath""$hashUrl""_thumb.png" && cp "404.png" "../cache/img/$startPath""$hashUrl.png" && cp "404.png" "../cache/img/$startPath""$hashUrl""_complete.png";;
manual) rm "../cache/tmp/$hashUrl.lock" && exit;;
*) cp "error.png" "../cache/img/$startPath""$hashUrl""_thumb.png" && cp "error.png" "../cache/img/$startPath""$hashUrl.png" && cp "error.png" "../cache/img/$startPath""$hashUrl""_complete.png";;
esac
rm "../cache/tmp/$hashUrl.lock"
if $log == true
then
end_time=`date +%s`
logDate=`date +'[%a %d %b %Y] [%H:%M:%S]'`
if [ $noErrorLog == "noErrorLog" ]
then
exit
fi
if [ $errorCode == 200 ]
then
echo "none --- "$site" --- "$hashUrl" --- "$thumbSize" --- "$sizeNameDir" --- "$onlyThumb" --- true --- "$errorCode > "../cache/logs/retry/"$hashUrl".log"
else
echo "none --- "$site" --- "$hashUrl" --- "$thumbSize" --- "$sizeNameDir" --- "$onlyThumb" --- true --- "$errorCode > "../cache/logs/other/"$hashUrl".log"
fi
fi
exit
fi
case $renderType in
# thumbnail only
t)
nice -n 5 convert "../cache/tmp/$hashUrl.png" -crop 1280x1024+0+0 -filter Lanczos -thumbnail "$thumbSize" "../cache/tmp/$hashUrl""_thumb.png"
if [ $optimizeTool ]
then
eval nice -n 5 $optimizeTool "../cache/tmp/$hashUrl""_thumb.png" &>/dev/null
fi
mv "../cache/tmp/$hashUrl""_thumb.png" "../cache/img/$startPath""$hashUrl""_thumb.png"
if [[ -f "../cache/img/$startPath""$hashUrl""_thumb.png" ]]
then
echo 1
else
echo 0
fi
rm "../cache/tmp/$hashUrl.png"
rm "../cache/tmp/$hashUrl.lock"
;;
# thumbnail + complete
tc)
nice -n 5 convert "../cache/tmp/$hashUrl.png" -crop 1280x1024+0+0 -filter Lanczos -thumbnail "$thumbSize" "../cache/tmp/$hashUrl""_thumb.png"
if [ $optimizeTool ]
then
nice -n 5 eval $optimizeTool "../cache/tmp/$hashUrl""_thumb.png" "../cache/tmp/$hashUrl.png" &>/dev/null
fi
mv "../cache/tmp/$hashUrl.png" "../cache/img/$startPath""$hashUrl""_complete.png"
mv "../cache/tmp/$hashUrl""_thumb.png" "../cache/img/$startPath""$hashUrl""_thumb.png"
if [[ -f "../cache/img/$startPath""$hashUrl""_thumb.png" && -f "../cache/img/$startPath""$hashUrl""_complete.png" ]]
then
echo 1
else
echo 0
fi
rm "../cache/tmp/$hashUrl.lock"
;;
# thumbnail + realsize
tr)
nice -n 5 convert "../cache/tmp/$hashUrl.png" -crop 1280x1024+0+0 "../cache/tmp/$hashUrl.png"
nice -n 5 convert "../cache/tmp/$hashUrl.png" -filter Lanczos -thumbnail "$thumbSize" "../cache/tmp/$hashUrl""_thumb.png"
if [ $optimizeTool ]
then
eval nice -n 5 $optimizeTool "../cache/tmp/$hashUrl""_thumb.png" "../cache/tmp/$hashUrl.png" &>/dev/null
fi
mv "../cache/tmp/$hashUrl.png" "../cache/img/$startPath""$hashUrl.png"
mv "../cache/tmp/$hashUrl""_thumb.png" "../cache/img/$startPath""$hashUrl""_thumb.png"
if [[ -f "../cache/img/$startPath""$hashUrl""_thumb.png" && -f "../cache/img/$startPath""$hashUrl.png" ]]
then
echo 1
else
echo 0
fi
rm "../cache/tmp/$hashUrl.lock"
;;
# thumbnail + realsize + complete
trc)
cp "../cache/tmp/$hashUrl.png" "../cache/tmp/$hashUrl""_complete.png"
nice -n 5 convert "../cache/tmp/$hashUrl.png" -crop 1280x1024+0+0 "../cache/tmp/$hashUrl.png"
nice -n 5 convert "../cache/tmp/$hashUrl.png" -filter Lanczos -thumbnail "$thumbSize" "../cache/tmp/$hashUrl""_thumb.png"
if [ $optimizeTool ]
then
eval nice -n 5 $optimizeTool "../cache/tmp/$hashUrl""_thumb.png" "../cache/tmp/$hashUrl.png" "../cache/tmp/$hashUrl""_complete.png" &>/dev/null
fi
mv "../cache/tmp/$hashUrl.png" "../cache/img/$startPath""$hashUrl.png"
mv "../cache/tmp/$hashUrl""_thumb.png" "../cache/img/$startPath""$hashUrl""_thumb.png"
mv "../cache/tmp/$hashUrl""_complete.png" "../cache/img/$startPath""$hashUrl""_complete.png"
if [[ -f "../cache/img/$startPath""$hashUrl""_thumb.png" && -f "../cache/img/$startPath""$hashUrl.png" && -f "../cache/img/$startPath""$hashUrl""_complete.png" ]]
then
echo 1
else
echo 0
fi
rm "../cache/tmp/$hashUrl.lock"
;;
esac
if $log
then
end_time=`date +%s`
logDate=`date +'[%a %d %b %Y] [%H:%M:%S]'`
echo $logDate `expr $end_time - $start_time`s >> '../cache/logs/success.txt'
fi

0
cache/index.html vendored
View file

View file

@ -1,5 +1,14 @@
{ {
"require": { "require": {
"embed/embed": "^3.3" "embed/embed": "^4.4.8",
"hassankhan/config": "^3.1",
"chrome-php/chrome": "^1.9",
"stefangabos/zebra_image": "^2.8.2",
"guzzlehttp/psr7": "^2.5"
},
"autoload": {
"psr-4": {
"App\\": "app/"
}
} }
} }

11
datas/config.default.json Normal file
View file

@ -0,0 +1,11 @@
{
"key": "",
"onlyLocalServer": true,
"webPage": false,
"log": true,
"alwaysMakePdf": false,
"permitType": [],
"expireCache": 12,
"maxGenPerBatch": 5,
"icoSize": 48
}

View file

@ -1,2 +0,0 @@
Allow from none
Deny from all

View file

@ -1,405 +0,0 @@
<?php
use Embed\Embed;
$acceptParam['log'] = array(
'suspect',
'success',
'other',
'retry',
);
if (isset($ui['pwd'])) {
checkAdmin($ui['pwd']);
}
if (isset($ui['log']) && !in_array($ui['log'], $acceptParam['log']) || $_SESSION['login'] !== true) {
die('Tell me, Mr Anderson, what good is a phone call if you\'re unable to speak ?');
}
if (empty($ui['log']) && empty($ui['ac'])) {
$ui['log'] = 'success';
}
function clearLog($log)
{
if (file_exists('cache/logs/' . $log . '.txt') && is_file('cache/logs/' . $log . '.txt')) {
file_put_contents('cache/logs/' . $log . '.txt', '');
}
}
function parseSuccessLog()
{
if (file_exists('cache/logs/success.txt')) {
$file = fopen('cache/logs/success.txt', "r");
$res = array();
if (!empty($file)) {
while (!feof($file)) {
$currentLine = trim(fgets($file));
$currentLine = explode(' ', $currentLine);
$currentLine = str_replace('s', '', $currentLine);
if (!empty($currentLine[5])) {
$res['genTime'][] = $currentLine[5];
}
}
} else {
$res['genTime'] = array();
}
fclose($file);
return $res;
}
}
function parseFailLog($log)
{
if (empty($log) || ($log !== 'suspect' && $log !== 'retry' && $log !== 'other')) {
die('Are you sure about this.');
}
$res = array();
$list = glob('cache/logs/' . $log . '/*.log');
if (!empty($list)) {
foreach ($list as $value) {
$line = file_get_contents($value);
$line = trim($line);
$line = explode(' --- ', $line);
if (!empty($line[7])) {
$res[] = array(
$line[1],
$line[2],
$line[4],
'Error ' . $line[7] . ' - ',
);
} else {
$res[] = array(
$line[1],
$line[2],
$line[4],
'',
);
}
}
}
return $res;
}
function parseFaviconLog($log)
{
if (empty($log) || ($log !== 'favicon')) {
die('Are you sure about this.');
}
$res = array();
$list = glob('cache/logs/' . $log . '/*.json');
if (!empty($list)) {
foreach ($list as $value) {
$res[] = json_decode(file_get_contents($value), true);
}
}
return $res;
}
function getInfoLog($hash)
{
$file = 'cache/logs/favicon/' . $hash . '.json';
if (file_exists($file)) {
$res = json_decode(file_get_contents($file), true);
} else {
$res = array();
}
return $res;
}
function manualGen($hash, $log)
{
$line = file_get_contents('cache/logs/' . $log . '/' . $hash . '.log');
$line = trim($line);
$line = explode(' --- ', $line);
$hash = sha1($GLOBALS['config']['salt'] . rawurldecode($line[1]));
file_put_contents('cache/tmp/manual.txt', $line[1]);
chdir('bin/');
exec('bash thumb_server.sh manual ' . escapeshellarg($hash) . ' ' . escapeshellarg($line[3]) . ' ' . escapeshellarg($line[4]) . ' trc 1', $result);
chdir('../');
if ((int) $result[0] == 1) {
$res['success'] = 1;
$res['filePath'] = pathForFile($line[4], $hash) . '.png';
$res['base64'] = 'data:image/png;base64,' . base64_encode(file_get_contents($res['filePath']));
} else {
$res['error'] = 1;
$res['msg'] = 'Can\'t generate thumbshot manualy, try curl method.';
}
return $res;
}
function delAndRegen($hash, $size)
{
$path = pathForFile($size, $hash);
if (file_exists($path . '.png')) {
unlink($path . '.png');
}
if (file_exists($path . '_thumb.png')) {
unlink($path . '_thumb.png');
}
if (file_exists($path . '_complete.png')) {
unlink($path . '_complete.png');
}
}
function tryRootDomain($hash, $log)
{
$line = file_get_contents('cache/logs/' . $log . '/' . $hash . '.log');
$line = trim($line);
$line = explode(' --- ', $line);
$hash = sha1($GLOBALS['config']['salt'] . rawurldecode($line[1]));
$parts = parse_url($line[1]);
$url = $parts['scheme'] . '://' . trim($parts['host']);
file_put_contents('cache/tmp/manual.txt', $url);
chdir('bin/');
exec('bash thumb_server.sh manual ' . escapeshellarg($hash) . ' ' . escapeshellarg($line[3]) . ' ' . escapeshellarg($line[4]) . ' trc 1', $result);
chdir('../');
if ((int) $result[0] === 1) {
$res['success'] = 1;
$res['filePath'] = pathForFile($line[4], $hash) . '.png';
$res['base64'] = 'data:image/png;base64,' . base64_encode(file_get_contents($res['filePath']));
return $res;
} else {
$res['error'] = 1;
$res['msg'] = 'Error with root domain';
return $res;
}
}
function keepThisThumb($hash, $log, $favicon = false)
{
if ($favicon === true) {
unlink('cache/logs/' . $log . '/' . $hash . '.json');
} else {
unlink('cache/logs/' . $log . '/' . $hash . '.log');
}
}
function tryWithCurl($hash, $log)
{
$line = file_get_contents('cache/logs/' . $log . '/' . $hash . '.log');
$line = trim($line);
$line = explode(' --- ', $line);
//$hash = sha1($GLOBALS['config']['salt'].rawurldecode($line[1]));
$line[1] = iconv(mb_detect_encoding($line[1], mb_detect_order(), true), "UTF-8", $line[1]);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $line[1]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'SoShot - perSOnal thumbSHOTer');
$resultat = curl_exec($ch);
curl_close($ch);
$searchStr = array(
'href="//',
'src="//',
'content="//',
);
$replaceStr = array(
'href="http://',
'src="http://',
'content="http://',
);
$resultat = str_replace($searchStr, $replaceStr, $resultat);
file_put_contents('cache/tmp/' . $line[2] . '.html', $resultat);
chdir('bin/');
exec('bash thumb_server.sh ../cache/tmp/' . $hash . '.html ' . escapeshellarg($line[2]) . ' ' . escapeshellarg($line[3]) . ' ' . escapeshellarg($line[4]) . ' trc 1 noErrorLog', $result);
chdir('../');
unlink('cache/tmp/' . $hash . '.html');
if (file_exists(pathForFile($line[4], $hash) . '.png')) {
$res['success'] = 1;
$res['filePath'] = pathForFile($line[4], $hash) . '.png';
$res['base64'] = 'data:image/png;base64,' . base64_encode(file_get_contents($res['filePath']));
return $res;
} else {
$res['error'] = 1;
$res['msg'] = 'Error with curl' . n_print($result);
return $res;
}
}
function tryWithOpenGraph($hash, $log)
{
require_once 'vendor/autoload.php';
$line = file_get_contents('cache/logs/' . $log . '/' . $hash . '.log');
$line = trim($line);
$line = explode(' --- ', $line);
$url = $line[1];
$startPath = '';
$url = iconv(mb_detect_encoding($line[1], mb_detect_order(), true), "UTF-8", $url);
$info = Embed::create($url);
$ext = testIfImg($info->image);
if ($ext !== false) {
$original = file_get_contents($info->image);
file_put_contents('cache/tmp/' . $hash . '.' . $ext, $original);
$res['success'] = 1;
$res['filePath'] = 'cache/tmp/' . $hash . '.' . $ext;
$res['base64'] = 'data:image/png;base64,' . base64_encode($original);
unlink('cache/tmp/' . $hash . '.' . $ext);
$startPath = 'cache/img/' . $line[4] . '/' . substr($hash, 0, 2) . '/' . substr($hash, 2, 2) . '/';
$width = explode("x", $line[3]);
$thumb = makeImgThumb($info->image, $ext, $hash, $width[0], $startPath);
return $res;
} else {
$res['error'] = 1;
$res['msg'] = 'Error with OpenGraph data';
$res['base64'] = 'data:image/png;base64,' . base64_encode(file_get_contents('bin/error.png'));
return $res;
}
}
if (isset($ui['clear']) && (int) $ui['clear'] === 1) {
clearLog($ui['log']);
}
if (isset($ui['ac']) && $ui['ac'] === 'delete' && isset($ui['thumb']) && !empty($ui['thumb'])) {
$imgUrl = pathForFile('m', $ui['thumb']);
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $imgUrl . '.png')) {
unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $imgUrl . '.png');
}
if (file_exists($imgUrl . '_thumb.png')) {
unlink($_SERVER['DOCUMENT_ROOT'] . '/' . $imgUrl . '_thumb.png');
}
}
echo '<div class="hMenu">
<ul>
<li>
<a href="?p=admin&log=success">Success</a>
</li>
<li>
<a href="?p=admin&log=suspect">Suspect</a>
</li>
<li>
<a href="?p=admin&log=retry">Retry</a>
</li>
<li>
<a href="?p=admin&log=other">Other error</a>
</li>
<li>
<a href="?p=admin&ac=delete">Delete thumbshot</a>
</li>
<li>
<a href="?logout=1">Logout</a>
</li>
</ul>
</div>
<div id="log">';
if (isset($ui['ac']) && $ui['ac'] === 'delete') {
if (!empty($ui['delThumb']) && $ui['delThumb']) {
delAndRegen($ui['delThumb'], $size);
}
if (isset($ui['deleteUrl']) && testValidUrl($ui['deleteUrl']) !== true) {
unset($ui['deleteUrl']);
echo '<div>Not a valid url.</div>';
}
echo '
<form method="post" action="?">
<p>
<label>Url </label>';
if (empty($ui['deleteUrl'])) {
echo '<input type="text" name="deleteUrl"/>';
} else {
echo '<input type="text" name="deleteUrl" value="', $ui['deleteUrl'], '"/>';
}
echo '</p>
<p>
<input type="hidden" name="p" value="admin"/>
<input type="hidden" name="ac" value="delete"/>
<input type="submit"/>
</p>
</form>';
if (!empty($ui['deleteUrl'])) {
$ui['deleteUrl'] = trim(rawurldecode($ui['deleteUrl']));
$ui['deleteUrl'] = rtrim($ui['deleteUrl'], '/');
$hashUrl = sha1($GLOBALS['config']['salt'] . $ui['deleteUrl']);
$imgUrl = pathForFile('', $hashUrl);
echo '</div>
<div id="result">
<p>
<a href="', $imgUrl, '.png"><img src="', $imgUrl, '_thumb.png"/></a>
</p>
<a href="?p=admin&amp;ac=delete&amp;delThumb=', $hashUrl, '">Delete this thumb</a>
</div>';
}
}
if (isset($ui['log']) && $ui['log'] === 'success') {
$logs = parseSuccessLog();
createDir();
if (!empty($logs)) {
$nbThumb = 0;
$nbThumb = count($logs['genTime']);
echo 'Total request : ', $nbThumb, '</br>';
echo 'Moyenne per request : ', round(array_sum($logs['genTime']) / $nbThumb, 2), 's (min (', min($logs['genTime']), 's) max (', max($logs['genTime']), 's))</br>';
} else {
echo 'No result';
}
echo '<p class="clear" ><a href="?p=admin&log=success&clear=1">Clear success log</a></p>';
}
if (isset($ui['log']) && ($ui['log'] === 'suspect' || $ui['log'] === 'retry' || $ui['log'] === 'other')) {
if (isset($ui['hash']) && !empty($ui['hash'])) {
//$ui['hash'] = validHash($ui['hash']);
if (isset($ui['root']) && (int) $ui['root'] === 1) {
$response = tryRootDomain($ui['hash'], $ui['log']);
}
if (isset($ui['cache']) && (int) $ui['cache'] === 1) {
$response['success'] = 1;
$response['filePath'] = pathForFile($ui['s'], $ui['hash']) . '.png';
if(file_exists($response['filePath'])){
$file = file_get_contents($response['filePath']);
} else {
$file = file_get_contents('bin/error.png');
}
$response['base64'] = 'data:image/png;base64,' . base64_encode($file);
if (!file_exists($response['filePath'])) {
$response['base64'] = 'data:image/png;base64,' . base64_encode(file_get_contents('bin/error.png'));
}
}
if (isset($ui['keep']) && (int) $ui['keep'] === 1) {
keepThisThumb($ui['hash'], $ui['log']);
}
if (isset($ui['mGen']) && (int) $ui['mGen'] === 1) {
$response = manualGen($ui['hash'], $ui['log']);
}
if (isset($ui['tryCurl']) && (int) $ui['tryCurl'] === 1) {
$response = tryWithCurl($ui['hash'], $ui['log']);
}
if (isset($ui['openGraph']) && (int) $ui['openGraph'] === 1) {
$response = tryWithOpenGraph($ui['hash'], $ui['log']);
}
}
$logs = parseFailLog($ui['log']);
if (!empty($logs)) {
echo '<ul>';
foreach ($logs as $value) {
echo '<li>', htmlentities(strip_tags($value['3'])), htmlentities(strip_tags($value['0'])), '</br><a href="?p=admin&log=', $ui['log'], '&hash=', $value['1'], '&mGen=1#result">manuel launch</a> <a href="', htmlentities(strip_tags($value['0'])), '">view site</a> <a href="?p=admin&log=', $ui['log'], '&hash=', $value['1'], '&cache=1&s=', $value['2'], '#result">view image in cache</a></li>';
}
echo '</ul>';
} else {
echo 'No result';
}
}
echo '</div>';
if (!empty($response) && !empty($response['success']) && $response['success'] === 1) {
echo '<div id="result">';
echo '<img src="', $response['base64'], '" style="max-width:100%;"/>';
echo '<p><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $response['filePath'], '" onclick="this.select()"/></p>';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&mGen=1#result">Manuel launch</a> / ';
if (extension_loaded("curl")) {
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&tryCurl=1#result">Try with curl</a> / ';
}
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&root=1#result">Try with root domain</a> / ';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&openGraph=1#result">Try with OpenGraph</a> / ';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&keep=1#result">Keep this thumbshot</a>';
echo '</div>';
} elseif (!empty($response) && !empty($response['error']) && $response['error'] === 1) {
echo '<div id="result">';
echo '<p>', $response['msg'], '</p>';
echo '<p><img src="', $response['base64'], '" style="max-width:100%;"/></p>';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&mGen=1#result">Manuel launch</a> / ';
if (extension_loaded("curl")) {
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&tryCurl=1#result">Try with curl</a> / ';
}
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&root=1#result">Try with root domain</a> / ';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&openGraph=1#result">Try with OpenGraph</a> / ';
echo '<a href="?p=admin&log=', $ui['log'], '&hash=', $ui['hash'], '&keep=1#result">Keep this thumbshot</a>';
echo '</div>';
}

View file

@ -1,46 +0,0 @@
<form method="post">
<p>
<input type="url" placeholder="<?php echo $defUrl; ?>" value="<?php echo $defUrl; ?>" name="url"/>
</p>
<p>
<label>Size</label>
<select name="s">
<?php
foreach ($GLOBALS['config']['thumbSize'] as $key => $value) {
if ($value === $width) {
echo '<option value="', $key, '" selected="selected">', $value, '</option>';
} else {
echo '<option value="', $key, '">', $value, '</option>';
}
}
?>
</select>
</p>
<p>
<label>Force refresh</label>
<input type="checkbox" value="1" name="fr" />
</p>
<p>
<input type="hidden" name="token" value="<?php echo genToken(); ?>" />
<input type="submit" value="Generate"/>
</p>
<p class="info">
<a href="http://forge.leslibres.org/projects/soshot">Homepage</a> <a href="http://knah-tsaeb.org/contact-page/">Contact</a>
</p>
</form>
<?php
if (!empty($success)) {
echo '<div id="result">';
echo '<h3>This image will be removed in ', $GLOBALS['config']['expireCache'], 'h</h3>';
echo '<img src="data:image/png;base64,',base64_encode(file_get_contents($success['favicon'])), '"/><br/>';
echo '<img src="data:image/png;base64,',base64_encode(file_get_contents($success['thumb'])), '"/>';
echo '<p><label>Thumbshot</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['thumb'], '" onclick="this.select()"/>';
if ($GLOBALS['config']['activeFullSize'] === true) {
echo '<p><label>1280x1024</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['normal'], '" onclick="this.select()"/></p>';
}
if ($GLOBALS['config']['activeComplete'] === true) {
echo '<p><label>Complete</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['complete'], '" onclick="this.select()"/></p>';
}
echo '<p><label>Favicon</label><input type="text" value="http://', $_SERVER['SERVER_NAME'], '/', $success['favicon'], '" onclick="this.select()"/></p>';
echo '</div>';
}

View file

@ -1,32 +0,0 @@
<?php
if(file_exists('cache/config/genConf.php') && $GLOBALS['config']['pwd'] !== 'install'){
die ('Seriously Dude, Where\'s My Car ?');
}
if(isset($ui['passOne'])){
savePass($ui['passOne'], $ui['passTwo'], $ui['token']);
}
?>
<div class="message">
This is the key for generate thumbnail whith GET method. Save it !
<p class="alert">
<?php
echo $serverKey;
?>
</p>
</div>
<form action="?" method="post">
<p>
<label>Password</label>
<input type="password" name="passOne" />
</p>
<p>
<label>Confirm</label>
<input type="password" name="passTwo" />
</p>
<p>
<input type="hidden" name="token" value="<?php echo genToken();?>"/>
<input type="hidden" name="p" value="install"/>
<input type="submit">
</p>
</form>

View file

@ -1,11 +0,0 @@
<form action="?" method="post">
<p>
<label>Password</label>
<input type="password" name="pwd" />
</p>
<p>
<input type="hidden" name="token" value="<?php echo genToken();?>"/>
<input type="hidden" name="p" value="admin" />
<input type="submit">
</p>
</form>

788
index.php
View file

@ -1,788 +0,0 @@
<?php
use Embed\Embed;
session_start();
if (empty($_SESSION['login'])) {
$_SESSION['login'] = false;
}
// change if you want no inpact
date_default_timezone_set('Europe/Paris');
// soshot only accept request by 127.0.0.1
$GLOBALS['config']['onlyLocalServer'] = false;
// No form for post url only acces by GET method
$GLOBALS['config']['NoWebPage'] = false;
// After 3 critical error ban user
$GLOBALS['config']['maxErrorBeforeBan'] = 3;
// Ban for 60 minutes
$GLOBALS['config']['banTime'] = 60;
// default url for form
$GLOBALS['config']['defaultUrl'] = 'https://duckduckgo.com/';
// default size for thumbnail
$GLOBALS['config']['defaultThumbSize'] = '120x90';
// list of available size for thumb
$GLOBALS['config']['thumbSize'] = array(
's' => '120x90',
'm' => '200x160',
'l' => '300x240',
'xl' => '400x320',
'xxl' => '500x400',
);
// create thumshot 1280x1024
$GLOBALS['config']['activeFullSize'] = false;
// create thumbshot of complete page
$GLOBALS['config']['activeComplete'] = false;
// create favicon
$GLOBALS['config']['favicon'] = false;
// Remove image older than 12 hours
$GLOBALS['config']['expireCache'] = 12;
// Disable exec command and use cron task
$GLOBALS['config']['disableExec'] = false;
// Enable log for success, suspect, error
$GLOBALS['config']['log'] = true;
if (file_exists('cache/config/options.php')) {
require 'cache/config/options.php';
}
if (!empty($_POST)) {
$ui = $_POST;
$ui['request'] = 'form';
$ui['iw'] = 1;
unset($_POST);
}
if (!empty($_GET)) {
$ui = $_GET;
$ui['request'] = 'api';
unset($_GET);
}
if (empty($ui['request'])) {
$ui['request'] = '';
}
if (empty($ui['p'])) {
$ui['p'] = 'index';
}
if (empty($ui['fr'])) {
$ui['fr'] = '';
}
if (empty($ui['t'])) {
$ui['t'] = 't';
}
if (isset($ui['logout']) && (int) $ui['logout'] === 1) {
session_destroy();
header("Location:?");
exit();
}
if (!file_exists('cache/config/genConf.php')) {
$serverKey = install();
$ui['p'] = 'install';
}
require 'cache/config/genConf.php';
if ($GLOBALS['config']['pwd'] === 'install' && $ui['p'] !== 'install') {
reloadInstall();
header("Location:?");
}
if (($GLOBALS['config']['onlyLocalServer'] === true && $_SERVER['REMOTE_ADDR'] !== '127.0.0.1') || checkIfBan() === true) {
header("HTTP/1.0 404 Not Found");
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
exit();
}
if ($GLOBALS['config']['NoWebPage'] === true && empty($_GET)) {
header("HTTP/1.0 404 Not Found");
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
exit();
}
function testExistImg($file, $type)
{
/*
type :
- c complete
- r full
- thumbnail
- fav favicon
*/
switch ($type) {
case 'c':
if (file_exists($file . '_complete.png')) {
return true;
}
break;
case 'r':
if (file_exists($file . '_full.png')) {
return true;
}
break;
case 'fav':
if (file_exists($file . '_favicon.png')) {
return true;
}
break;
case 't':
if (file_exists($file . '_thumb.png')) {
return true;
}
break;
default:
return false;
break;
}
return false;
}
/**
* Run the bash script for generate thumbnail
*
* @author Knah Tsaeb
* @date 2013-02-12
* @param $url (string) url for thumbshot
* @param $hashUrl (hash) hash($url)
* @param $width (string) size of thumbnail 190x90
* @param $onlyThumb (bool)
* @param $waitForResult (bool)
* @return
*/
function launchScript($url, $hashUrl, $width, $size, $waitForResult = false)
{
$oriHash = $hashUrl;
$hashUrl = escapeshellarg($hashUrl);
$url = escapeshellarg($url);
$width = escapeshellarg($width);
if ($GLOBALS['config']['activeFullSize'] && $GLOBALS['config']['activeComplete']) {
$renderType = 'trc';
} elseif ($GLOBALS['config']['activeFullSize']) {
$renderType = 'tr';
} elseif ($GLOBALS['config']['activeComplete']) {
$renderType = 'tc';
} else {
$renderType = 't';
}
if ($GLOBALS['config']['disableExec'] === false) {
if (!file_exists('cache/tmp/' . $oriHash . '.lock')) {
touch('cache/tmp/' . $oriHash . '.lock');
chdir('bin/');
if ($waitForResult === false) {
exec('bash thumb_server.sh ' . $url . ' ' . $hashUrl . ' ' . $width . ' ' . $size . ' ' . $renderType . ' > /dev/null &', $result);
} else {
exec('bash thumb_server.sh ' . $url . ' ' . $hashUrl . ' ' . $width . ' ' . $size . ' ' . $renderType . ' 1', $result);
}
chdir('../');
} else {
return 0;
}
} else {
makeQueueFile($url, $hashUrl, $width, $size, $renderType);
$result = 0;
}
return $result;
}
function makeQueueFile($url, $hashUrl, $width, $size, $renderType)
{
$url = str_replace('\'', '', $url);
$hashUrl = str_replace('\'', '', $hashUrl);
$width = str_replace('\'', '', $width);
if (!file_exists('cache/cronTask/' . $hashUrl . '.hash')) {
$data = $url . ' ' . $hashUrl . ' ' . $width . ' ' . $size . ' ' . $renderType . "\n";
file_put_contents('cache/cronTask/' . $hashUrl . '.hash', $data);
}
}
function testValidUrl($url)
{
$url = trim($url);
if (filter_var($url, FILTER_VALIDATE_URL)) {
$url = parse_url($url);
if (!in_array($url['scheme'], array(
'http',
'https',
))) {
return array('msg' => 'Url must be start by http or https.');
}
return true;
} else {
return array('msg' => 'Not a valid url.');
}
}
function genToken()
{
$token = sha1(uniqid(rand(), true) . '_' . mt_rand());
$_SESSION['token'] = $token;
$_SESSION['tokenTime'] = time();
return $token;
}
function verifToken($token)
{
if ($token !== $_SESSION['token'] || $_SESSION['tokenTime'] <= time() - 24000) {
ban();
die('So Long, and Thanks for All the Fish.');
}
}
function checkIfBan()
{
require 'cache/logs/banUser.php';
$userIp = $_SERVER['REMOTE_ADDR'];
if (isset($banList[$userIp]) && $banList[$userIp]['nbBan'] >= $GLOBALS['config']['maxErrorBeforeBan'] && $banList[$userIp]['lastBan'] + $GLOBALS['config']['banTime'] > time()) {
return true;
} elseif (isset($banList[$userIp]) && $banList[$userIp]['lastBan'] + $GLOBALS['config']['banTime'] < time()) {
unban();
return false;
} else {
return false;
}
}
function ban()
{
require 'cache/logs/banUser.php';
$userIp = $_SERVER['REMOTE_ADDR'];
if (isset($banList[$userIp])) {
$banList[$userIp]['lastBan'] = time();
$banList[$userIp]['nbBan']++;
} else {
$banList[$userIp]['lastBan'] = time();
$banList[$userIp]['nbBan'] = 1;
}
file_put_contents('cache/logs/banUser.php', "<?php\n\$banList=" . var_export($banList, true) . ";\n?>");
}
function unBan()
{
require 'cache/logs/banUser.php';
$userIp = $_SERVER['REMOTE_ADDR'];
unset($banList[$userIp]);
file_put_contents('cache/logs/banUser.php', "<?php\n\$banList=" . var_export($banList, true) . ";\n?>");
}
function createDir()
{
if (!is_writable('cache')) {
die('Make dir "cache" writable');
}
if (!is_dir('cache/config') && !mkdir('cache/config', 0705)) {
die('Error on create dir "cache/config".');
}
if (!is_dir('cache/img') && !mkdir('cache/img', 0705)) {
die('Error on create dir "cache/img".');
}
if (!is_dir('cache/logs') && !mkdir('cache/logs', 0705)) {
die('Error on create dir "cache/logs".');
}
if (!is_dir('cache/logs/suspect') && !mkdir('cache/logs/suspect', 0705)) {
die('Error on create dir "cache/logs/suspect".');
}
if (!is_dir('cache/logs/retry') && !mkdir('cache/logs/retry', 0705)) {
die('Error on create dir "cache/logs/retry".');
}
if (!is_dir('cache/logs/other') && !mkdir('cache/logs/other', 0705)) {
die('Error on create dir "cache/logs/other".');
}
if (!is_dir('cache/tmp') && !mkdir('cache/tmp', 0705)) {
die('Error on create dir "cache/tmp".');
}
if (!is_dir('cache/cronTask') && !mkdir('cache/cronTask', 0705)) {
die('Error on create dir "cache/cronTask".');
}
}
function install()
{
createDir();
$salt = sha1(uniqid(rand(), true) . '_' . mt_rand());
$serverKey = substr(sha1(uniqid(rand(), true) . '_' . mt_rand() . $salt), 0, 12);
$encryptServerKey = sha1($serverKey . $salt);
if (!is_file('cache/config/genConf.php')) {
file_put_contents('cache/config/genConf.php', "
<?php
\$GLOBALS['config']['serverKey'] = '$encryptServerKey';
\$GLOBALS['config']['salt'] = '$salt';
\$GLOBALS['config']['pwd'] = 'install';
\$GLOBALS['config']['apikey'] = '$serverKey';
?>");
}
if (!is_file('cache/config/serverOptions.php')) {
touch('cache/config/serverOptions.php');
}
if (!is_file('cache/index.html')) {
touch('cache/index.html');
}
if (!is_file('cache/config/options.php')) {
file_put_contents('cache/config/options.php', "<?php\n\n?>");
}
if (!is_file('cache/logs/banUser.php')) {
file_put_contents('cache/logs/banUser.php', "<?php\n\n?>");
}
$GLOBALS['config']['serverKey'] = $encryptServerKey;
$GLOBALS['config']['salt'] = $salt;
$GLOBALS['config']['pwd'] = 'install';
$GLOBALS['config']['apikey'] = $serverKey;
return $serverKey;
}
function checkInstall()
{
if (!is_file('.htaccess')) {
file_put_contents('.htaccess', "AddDefaultCharset UTF-8\nOptions -Indexes\nDirectoryIndex index.php index.html\nFileETag none\nSetOutputFilter DEFLATE\n");
}
if (!is_file('cache/logs/.htaccess')) {
file_put_contents('cache/logs/.htaccess', "Allow from none\nDeny from all\n");
}
if (!is_file('cache/config/.htaccess')) {
file_put_contents('cache/config/.htaccess', "Allow from none\nDeny from all\n");
}
if (!is_file('cache/cronTask/.htaccess')) {
file_put_contents('cache/config/.htaccess', "Allow from none\nDeny from all\n");
}
if (!is_file('bin/.htaccess')) {
file_put_contents('bin/.htaccess', "Allow from none\nDeny from all\n");
}
}
function removeOlderThan($dir = 'cache/img/shortLive')
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object !== '.' && $object !== '..' && $object) {
if (filetype($dir . '/' . $object) === 'dir') {
removeOlderThan($dir . '/' . $object);
} else {
if (fileatime($dir . '/' . $object) < time() - 3600 * $GLOBALS['config']['expireCache']) {
unlink($dir . '/' . $object);
}
}
}
}
reset($objects);
}
}
function pathForFile($size, $hashUrl)
{
$startPath = substr($hashUrl, 0, 2) . '/' . substr($hashUrl, 2, 2) . '/';
if (empty($size)) {
$size = tryDetectSize($startPath . $hashUrl);
}
$file = 'cache/img/' . $size . '/' . $startPath . $hashUrl;
return $file;
}
function tryDetectSize($file)
{
if (is_file('cache/img/s/' . $file . '_thumb.png')) {
return 's';
}
if (is_file('cache/img/m/' . $file . '_thumb.png')) {
return 'm';
}
if (is_file('cache/img/l/' . $file . '_thumb.png')) {
return 'l';
}
if (is_file('cache/img/xl/' . $file . '_thumb.png')) {
return 'xl';
}
if (is_file('cache/img/xxl/' . $file . '_thumb.png')) {
return 'xxl';
}
}
function validHash($hash)
{
if (empty($hash)) {
die('You talking to me');
}
if (!preg_match('/^[0-9a-f]{40}$/i', $hash)) {
die('I don\'t understand biiip bip bip biiiip bip bip bip biiiiiiip biip ...');
}
return $hash;
}
function checkAdmin($pwd)
{
$pwd = sha1($GLOBALS['config']['salt'] . $pwd . $GLOBALS['config']['serverKey']);
if (validHash($pwd) !== $GLOBALS['config']['pwd']) {
ban();
die('1, 2, 3, 4, 5 ? That\'s amazing ! I\'ve got the same combination on my luggage !');
}
$_SESSION['login'] = true;
return true;
}
function savePass($passOne, $passTwo, $token)
{
verifToken($token);
if ($passOne !== $passTwo || empty($passOne) || empty($passTwo)) {
reloadInstall();
} else {
$GLOBALS['config']['pwd'] = sha1($GLOBALS['config']['salt'] . $passOne . $GLOBALS['config']['serverKey']);
$confServerKey = $GLOBALS['config']['serverKey'];
$confSalt = $GLOBALS['config']['salt'];
$confPwd = $GLOBALS['config']['pwd'];
$apikey = $GLOBALS['config']['apikey'];
$confFile = '
<?php
$GLOBALS[\'config\'][\'serverKey\'] = \'' . $confServerKey . '\';
$GLOBALS[\'config\'][\'salt\'] = \'' . $confSalt . '\';
$GLOBALS[\'config\'][\'pwd\'] = \'' . $confPwd . '\';
$GLOBALS[\'config\'][\'apikey\'] = \'' . $apikey . '\';
?>';
file_put_contents('cache/config/genConf.php', $confFile);
}
header("Location:?");
}
function reloadInstall()
{
array_map('unlink', glob("cache/config/*"));
}
/**
* Améliore la sortie print
*
* @author Tatane http://www.tatane.info/index.php/print_rn
* @author http://www.blog.cactuscrew.com/77-print_rn.html
* @param $data (array) tableau ou variable à examiner
* @param $name (string) nom a afficher
* @return false affiche les clef valeur du tableau $data
* @example n_print($array, 'Tableau de valeur');
*/
function n_print($data, $name = '')
{
$aBackTrace = debug_backtrace();
echo '<h2>', $name, '</h2>';
echo '<fieldset style="border: 1px solid orange; padding: 5px;color: #333; background-color: #fff;">';
echo '<legend style="border:1px solid orange;padding: 1px;background-color:#eee;color:orange;">
', basename($aBackTrace[0]['file']), ' ligne => ', $aBackTrace[0]['line'], '
</legend>';
echo '<pre>', htmlentities(print_r($data, 1)), '</pre>';
echo '
</fieldset>
<br />
';
}
function printThumbShot($file, $renderType)
{
ob_end_clean();
header("Content-type: image/png");
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
switch ($renderType) {
case 'c':
echo file_get_contents($file . '_complete.png');
break;
case 'r':
echo file_get_contents($file . '.png');
break;
case 'fav':
echo file_get_contents($file . '_favicon.png');
break;
default:
echo file_get_contents($file . '_thumb.png');
break;
}
exit();
}
function getPage($page)
{
$page = htmlspecialchars($page);
switch ($page) {
case 'login':
return 'inc/login.php';
break;
case 'install':
return 'inc/install.php';
break;
case 'admin':
return 'inc/admin.php';
break;
default:
return 'inc/index.php';
break;
}
}
function testIfImg($url)
{
$ext = strtolower(pathinfo(strtok($url, '?'), PATHINFO_EXTENSION));
if ($ext === 'jpg' || $ext === 'jpeg' || $ext === 'png' || $ext === 'gif' || $ext === 'ico') {
return $ext;
} else {
return false;
}
}
function makeImgThumb($url, $ext, $hashUrl, $width, $path, $renderType = null)
{
if (!function_exists('imagecreatefromjpeg')) {
return false;
}
$image = file_get_contents($url);
$fullSize = file_put_contents('cache/tmp/' . $hashUrl . '.' . $ext, $image);
if ($ext === 'jpg' || $ext === 'jpeg') {
$tmpImg = imagecreatefromjpeg('cache/tmp/' . $hashUrl . '.' . $ext);
}
if ($ext === 'png') {
$tmpImg = imagecreatefrompng('cache/tmp/' . $hashUrl . '.' . $ext);
}
if ($ext === 'gif') {
$tmpImg = imagecreatefromgif('cache/tmp/' . $hashUrl . '.' . $ext);
}
if (!$tmpImg) {
unlink('cache/tmp/' . $hashUrl . '.' . $ext);
return false;
}
$w = imagesx($tmpImg);
$h = imagesy($tmpImg);
$ystart = 0;
$yheight = $h;
if ($h > $w) {$ystart = ($h / 2) - ($w / 2);
$yheight = $w / 2;
}
$nh = min(floor(($h * $width) / $w), $width);
$im2 = imagecreatetruecolor($width, $nh);
imagecopyresampled($im2, $tmpImg, 0, 0, 0, $ystart, $width, $nh, $w, $yheight);
$tempname = 'cache/tmp/' . $hashUrl . '_TEMP.png';
imagepng($im2, $tempname, 9);
if (!is_dir($path)) {
mkdir($path, 0775, true);
}
imagedestroy($tmpImg);
imagedestroy($im2);
unlink('cache/tmp/' . $hashUrl . '.' . $ext);
rename($tempname, $path . $hashUrl . '_thumb.png');
if (file_exists($path . $hashUrl . '_thumb.png')) {
return true;
} else {
return false;
}
}
function checkHmac($receiveHmac, $url)
{
if ($receiveHmac === makeHmac($url, $GLOBALS['config']['apikey'])) {
return true;
} else {
return false;
}
}
function makeHmac($url)
{
return hash_hmac('sha1', $url, $GLOBALS['config']['apikey']);
}
function makeHashPath($hashUrl)
{
return substr($hashUrl, 0, 2) . '/' . substr($hashUrl, 2, 2);
}
function makeFavicon($hash, $url, $filePath)
{
require_once 'vendor/autoload.php';
$resResize = '';
$data = array();
$data['hashPath'] = $hashPath = $filePath;
$data['file'] = $file = $filePath . $hash . '_favicon.png';
$info = Embed::create($url, [
'follow_canonical' => true,
'external_images' => true,
]);
$faviconUrl = $info->providerIcon;
$data['ext'] = testIfImg($faviconUrl);
$data['favicon'] = $faviconUrl;
$image = file_get_contents($faviconUrl);
$fullSize = file_put_contents('cache/tmp/' . $hash . '.' . $data['ext'], $image);
$tmpFile = 'cache/tmp/' . $hash . '.' . $data['ext'];
if ($data['ext'] === 'ico') {
$getBestSize = exec('identify ' . escapeshellarg($tmpFile), $originalFav);
if (is_array($originalFav)) {
end($originalFav);
$key = key($originalFav);
if (!is_dir($hashPath)) {
mkdir($hashPath, 0700, true);
}
exec('convert -background transparent ' . escapeshellarg($tmpFile . '[' . $key . ']') . ' -resize x32 ' . $file, $resResize);
unlink('cache/tmp/' . $hash . '.' . $data['ext']);
}
} else {
if (!is_dir($hashPath)) {
mkdir($hashPath, 0700, true);
}
exec('convert -background transparent ' . escapeshellarg($tmpFile) . ' -resize x32 ' . $file, $resResize);
unlink('cache/tmp/' . $hash . '.' . $data['ext']);
}
if (file_exists($file)) {
return $file;
} else {
file_put_contents($file, file_get_contents('bin/error_fav.png'));
return $file;
}
}
function makeHashUrl($url)
{
return sha1($GLOBALS['config']['salt'] . $url);
}
/*
$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //save the image on your server
*
*
*/
checkInstall();
removeOlderThan();
if (empty($defUrl)) {
$defUrl = $GLOBALS['config']['defaultUrl'];
}
if (isset($ui['s']) && array_key_exists($ui['s'], $GLOBALS['config']['thumbSize'])) {
$width = $GLOBALS['config']['thumbSize'][$ui['s']];
} else {
$width = $GLOBALS['config']['defaultThumbSize'];
}
// Generate or return img
if (!empty($ui['request']) && $ui['p'] !== 'install' && $ui['p'] !== 'login' && $ui['p'] !== 'admin') {
if (empty($ui['url'])) {
die('You see in this world there\'s two kinds of people, my friend. Those with loaded guns, and those who dig. You dig.');
}
if ($ui['request'] === 'form') {
//$file = 'cache/img/shortLive/' . $startPath . $hashUrl;
$ui['s'] = 'shortLive';
}
$ui['sendUrl'] = $ui['url'];
$ui['url'] = trim(rawurldecode($ui['url']));
$ui['url'] = rtrim($ui['url'], '/');
$hashUrl = sha1($GLOBALS['config']['salt'] . $ui['url']);
$startPath = substr($hashUrl, 0, 2) . '/' . substr($hashUrl, 2, 2) . '/';
$filePath = 'cache/img/' . $ui['s'] . '/' . $startPath;
$file = 'cache/img/' . $ui['s'] . '/' . $startPath . $hashUrl;
$testUrl = testValidUrl($ui['url']);
$defUrl = $ui['url'];
// file exist we return img
if (testExistImg($file, $ui['t']) === true && (int) $ui['fr'] !== 1) {
if ($ui['request'] === 'api') {
if (checkHmac($ui['hm'], $ui['sendUrl'])) {
printThumbShot($file, $ui['t']);
} else {
ban();
die('I take a chips and give it to Godzilla. I give high kick in Chuck Norris face and I go to ... Humm .... Ehh .... Arg ....... KAMOULOX ! Well done Jean Pierre.');
}
}
if ($ui['request'] === 'form') {
$success = array(
'normal' => $file . '.png',
'thumb' => $file . '_thumb.png',
'complete' => $file . '_complete.png',
'favicon' => $file . '_favicon.png',
);
}
} else {
if ($ui['request'] === 'api') {
if (empty($ui['hm']) || empty($ui['hm'])) {
die('Are you Ken ?');
}
if (!checkHmac($ui['hm'], $ui['sendUrl'])) {
ban();
die('I take a chips and give it to Godzilla. I give high kick in Chuck Norris face and I go to ... Humm .... Ehh .... Arg ....... KAMOULOX ! Well done Jean Pierre.');
}
} else {
verifToken($ui['token']);
}
// url isn't correct put it in suspect log
if ($testUrl !== true) {
if (!file_exists('cache/logs/' . $hashUrl . 'log')) {
file_put_contents('cache/logs/suspect/' . $hashUrl . '.log', $_SERVER['REMOTE_ADDR'] . ' --- ' . $ui['url'] . ' --- ' . $hashUrl . ' --- ' . $width . ' --- ' . $ui['s'] . ' --- ' . $renderType . ' --- true' . "\n");
}
if ($ui['request'] === 'api') {
printThumbShot('bin/error', $ui['t']);
} else {
$success = array(
'normal' => 'bin/error.png',
'thumb' => 'bin/error_thumb.png',
'complete' => 'bin/error.png',
'favicon' => 'bin/error_fav.png',
);
}
} else {
$ext = testIfImg($ui['url']);
if ($ext !== false) {
$genWidth = explode("x", $width);
if ($ui['request'] === 'api') {
$makeImg = makeImgThumb($ui['url'], $ext, $hashUrl, $genWidth[0], 'cache/img/' . $ui['s'] . '/' . $startPath, $ui['t']);
} else {
$makeImg = makeImgThumb($ui['url'], $ext, $hashUrl, $genWidth[0], 'cache/img/shortLive/' . $startPath, $ui['t']);
}
if ($makeImg === true) {
//
$GLOBALS['config']['disableExec'] = true;
if ($ui['request'] === 'api') {
printThumbShot($file, $ui['t']);
} else {
$success = array(
'normal' => $file . '.png',
'thumb' => $file . '_thumb.png',
'complete' => $file . '_complete.png',
'favicon' => $file . '_favicon.png',
);
}
}
}
if ((isset($ui['iw']) && (int) $ui['iw'] === 1 && $ui['request'] === 'api')) {
$res = launchScript($defUrl, $hashUrl, $width, $ui['s'], true);
} elseif (isset($ui['iw']) && (int) $ui['iw'] === 1 && $ui['request'] === 'form') { // img not exist or force refresh make it and return it
$res = launchScript($defUrl, $hashUrl, $width, 'shortLive', true);
makeFavicon($hashUrl, $ui['url'], $filePath);
} else {
if ($ui['t'] === 'fav') {
$res = makeFavicon($hashUrl, $ui['url'], $filePath);
} else {
$res = launchScript($defUrl, $hashUrl, $width, $ui['s'], false);
}
}
if ($ui['request'] === 'api') {
$file = 'bin/loadingGen';
printThumbShot($file, $ui['t']);
die();
} else {
if ($GLOBALS['config']['disableExec'] === true) {
$file = 'bin/loadingGen';
}
$success = array(
'normal' => $file . '.png',
'thumb' => $file . '_thumb.png',
'complete' => $file . '_complete.png',
'favicon' => $file . '_favicon.png',
);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SoShot</title>
<meta name="description" content="Personal webshot">
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
require getPage($ui['p']);
?>
</body>
</html>

12
public/.htaccess Normal file
View file

@ -0,0 +1,12 @@
AddDefaultCharset UTF-8
Options -Indexes
DirectoryIndex index.php index.html
FileETag none
SetOutputFilter DEFLATE
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

12
public/assets/css/fork-awesome.min.css vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

106
public/assets/css/style.css Normal file
View file

@ -0,0 +1,106 @@
html {
font-family: arial, sans-serif;
font-weight: bold;
line-height: 2em;
background-color: #ffffffcb;
}
html,
body,
h1,
h2,
h3,
h4,
h5,
h6 {
font-family: "Roboto", sans-serif;
}
.w3-sidebar {
z-index: 3;
width: 250px;
top: 43px;
height: inherit;
}
a {
text-decoration: none;
color: #8AC007;
}
a:hover,
.title:hover {
text-decoration: none;
}
a:visited {
color: #8AC007;
}
.centerBlock {
margin: auto;
}
.homeForm {
width: 49.9%;
}
.w3-bar {
background-color: #333333 !important;
}
#mySidebar {
top: inherit;
background-color: initial !important;
}
#mySidebar a:hover {
text-decoration: none;
}
.w3-bar-block .w3-bar-item {
padding: 4px 16px;
}
#myFooter {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
text-align: center;
}
.w3-main {
margin: 64px auto 64px 270px;
}
.soshot-main {
padding-bottom: 16px;
}
.fa {
color: #009688;
}
form label {
width: 48% !important;
display: inline-block;
text-align: right;
margin-right: 16px;
}
.w3-input,
.w3-select {
display: inline-block;
width: 48%;
}
@media (max-width:768px) {
#mySidebar {
background-color: #ffffffcb !important;
width: 100%;
height: 50%;
}
}

1994
public/assets/css/w3.css Normal file

File diff suppressed because it is too large Load diff

Binary file not shown.

File diff suppressed because it is too large Load diff

After

Width:  |  Height:  |  Size: 547 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 331 KiB

View file

Before

Width:  |  Height:  |  Size: 99 KiB

After

Width:  |  Height:  |  Size: 99 KiB

67
public/index.php Normal file
View file

@ -0,0 +1,67 @@
<?php
require_once '../vendor/autoload.php';
ini_set('display_errors', '1');
/**
* Améliore la sortie print
*
* @author Tatane http://www.tatane.info/index.php/print_rn
* @author http://www.blog.cactuscrew.com/77-print_rn.html
* @param $data (array) tableau ou variable à examiner
* @param $name (string) nom a afficher
* @return false affiche les clef valeur du tableau $data
* @example n_print($array, 'Tableau de valeur');
*/
function n_print($data, $name = '') {
$aBackTrace = debug_backtrace();
echo '<h2>', $name, '</h2>';
echo '<fieldset style="border: 1px solid orange; padding: 5px;color: #333; background-color: #fff;">';
echo '<legend style="border:1px solid orange;padding: 1px;background-color:#eee;color:orange;">
', basename($aBackTrace[0]['file']), ' ligne => ', $aBackTrace[0]['line'], '
</legend>';
echo '<pre>', htmlentities(print_r($data, 1)), '</pre>';
echo '
</fieldset>
<br />
';
}
use App\Router;
use App\Utils\Error;
use Noodlehaus\Config;
$router = new Router();
$router->addRoute(['/', '/index.php', '/index'], 'App\Controllers\Home', 'GET');
$router->addRoute('/api', 'App\Controllers\Result', 'GET');
$router->addRoute('/hmac', 'App\Controllers\GenHmac', 'GET');
//$router->addRoute('/debug', 'App\Bin\ThumbShoter', 'GET');
$router->addRoute('/backend', 'App\Controllers\Backend', 'GET');
$router->addRoute('/logout', 'App\Controllers\Logout', 'GET');
$conf = (object)Config::load([__DIR__ . '/../datas/config.default.json', '?' . __DIR__ . '/../datas/config.json'])->all();
if (!file_exists(__DIR__ . '/../datas/config.json')) {
session_start();
$conf->webPage = true;
$_SESSION['login'] = 1;
$_SESSION['firstRun'] = 1;
if ($_SERVER['REQUEST_URI'] !== '/backend?page=settings') {
header("Location:/backend?page=settings");
exit();
}
}
if ($conf->onlyLocalServer === true && $_SERVER['REMOTE_ADDR'] !== '127.0.0.1') {
$error = new Error();
$error->index((object)['status' => 404, 'message' => 'The page that you have requested could not be found.']);
exit();
}
if ($router->match()) {
$router->render($conf);
} else {
$error = new Error();
$error->index((object)['status' => 404, 'message' => 'The page that you have requested could not be found.']);
}

View file

@ -1,14 +0,0 @@
# !!!! Be careful !!!!
## This script can overcharge your server.
## Use at your own risk
All info in the homepage http://forge.leslibres.org/projects/soshot
**Thanks**
* Icon by http://www.iconfinder.com/icondetails/7917/128/camera_file_image_icon
* Icon by https://www.iconfinder.com/icons/34267/browser_earth_global_globe_international_internet_map_planet_world_icon
* Bash script idea by http://www.cambus.net/blog/page/3/
* Httpstatus in bash by https://gist.github.com/rsvp/1171304
* The engine phantomjs by http://phantomjs.org/

View file

Before

Width:  |  Height:  |  Size: 1.2 KiB

After

Width:  |  Height:  |  Size: 1.2 KiB

View file

Before

Width:  |  Height:  |  Size: 1 KiB

After

Width:  |  Height:  |  Size: 1 KiB

View file

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View file

Before

Width:  |  Height:  |  Size: 5.5 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

View file

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View file

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

View file

Before

Width:  |  Height:  |  Size: 1.9 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

125
style.css
View file

@ -1,125 +0,0 @@
html {
padding: 1em;
font-family: arial, sans-serif;
font-weight: bold;
line-height: 2em;
background-color: #dedede;
}
a {
text-decoration: none;
color:#8AC007;
}
a:hover {
text-decoration: underline;
}
a:visited {
color : #8AC007;
}
form, #result, #header, .message, .hMenu, #log {
padding: 1em;
text-align: center;
width: 60%;
margin: 1em auto;
background-color: #ffffff;
border-radius: 5px;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.50), 0 85px 180px 0 #FFFFFF, 0 12px 8px -5px rgba(0, 0, 0, 0.95);
}
input, select {
height: 2em;
}
#result input[type=text] {
width: 80%;
display: inline-block;
}
input[type=url] {
width: 100%;
}
#result label {
margin-right: 1em;
width: 15%;
display: inline-block;
text-align: center;
}
form .info {
text-align: right;
margin: 0 0;
line-height: 0.8em;
font-size: 0.8em;
}
#result, #header {
text-align: center;
padding: 1em;
margin: 1em auto;
}
#result img {
box-shadow: 3px 3px 3px #cdcdcd;
border: 1px solid #cdcdcd;
border-radius: 5px;
}
.message {
background-color: orange;
}
.hMenu li {
display: inline-block;
font-size: 1.2em;
}
.hMenu li:after {
content: " / ";
}
.hMenu li:last-child:after {
content: "";
}
.clear {
text-align: right;
}
#log li {
text-align: left;
}
@media screen and (min-width: 320px) and (max-width: 800px) {
html {
padding: 0.1em;
}
form, #result {
width: 100%;
padding: 0.1em;
}
input[type=url] {
width: 99%;
height: 2em;
}
input[type=submit] {
width: 99%;
height: 2em;
}
label {
display: block;
}
select {
width: 99%;
height: 2em;
display: block;
}
}

19
tpl/bone.php Normal file
View file

@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<title>SoShot</title>
<meta charset="UTF-8">
<meta name="description" content="Personal webshot">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/w3.css">
<link rel="stylesheet" href="https://www.w3schools.com/lib/w3-theme-black.css">
<link rel="stylesheet" href="assets/css/fork-awesome.min.css">
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
<?= $content; ?>
</body>
</html>

6
tpl/footer.php Normal file
View file

@ -0,0 +1,6 @@
</div>
<footer id="myFooter" class="w3-bottom w3-margin-top">
<div class="w3-container w3-theme-l1">
<p>Powered by <a href="https://www.w3schools.com/w3css/default.asp" target="_blank">w3.css</a></p>
</div>
</footer>

10
tpl/home.php Normal file
View file

@ -0,0 +1,10 @@
<div class="w3-row-padding centerBlock homeForm">
<h1 class="w3-center">SoShot</h1>
<p>Per<b>so</b>nal web<b>shot</b>er</p>
<div>
<img src="assets/img/wikipedia_logiciel_libre.png" alt="Thumbshot of french wikipedia home page" width="720px">
</div>
<p class="w3-center">
<a href="https://forge.leslibres.org/Knah-Tsaeb/Soshot">Homepage</a> | <a href="https://knah-tsaeb.org/contact-page/">Contact</a>
</p>
</div>

137
tpl/infos.php Normal file
View file

@ -0,0 +1,137 @@
<?php
use App\Utils\ConvertStatus;
use App\Utils\Domains;
//require_once 'nav.php';
?>
<div class="w3-row soshot-main w3-margin-bottom">
<div class="w3-container">
<h1 class="w3-text-teal">Infos</h1>
<p>
Nb : <?= $total; ?>
</p>
<table class="w3-table-all w3-hoverable">
<thead>
<tr>
<td>Domain</td>
<td>Created</td>
<td>Complete</td>
<td>Full</td>
<td>HD</td>
<td>Thumb</td>
<td>Favicon</td>
<td>Og</td>
<td>PDF</td>
</tr>
</thead>
<tbody>
<?php foreach ($genList as $value) : ?>
<tr>
<td><a href="#" class="linkDetail" data-hmac="<?= $value->id; ?>" data-href="<?= $value->url; ?>"><?= Domains::getDomain($value->url); ?></a></td>
<td><?= $value->created; ?></td>
<td><?= ConvertStatus::convertToIcon($value->complete); ?></td>
<td><?= ConvertStatus::convertToIcon($value->full); ?></td>
<td><?= ConvertStatus::convertToIcon($value->hd); ?></td>
<td><?= ConvertStatus::convertToIcon($value->thumb); ?></td>
<td><?= ConvertStatus::convertToIcon($value->fav); ?></td>
<td><?= ConvertStatus::convertToIcon($value->og); ?></td>
<td><?= ConvertStatus::convertToIcon($value->pdf); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="w3-center">
<div class="w3-bar">
<a href="?page=infos&start=<?= $previous; ?>" class="w3-bar-item w3-button">&laquo; Previous</a>
<a href="?page=infos&start=<?= $next; ?>" class="w3-button">Next &raquo; </a>
</div>
</div>
</div>
<div id="detail" class="w3-modal">
<div class="w3-modal-content w3-animate-opacity">
<div class="w3-container">
<span onclick="document.getElementById('detail').style.display='none'" class="w3-button w3-display-topright">&times;</span>
<p>
<img src="" id="fav" height="32px">
<a href="" id="titlePreview" target="_blanck"></a>
</p>
<img class="w3-border w3c-margin" src="" id="complete" width="45%">
<img class="w3-border w3c-margin" src="" id="full" width="35%">
<img class="w3-border w3c-margin" src="" id="hd" width="30%">
<img class="w3-border w3c-margin" src="" id="og" width="25%">
<img class="w3-border w3c-margin" src="" id="thumb" width="15%">
</div>
</div>
</div>
</div>
<!-- END MAIN -->
<script>
// Get the Sidebar
var mySidebar = document.getElementById("mySidebar");
// Get the DIV with overlay effect
var overlayBg = document.getElementById("myOverlay");
// Toggle between showing and hiding the sidebar, and add overlay effect
function w3_open() {
if (mySidebar.style.display === 'block') {
mySidebar.style.display = 'none';
overlayBg.style.display = "none";
} else {
mySidebar.style.display = 'block';
overlayBg.style.display = "block";
}
}
// Close the sidebar with the close button
function w3_close() {
mySidebar.style.display = "none";
overlayBg.style.display = "none";
}
const el = document.querySelectorAll('.linkDetail');
el.forEach(element => {
element.addEventListener("click", (el) => {
let $hmac = el.srcElement.dataset.hmac;
let $href = el.srcElement.dataset.href;
let $title = document.getElementById("titlePreview");
let $complete = document.getElementById("complete");
let $full = document.getElementById("full");
let $hd = document.getElementById("hd");
let $thumb = document.getElementById("thumb");
let $og = document.getElementById("og");
let $fav = document.getElementById("fav");
$title.href = $href;
$title.textContent = $href;
$complete.src = "?type=complete&showImg=" + $hmac;
$full.src = "?type=full&showImg=" + $hmac;
$hd.src = "?type=hd&showImg=" + $hmac;
$thumb.src = "?type=thumb&showImg=" + $hmac;
$og.src = "?type=og&showImg=" + $hmac;
$fav.src = "?type=fav&showImg=" + $hmac;
document.getElementById('detail').style.display = 'block';
});
});
function showDetail(el) {
}
// Get the modal
var modal = document.getElementById('detail');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<?php
//require_once 'footer.php';

11
tpl/login.php Normal file
View file

@ -0,0 +1,11 @@
<div class="w3-center w3-container w3-half w3-display-middle">
<i class="fa fa-5x fa-lock" aria-hidden="true"></i>
<form class="w3-container" action="?" method="post">
<div class="w3-section">
<input class="w3-input w3-border" type="password" placeholder="Password" name="loginPassword" required>
<input type="hidden" name="token" value="<?= $token; ?>" />
<button class="w3-button w3-block w3-teal w3-section w3-padding" style="width:30%; margin:0 auto" type="submit">Login</button>
</div>
</form>
</div>

28
tpl/nav.php Normal file
View file

@ -0,0 +1,28 @@
<?php
use App\Utils\Page;
?>
<div class="w3-top w3-round">
<div class="w3-bar w3-theme w3-top w3-left-align w3-large">
<a class="w3-bar-item w3-button w3-right w3-hide-large w3-hover-white w3-large w3-theme-l1" href="javascript:void(0)" onclick="w3_open()"><i class="fa fa-bars"></i></a>
<a href="#" class="w3-bar-item w3-button w3-theme-l1 title"><i class="fa fa-camera" aria-hidden="true"></i> SoShot</a>
<?php if ($this->runningJob) : ?><i class="fa fa-refresh fa-spin w3-text-red"></i><?php endif; ?>
</div>
</div>
<!-- Sidebar -->
<nav class="w3-sidebar w3-bar-block w3-collapse w3-large w3-theme-l5 w3-round" id="mySidebar">
<a href="javascript:void(0)" onclick="w3_close()" class="w3-right w3-xlarge w3-padding-large w3-hover-black w3-hide-large" title="Close Menu">
<i class="fa fa-remove"></i>
</a>
<a class="w3-bar-item w3-button <?= Page::active($params->page, 'infos', 'w3-gray') ?>" href="?page=infos">&nbsp;<i class="fa fa-info"></i> Infos</a>
<a class="w3-bar-item w3-button <?= Page::active($params->page, 'settings', 'w3-gray') ?>" href="?page=settings"><i class="fa fa-cog"></i> Settings</a>
<a class="w3-bar-item w3-button w3-margin-top <?= Page::active($params->page, 'logout', 'w3-gray') ?>" href="/logout"><i class="fa fa-cog"></i> Logout</a>
</nav>
<!-- Overlay effect when opening sidebar on small screens -->
<div class="w3-overlay w3-hide-large" onclick="w3_close()" style="cursor:pointer" title="close side menu" id="myOverlay"></div>
<!-- Main content: shift it to the right by 250 pixels when the sidebar is visible -->
<div class="w3-main w3-animate-right">

69
tpl/settings.php Normal file
View file

@ -0,0 +1,69 @@
<?php
use App\Utils\Page;
?>
<div class="w3-row soshot-main w3-margin-bottom">
<div class="w3-container">
<h1 class="w3-text-teal"><?= $this->title; ?></h1>
<form class="w3-container" method="post">
<p>
<label>Accept only request from 127.0.0.1</label>
<input class="w3-check" type="checkbox" name="onlyLocalServer" value="1" <?= Page::checked($this->conf->onlyLocalServer, true); ?>>
</p>
<p>
<label>Use web GUI</label>
<input class="w3-check" type="checkbox" name="webPage" value="1" <?= Page::checked($this->conf->webPage, true); ?>>
</p>
<p>
<label>Use log</label>
<input class="w3-check" type="checkbox" name="log" value="1" <?= Page::checked($this->conf->log, true); ?>>
</p>
<p>
<label>Always make PDF</label>
<input class="w3-check" type="checkbox" name="alwaysMakePdf" value="1" <?= Page::checked($this->conf->alwaysMakePdf, true); ?>>
</p>
<p>
<label>Favicon size</label>
<input class="w3-input w3-border" type="number" name="icoSize" value="<?= $this->conf->icoSize; ?>">
</p>
<p>
<label>Permit type of webshot</label>
<select class="w3-select w3-border" name="permitType[]" multiple size="7">
<option value="fav" <?= Page::selected('fav', $this->conf->permitType); ?>>Favicon (<?= $this->conf->icoSize; ?>x<?= $this->conf->icoSize; ?>)</option>
<option value="og" <?= Page::selected('og', $this->conf->permitType); ?>>Og image</option>
<option value="pdf" <?= Page::selected('pdf', $this->conf->permitType); ?>>PDF</option>
<option value="thumb" <?= Page::selected('thumb', $this->conf->permitType); ?>>ThumbShot (160x90)</option>
<option value="hd" <?= Page::selected('hd', $this->conf->permitType); ?>>HD (1080x720)</option>
<option value="full" <?= Page::selected('full', $this->conf->permitType); ?>>Full HD (1920x1080)</option>
<option value="complete" <?= Page::selected('complete', $this->conf->permitType); ?>>Complete (1920x height of page)</option>
</select>
</p>
<p>
<label>Cache expiration (for web GUI) in hour</label>
<input class="w3-input w3-border" type="number" name="expireCache" value="<?= $this->conf->expireCache; ?>">
</p>
<p>
<label>Maximum work per batch</label>
<input class="w3-input w3-border" type="number" name="maxGenPerBatch" value="<?= $this->conf->maxGenPerBatch; ?>">
</p>
<p>
<label>Api key (<span class="w3-red">change key will be invalid all previous generation</span>)</label>
<input class="w3-input w3-border" type="text" name="key" value="<?= $this->conf->key; ?>">
</p>
<p>
<label>Password</label>
<input class="w3-input w3-border" type="password" name="password" value="" <?= $this->passwordRequired; ?>>
</p>
<p>
<input type="hidden" name="page" value="settings">
<input type="hidden" name="token" value="<?= $token;?>">
<button type="submit" class="w3-btn w3-padding w3-teal" style="width:120px">Save</button>
</p>
</form>
</div>
</div>

20
vendor/autoload.php vendored
View file

@ -2,6 +2,24 @@
// autoload.php @generated by Composer // autoload.php @generated by Composer
if (PHP_VERSION_ID < 50600) {
if (!headers_sent()) {
header('HTTP/1.1 500 Internal Server Error');
}
$err = 'Composer 2.3.0 dropped support for autoloading on PHP <5.6 and you are running '.PHP_VERSION.', please upgrade PHP or use Composer 2.2 LTS via "composer self-update --2.2". Aborting.'.PHP_EOL;
if (!ini_get('display_errors')) {
if (PHP_SAPI === 'cli' || PHP_SAPI === 'phpdbg') {
fwrite(STDERR, $err);
} elseif (!headers_sent()) {
echo $err;
}
}
trigger_error(
$err,
E_USER_ERROR
);
}
require_once __DIR__ . '/composer/autoload_real.php'; require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit0e506de7fccd419bf18972ed94446862::getLoader(); return ComposerAutoloaderInit7d740ebad4b2c7aa4e5cabba3044a596::getLoader();

View file

@ -37,57 +37,134 @@ namespace Composer\Autoload;
* *
* @author Fabien Potencier <fabien@symfony.com> * @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be> * @author Jordi Boggiano <j.boggiano@seld.be>
* @see http://www.php-fig.org/psr/psr-0/ * @see https://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/ * @see https://www.php-fig.org/psr/psr-4/
*/ */
class ClassLoader class ClassLoader
{ {
/** @var \Closure(string):void */
private static $includeFile;
/** @var ?string */
private $vendorDir;
// PSR-4 // PSR-4
/**
* @var array[]
* @psalm-var array<string, array<string, int>>
*/
private $prefixLengthsPsr4 = array(); private $prefixLengthsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, array<int, string>>
*/
private $prefixDirsPsr4 = array(); private $prefixDirsPsr4 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr4 = array(); private $fallbackDirsPsr4 = array();
// PSR-0 // PSR-0
/**
* @var array[]
* @psalm-var array<string, array<string, string[]>>
*/
private $prefixesPsr0 = array(); private $prefixesPsr0 = array();
/**
* @var array[]
* @psalm-var array<string, string>
*/
private $fallbackDirsPsr0 = array(); private $fallbackDirsPsr0 = array();
/** @var bool */
private $useIncludePath = false; private $useIncludePath = false;
/**
* @var string[]
* @psalm-var array<string, string>
*/
private $classMap = array(); private $classMap = array();
/** @var bool */
private $classMapAuthoritative = false; private $classMapAuthoritative = false;
/**
* @var bool[]
* @psalm-var array<string, bool>
*/
private $missingClasses = array(); private $missingClasses = array();
/** @var ?string */
private $apcuPrefix; private $apcuPrefix;
/**
* @var self[]
*/
private static $registeredLoaders = array();
/**
* @param ?string $vendorDir
*/
public function __construct($vendorDir = null)
{
$this->vendorDir = $vendorDir;
self::initializeIncludeClosure();
}
/**
* @return string[]
*/
public function getPrefixes() public function getPrefixes()
{ {
if (!empty($this->prefixesPsr0)) { if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0); return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
} }
return array(); return array();
} }
/**
* @return array[]
* @psalm-return array<string, array<int, string>>
*/
public function getPrefixesPsr4() public function getPrefixesPsr4()
{ {
return $this->prefixDirsPsr4; return $this->prefixDirsPsr4;
} }
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirs() public function getFallbackDirs()
{ {
return $this->fallbackDirsPsr0; return $this->fallbackDirsPsr0;
} }
/**
* @return array[]
* @psalm-return array<string, string>
*/
public function getFallbackDirsPsr4() public function getFallbackDirsPsr4()
{ {
return $this->fallbackDirsPsr4; return $this->fallbackDirsPsr4;
} }
/**
* @return string[] Array of classname => path
* @psalm-return array<string, string>
*/
public function getClassMap() public function getClassMap()
{ {
return $this->classMap; return $this->classMap;
} }
/** /**
* @param array $classMap Class to filename map * @param string[] $classMap Class to filename map
* @psalm-param array<string, string> $classMap
*
* @return void
*/ */
public function addClassMap(array $classMap) public function addClassMap(array $classMap)
{ {
@ -103,8 +180,10 @@ class ClassLoader
* appending or prepending to the ones previously set for this prefix. * appending or prepending to the ones previously set for this prefix.
* *
* @param string $prefix The prefix * @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories * @param string[]|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories * @param bool $prepend Whether to prepend the directories
*
* @return void
*/ */
public function add($prefix, $paths, $prepend = false) public function add($prefix, $paths, $prepend = false)
{ {
@ -148,10 +227,12 @@ class ClassLoader
* appending or prepending to the ones previously set for this namespace. * appending or prepending to the ones previously set for this namespace.
* *
* @param string $prefix The prefix/namespace, with trailing '\\' * @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories * @param string[]|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories * @param bool $prepend Whether to prepend the directories
* *
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*
* @return void
*/ */
public function addPsr4($prefix, $paths, $prepend = false) public function addPsr4($prefix, $paths, $prepend = false)
{ {
@ -196,7 +277,9 @@ class ClassLoader
* replacing any others previously set for this prefix. * replacing any others previously set for this prefix.
* *
* @param string $prefix The prefix * @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories * @param string[]|string $paths The PSR-0 base directories
*
* @return void
*/ */
public function set($prefix, $paths) public function set($prefix, $paths)
{ {
@ -212,9 +295,11 @@ class ClassLoader
* replacing any others previously set for this namespace. * replacing any others previously set for this namespace.
* *
* @param string $prefix The prefix/namespace, with trailing '\\' * @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories * @param string[]|string $paths The PSR-4 base directories
* *
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
*
* @return void
*/ */
public function setPsr4($prefix, $paths) public function setPsr4($prefix, $paths)
{ {
@ -234,6 +319,8 @@ class ClassLoader
* Turns on searching the include path for class files. * Turns on searching the include path for class files.
* *
* @param bool $useIncludePath * @param bool $useIncludePath
*
* @return void
*/ */
public function setUseIncludePath($useIncludePath) public function setUseIncludePath($useIncludePath)
{ {
@ -256,6 +343,8 @@ class ClassLoader
* that have not been registered with the class map. * that have not been registered with the class map.
* *
* @param bool $classMapAuthoritative * @param bool $classMapAuthoritative
*
* @return void
*/ */
public function setClassMapAuthoritative($classMapAuthoritative) public function setClassMapAuthoritative($classMapAuthoritative)
{ {
@ -276,10 +365,12 @@ class ClassLoader
* APCu prefix to use to cache found/not-found classes, if the extension is enabled. * APCu prefix to use to cache found/not-found classes, if the extension is enabled.
* *
* @param string|null $apcuPrefix * @param string|null $apcuPrefix
*
* @return void
*/ */
public function setApcuPrefix($apcuPrefix) public function setApcuPrefix($apcuPrefix)
{ {
$this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null; $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
} }
/** /**
@ -296,33 +387,55 @@ class ClassLoader
* Registers this instance as an autoloader. * Registers this instance as an autoloader.
* *
* @param bool $prepend Whether to prepend the autoloader or not * @param bool $prepend Whether to prepend the autoloader or not
*
* @return void
*/ */
public function register($prepend = false) public function register($prepend = false)
{ {
spl_autoload_register(array($this, 'loadClass'), true, $prepend); spl_autoload_register(array($this, 'loadClass'), true, $prepend);
if (null === $this->vendorDir) {
return;
}
if ($prepend) {
self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
} else {
unset(self::$registeredLoaders[$this->vendorDir]);
self::$registeredLoaders[$this->vendorDir] = $this;
}
} }
/** /**
* Unregisters this instance as an autoloader. * Unregisters this instance as an autoloader.
*
* @return void
*/ */
public function unregister() public function unregister()
{ {
spl_autoload_unregister(array($this, 'loadClass')); spl_autoload_unregister(array($this, 'loadClass'));
if (null !== $this->vendorDir) {
unset(self::$registeredLoaders[$this->vendorDir]);
}
} }
/** /**
* Loads the given class or interface. * Loads the given class or interface.
* *
* @param string $class The name of the class * @param string $class The name of the class
* @return bool|null True if loaded, null otherwise * @return true|null True if loaded, null otherwise
*/ */
public function loadClass($class) public function loadClass($class)
{ {
if ($file = $this->findFile($class)) { if ($file = $this->findFile($class)) {
includeFile($file); $includeFile = self::$includeFile;
$includeFile($file);
return true; return true;
} }
return null;
} }
/** /**
@ -367,6 +480,21 @@ class ClassLoader
return $file; return $file;
} }
/**
* Returns the currently registered loaders indexed by their corresponding vendor directories.
*
* @return self[]
*/
public static function getRegisteredLoaders()
{
return self::$registeredLoaders;
}
/**
* @param string $class
* @param string $ext
* @return string|false
*/
private function findFileWithExtension($class, $ext) private function findFileWithExtension($class, $ext)
{ {
// PSR-4 lookup // PSR-4 lookup
@ -432,14 +560,26 @@ class ClassLoader
return false; return false;
} }
/**
* @return void
*/
private static function initializeIncludeClosure()
{
if (self::$includeFile !== null) {
return;
} }
/** /**
* Scope isolated include. * Scope isolated include.
* *
* Prevents access to $this/self from included files. * Prevents access to $this/self from included files.
*
* @param string $file
* @return void
*/ */
function includeFile($file) self::$includeFile = \Closure::bind(static function($file) {
{
include $file; include $file;
}, null, null);
}
} }

View file

@ -2,8 +2,15 @@
// autoload_classmap.php @generated by Composer // autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__)); $vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir); $baseDir = dirname($vendorDir);
return array( return array(
'Attribute' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => $vendorDir . '/composer/InstalledVersions.php',
'PhpToken' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => $vendorDir . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
'Zebra_Image' => $vendorDir . '/stefangabos/zebra_image/Zebra_Image.php',
); );

View file

@ -2,8 +2,10 @@
// autoload_namespaces.php @generated by Composer // autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__)); $vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir); $baseDir = dirname($vendorDir);
return array( return array(
'ML\\IRI' => array($vendorDir . '/ml/iri'),
'Evenement' => array($vendorDir . '/evenement/evenement/src'),
); );

View file

@ -2,10 +2,28 @@
// autoload_psr4.php @generated by Composer // autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__)); $vendorDir = dirname(__DIR__);
$baseDir = dirname($vendorDir); $baseDir = dirname($vendorDir);
return array( return array(
'Wrench\\' => array($vendorDir . '/chrome-php/wrench/src'),
'Symfony\\Polyfill\\Uuid\\' => array($vendorDir . '/symfony/polyfill-uuid'),
'Symfony\\Polyfill\\Php80\\' => array($vendorDir . '/symfony/polyfill-php80'),
'Symfony\\Polyfill\\Mbstring\\' => array($vendorDir . '/symfony/polyfill-mbstring'),
'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'),
'Symfony\\Component\\Uid\\' => array($vendorDir . '/symfony/uid'),
'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
'Symfony\\Component\\Filesystem\\' => array($vendorDir . '/symfony/filesystem'),
'Psr\\Log\\' => array($vendorDir . '/psr/log/src'),
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
'Noodlehaus\\' => array($vendorDir . '/hassankhan/config/src'),
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
'ML\\JsonLD\\' => array($vendorDir . '/ml/json-ld'),
'HtmlParser\\' => array($vendorDir . '/oscarotero/html-parser/src'),
'HeadlessChromium\\' => array($vendorDir . '/chrome-php/chrome/src'),
'GuzzleHttp\\Psr7\\' => array($vendorDir . '/guzzlehttp/psr7/src'),
'Embed\\' => array($vendorDir . '/embed/embed/src'), 'Embed\\' => array($vendorDir . '/embed/embed/src'),
'Composer\\CaBundle\\' => array($vendorDir . '/composer/ca-bundle/src'), 'Composer\\CaBundle\\' => array($vendorDir . '/composer/ca-bundle/src'),
'App\\' => array($baseDir . '/app'),
); );

View file

@ -2,7 +2,7 @@
// autoload_real.php @generated by Composer // autoload_real.php @generated by Composer
class ComposerAutoloaderInit0e506de7fccd419bf18972ed94446862 class ComposerAutoloaderInit7d740ebad4b2c7aa4e5cabba3044a596
{ {
private static $loader; private static $loader;
@ -13,40 +13,38 @@ class ComposerAutoloaderInit0e506de7fccd419bf18972ed94446862
} }
} }
/**
* @return \Composer\Autoload\ClassLoader
*/
public static function getLoader() public static function getLoader()
{ {
if (null !== self::$loader) { if (null !== self::$loader) {
return self::$loader; return self::$loader;
} }
spl_autoload_register(array('ComposerAutoloaderInit0e506de7fccd419bf18972ed94446862', 'loadClassLoader'), true, true); require __DIR__ . '/platform_check.php';
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInit0e506de7fccd419bf18972ed94446862', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); spl_autoload_register(array('ComposerAutoloaderInit7d740ebad4b2c7aa4e5cabba3044a596', 'loadClassLoader'), true, true);
if ($useStaticLoader) { self::$loader = $loader = new \Composer\Autoload\ClassLoader(\dirname(__DIR__));
require_once __DIR__ . '/autoload_static.php'; spl_autoload_unregister(array('ComposerAutoloaderInit7d740ebad4b2c7aa4e5cabba3044a596', 'loadClassLoader'));
call_user_func(\Composer\Autoload\ComposerStaticInit0e506de7fccd419bf18972ed94446862::getInitializer($loader)); require __DIR__ . '/autoload_static.php';
} else { call_user_func(\Composer\Autoload\ComposerStaticInit7d740ebad4b2c7aa4e5cabba3044a596::getInitializer($loader));
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true); $loader->register(true);
$filesToLoad = \Composer\Autoload\ComposerStaticInit7d740ebad4b2c7aa4e5cabba3044a596::$files;
$requireFile = \Closure::bind(static function ($fileIdentifier, $file) {
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
require $file;
}
}, null, null);
foreach ($filesToLoad as $fileIdentifier => $file) {
$requireFile($fileIdentifier, $file);
}
return $loader; return $loader;
} }
} }

View file

@ -4,9 +4,56 @@
namespace Composer\Autoload; namespace Composer\Autoload;
class ComposerStaticInit0e506de7fccd419bf18972ed94446862 class ComposerStaticInit7d740ebad4b2c7aa4e5cabba3044a596
{ {
public static $files = array (
'0e6d7bf4a5811bfa5cf40c5ccd6fae6a' => __DIR__ . '/..' . '/symfony/polyfill-mbstring/bootstrap.php',
'320cde22f66dd4f5d3fd621d3e88b98f' => __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php',
'a4a119a56e50fbb293281d9a48007e0e' => __DIR__ . '/..' . '/symfony/polyfill-php80/bootstrap.php',
'7b11c4dc42b3b3023073cb14e519683c' => __DIR__ . '/..' . '/ralouphie/getallheaders/src/getallheaders.php',
'09f6b20656683369174dd6fa83b7e5fb' => __DIR__ . '/..' . '/symfony/polyfill-uuid/bootstrap.php',
'09fc349b549513bf7f4291502426f919' => __DIR__ . '/..' . '/embed/embed/src/functions.php',
);
public static $prefixLengthsPsr4 = array ( public static $prefixLengthsPsr4 = array (
'W' =>
array (
'Wrench\\' => 7,
),
'S' =>
array (
'Symfony\\Polyfill\\Uuid\\' => 22,
'Symfony\\Polyfill\\Php80\\' => 23,
'Symfony\\Polyfill\\Mbstring\\' => 26,
'Symfony\\Polyfill\\Ctype\\' => 23,
'Symfony\\Component\\Uid\\' => 22,
'Symfony\\Component\\Process\\' => 26,
'Symfony\\Component\\Filesystem\\' => 29,
),
'P' =>
array (
'Psr\\Log\\' => 8,
'Psr\\Http\\Message\\' => 17,
'Psr\\Http\\Client\\' => 16,
),
'N' =>
array (
'Noodlehaus\\' => 11,
),
'M' =>
array (
'Monolog\\' => 8,
'ML\\JsonLD\\' => 10,
),
'H' =>
array (
'HtmlParser\\' => 11,
'HeadlessChromium\\' => 17,
),
'G' =>
array (
'GuzzleHttp\\Psr7\\' => 16,
),
'E' => 'E' =>
array ( array (
'Embed\\' => 6, 'Embed\\' => 6,
@ -15,9 +62,82 @@ class ComposerStaticInit0e506de7fccd419bf18972ed94446862
array ( array (
'Composer\\CaBundle\\' => 18, 'Composer\\CaBundle\\' => 18,
), ),
'A' =>
array (
'App\\' => 4,
),
); );
public static $prefixDirsPsr4 = array ( public static $prefixDirsPsr4 = array (
'Wrench\\' =>
array (
0 => __DIR__ . '/..' . '/chrome-php/wrench/src',
),
'Symfony\\Polyfill\\Uuid\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-uuid',
),
'Symfony\\Polyfill\\Php80\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-php80',
),
'Symfony\\Polyfill\\Mbstring\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-mbstring',
),
'Symfony\\Polyfill\\Ctype\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/polyfill-ctype',
),
'Symfony\\Component\\Uid\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/uid',
),
'Symfony\\Component\\Process\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/process',
),
'Symfony\\Component\\Filesystem\\' =>
array (
0 => __DIR__ . '/..' . '/symfony/filesystem',
),
'Psr\\Log\\' =>
array (
0 => __DIR__ . '/..' . '/psr/log/src',
),
'Psr\\Http\\Message\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-factory/src',
1 => __DIR__ . '/..' . '/psr/http-message/src',
),
'Psr\\Http\\Client\\' =>
array (
0 => __DIR__ . '/..' . '/psr/http-client/src',
),
'Noodlehaus\\' =>
array (
0 => __DIR__ . '/..' . '/hassankhan/config/src',
),
'Monolog\\' =>
array (
0 => __DIR__ . '/..' . '/monolog/monolog/src/Monolog',
),
'ML\\JsonLD\\' =>
array (
0 => __DIR__ . '/..' . '/ml/json-ld',
),
'HtmlParser\\' =>
array (
0 => __DIR__ . '/..' . '/oscarotero/html-parser/src',
),
'HeadlessChromium\\' =>
array (
0 => __DIR__ . '/..' . '/chrome-php/chrome/src',
),
'GuzzleHttp\\Psr7\\' =>
array (
0 => __DIR__ . '/..' . '/guzzlehttp/psr7/src',
),
'Embed\\' => 'Embed\\' =>
array ( array (
0 => __DIR__ . '/..' . '/embed/embed/src', 0 => __DIR__ . '/..' . '/embed/embed/src',
@ -26,13 +146,46 @@ class ComposerStaticInit0e506de7fccd419bf18972ed94446862
array ( array (
0 => __DIR__ . '/..' . '/composer/ca-bundle/src', 0 => __DIR__ . '/..' . '/composer/ca-bundle/src',
), ),
'App\\' =>
array (
0 => __DIR__ . '/../..' . '/app',
),
);
public static $prefixesPsr0 = array (
'M' =>
array (
'ML\\IRI' =>
array (
0 => __DIR__ . '/..' . '/ml/iri',
),
),
'E' =>
array (
'Evenement' =>
array (
0 => __DIR__ . '/..' . '/evenement/evenement/src',
),
),
);
public static $classMap = array (
'Attribute' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Attribute.php',
'Composer\\InstalledVersions' => __DIR__ . '/..' . '/composer/InstalledVersions.php',
'PhpToken' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/PhpToken.php',
'Stringable' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/Stringable.php',
'UnhandledMatchError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/UnhandledMatchError.php',
'ValueError' => __DIR__ . '/..' . '/symfony/polyfill-php80/Resources/stubs/ValueError.php',
'Zebra_Image' => __DIR__ . '/..' . '/stefangabos/zebra_image/Zebra_Image.php',
); );
public static function getInitializer(ClassLoader $loader) public static function getInitializer(ClassLoader $loader)
{ {
return \Closure::bind(function () use ($loader) { return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInit0e506de7fccd419bf18972ed94446862::$prefixLengthsPsr4; $loader->prefixLengthsPsr4 = ComposerStaticInit7d740ebad4b2c7aa4e5cabba3044a596::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInit0e506de7fccd419bf18972ed94446862::$prefixDirsPsr4; $loader->prefixDirsPsr4 = ComposerStaticInit7d740ebad4b2c7aa4e5cabba3044a596::$prefixDirsPsr4;
$loader->prefixesPsr0 = ComposerStaticInit7d740ebad4b2c7aa4e5cabba3044a596::$prefixesPsr0;
$loader->classMap = ComposerStaticInit7d740ebad4b2c7aa4e5cabba3044a596::$classMap;
}, null, ClassLoader::class); }, null, ClassLoader::class);
} }

View file

@ -27,22 +27,22 @@ Requirements
Basic usage Basic usage
----------- -----------
# `Composer\CaBundle\CaBundle` ### `Composer\CaBundle\CaBundle`
- `CaBundle::getSystemCaRootBundlePath()`: Returns the system CA bundle path, or a path to the bundled one as fallback - `CaBundle::getSystemCaRootBundlePath()`: Returns the system CA bundle path, or a path to the bundled one as fallback
- `CaBundle::getBundledCaBundlePath()`: Returns the path to the bundled CA file - `CaBundle::getBundledCaBundlePath()`: Returns the path to the bundled CA file
- `CaBundle::validateCaFile($filename)`: Validates a CA file using opensl_x509_parse only if it is safe to use - `CaBundle::validateCaFile($filename)`: Validates a CA file using openssl_x509_parse only if it is safe to use
- `CaBundle::isOpensslParseSafe()`: Test if it is safe to use the PHP function openssl_x509_parse() - `CaBundle::isOpensslParseSafe()`: Test if it is safe to use the PHP function openssl_x509_parse()
- `CaBundle::reset()`: Resets the static caches - `CaBundle::reset()`: Resets the static caches
## To use with curl #### To use with curl
```php ```php
$curl = curl_init("https://example.org/"); $curl = curl_init("https://example.org/");
$caPathOrFile = \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(); $caPathOrFile = \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath();
if (is_dir($caPathOrFile) || (is_link($caPathOrFile) && is_dir(readlink($caPathOrFile)))) { if (is_dir($caPathOrFile)) {
curl_setopt($curl, CURLOPT_CAPATH, $caPathOrFile); curl_setopt($curl, CURLOPT_CAPATH, $caPathOrFile);
} else { } else {
curl_setopt($curl, CURLOPT_CAINFO, $caPathOrFile); curl_setopt($curl, CURLOPT_CAINFO, $caPathOrFile);
@ -51,7 +51,7 @@ if (is_dir($caPathOrFile) || (is_link($caPathOrFile) && is_dir(readlink($caPathO
$result = curl_exec($curl); $result = curl_exec($curl);
``` ```
## To use with php streams #### To use with php streams
```php ```php
$opts = array( $opts = array(
@ -61,7 +61,7 @@ $opts = array(
); );
$caPathOrFile = \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath(); $caPathOrFile = \Composer\CaBundle\CaBundle::getSystemCaRootBundlePath();
if (is_dir($caPathOrFile) || (is_link($caPathOrFile) && is_dir(readlink($caPathOrFile)))) { if (is_dir($caPathOrFile)) {
$opts['ssl']['capath'] = $caPathOrFile; $opts['ssl']['capath'] = $caPathOrFile;
} else { } else {
$opts['ssl']['cafile'] = $caPathOrFile; $opts['ssl']['cafile'] = $caPathOrFile;
@ -71,7 +71,7 @@ $context = stream_context_create($opts);
$result = file_get_contents('https://example.com', false, $context); $result = file_get_contents('https://example.com', false, $context);
``` ```
## To use with Guzzle #### To use with Guzzle
```php ```php
$client = new \GuzzleHttp\Client([ $client = new \GuzzleHttp\Client([

View file

@ -24,12 +24,13 @@
"require": { "require": {
"ext-openssl": "*", "ext-openssl": "*",
"ext-pcre": "*", "ext-pcre": "*",
"php": "^5.3.2 || ^7.0" "php": "^5.3.2 || ^7.0 || ^8.0"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^4.8.35 || ^5.7 || ^6.5", "symfony/phpunit-bridge": "^4.2 || ^5",
"phpstan/phpstan": "^0.12.55",
"psr/log": "^1.0", "psr/log": "^1.0",
"symfony/process": "^2.5 || ^3.0 || ^4.0" "symfony/process": "^2.5 || ^3.0 || ^4.0 || ^5.0 || ^6.0"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
@ -43,12 +44,11 @@
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "1.x-dev" "dev-main": "1.x-dev"
} }
}, },
"config": { "scripts": {
"platform": { "test": "SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 vendor/bin/simple-phpunit",
"php": "5.3.9" "phpstan": "vendor/bin/phpstan analyse"
}
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -20,8 +20,11 @@ use Symfony\Component\Process\PhpProcess;
*/ */
class CaBundle class CaBundle
{ {
/** @var string|null */
private static $caPath; private static $caPath;
/** @var array<string, bool> */
private static $caFileValidity = array(); private static $caFileValidity = array();
/** @var bool|null */
private static $useOpensslParse; private static $useOpensslParse;
/** /**
@ -66,32 +69,20 @@ class CaBundle
if (self::$caPath !== null) { if (self::$caPath !== null) {
return self::$caPath; return self::$caPath;
} }
$caBundlePaths = array();
// If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that. // If SSL_CERT_FILE env variable points to a valid certificate/bundle, use that.
// This mimics how OpenSSL uses the SSL_CERT_FILE env variable. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
$envCertFile = getenv('SSL_CERT_FILE'); $caBundlePaths[] = self::getEnvVariable('SSL_CERT_FILE');
if ($envCertFile && is_readable($envCertFile) && static::validateCaFile($envCertFile, $logger)) {
return self::$caPath = $envCertFile;
}
// If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that. // If SSL_CERT_DIR env variable points to a valid certificate/bundle, use that.
// This mimics how OpenSSL uses the SSL_CERT_FILE env variable. // This mimics how OpenSSL uses the SSL_CERT_FILE env variable.
$envCertDir = getenv('SSL_CERT_DIR'); $caBundlePaths[] = self::getEnvVariable('SSL_CERT_DIR');
if ($envCertDir && is_dir($envCertDir) && is_readable($envCertDir)) {
return self::$caPath = $envCertDir;
}
$configured = ini_get('openssl.cafile'); $caBundlePaths[] = ini_get('openssl.cafile');
if ($configured && strlen($configured) > 0 && is_readable($configured) && static::validateCaFile($configured, $logger)) { $caBundlePaths[] = ini_get('openssl.capath');
return self::$caPath = $configured;
}
$configured = ini_get('openssl.capath'); $otherLocations = array(
if ($configured && is_dir($configured) && is_readable($configured)) {
return self::$caPath = $configured;
}
$caBundlePaths = array(
'/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package) '/etc/pki/tls/certs/ca-bundle.crt', // Fedora, RHEL, CentOS (ca-certificates package)
'/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package) '/etc/ssl/certs/ca-certificates.crt', // Debian, Ubuntu, Gentoo, Arch Linux (ca-certificates package)
'/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package) '/etc/ssl/ca-bundle.pem', // SUSE, openSUSE (ca-certificates package)
@ -103,17 +94,21 @@ class CaBundle
'/etc/ssl/cert.pem', // OpenBSD '/etc/ssl/cert.pem', // OpenBSD
'/usr/local/etc/ssl/cert.pem', // FreeBSD 10.x '/usr/local/etc/ssl/cert.pem', // FreeBSD 10.x
'/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package '/usr/local/etc/openssl/cert.pem', // OS X homebrew, openssl package
'/usr/local/etc/openssl@1.1/cert.pem', // OS X homebrew, openssl@1.1 package
); );
foreach ($caBundlePaths as $caBundle) { foreach($otherLocations as $location) {
if (@is_readable($caBundle) && static::validateCaFile($caBundle, $logger)) { $otherLocations[] = dirname($location);
return self::$caPath = $caBundle;
}
} }
$caBundlePaths = array_merge($caBundlePaths, $otherLocations);
foreach ($caBundlePaths as $caBundle) { foreach ($caBundlePaths as $caBundle) {
$caBundle = dirname($caBundle); if ($caBundle && self::caFileUsable($caBundle, $logger)) {
if (@is_dir($caBundle) && glob($caBundle.'/*')) { return self::$caPath = $caBundle;
}
if ($caBundle && self::caDirUsable($caBundle, $logger)) {
return self::$caPath = $caBundle; return self::$caPath = $caBundle;
} }
} }
@ -135,8 +130,13 @@ class CaBundle
// cURL does not understand 'phar://' paths // cURL does not understand 'phar://' paths
// see https://github.com/composer/ca-bundle/issues/10 // see https://github.com/composer/ca-bundle/issues/10
if (0 === strpos($caBundleFile, 'phar://')) { if (0 === strpos($caBundleFile, 'phar://')) {
$tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-');
if (false === $tempCaBundleFile) {
throw new \RuntimeException('Could not create a temporary file to store the bundled CA file');
}
file_put_contents( file_put_contents(
$tempCaBundleFile = tempnam(sys_get_temp_dir(), 'openssl-ca-bundle-'), $tempCaBundleFile,
file_get_contents($caBundleFile) file_get_contents($caBundleFile)
); );
@ -180,9 +180,17 @@ class CaBundle
} }
$isValid = !empty($contents); $isValid = !empty($contents);
} elseif (is_string($contents) && strlen($contents) > 0) {
$contents = preg_replace("/^(\\-+(?:BEGIN|END))\\s+TRUSTED\\s+(CERTIFICATE\\-+)\$/m", '$1 $2', $contents);
if (null === $contents) {
// regex extraction failed
$isValid = false;
} else { } else {
$isValid = (bool) openssl_x509_parse($contents); $isValid = (bool) openssl_x509_parse($contents);
} }
} else {
$isValid = false;
}
if ($logger) { if ($logger) {
$logger->debug('Checked CA file '.realpath($filename).': '.($isValid ? 'valid' : 'invalid')); $logger->debug('Checked CA file '.realpath($filename).': '.($isValid ? 'valid' : 'invalid'));
@ -216,7 +224,7 @@ class CaBundle
if ( if (
(PHP_VERSION_ID < 50400 && PHP_VERSION_ID >= 50328) (PHP_VERSION_ID < 50400 && PHP_VERSION_ID >= 50328)
|| (PHP_VERSION_ID < 50500 && PHP_VERSION_ID >= 50423) || (PHP_VERSION_ID < 50500 && PHP_VERSION_ID >= 50423)
|| (PHP_VERSION_ID < 50600 && PHP_VERSION_ID >= 50507) || PHP_VERSION_ID >= 50507
) { ) {
// This version of PHP has the fix for CVE-2013-6420 applied. // This version of PHP has the fix for CVE-2013-6420 applied.
return self::$useOpensslParse = true; return self::$useOpensslParse = true;
@ -283,7 +291,8 @@ EOT;
$errorOutput = trim($process->getErrorOutput()); $errorOutput = trim($process->getErrorOutput());
if ( if (
count($output) === 3 is_array($output)
&& count($output) === 3
&& $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION) && $output[0] === sprintf('string(%d) "%s"', strlen(PHP_VERSION), PHP_VERSION)
&& $output[1] === 'string(27) "stefan.esser@sektioneins.de"' && $output[1] === 'string(27) "stefan.esser@sektioneins.de"'
&& $output[2] === 'int(-1)' && $output[2] === 'int(-1)'
@ -298,6 +307,7 @@ EOT;
/** /**
* Resets the static caches * Resets the static caches
* @return void
*/ */
public static function reset() public static function reset()
{ {
@ -305,4 +315,117 @@ EOT;
self::$caPath = null; self::$caPath = null;
self::$useOpensslParse = null; self::$useOpensslParse = null;
} }
/**
* @param string $name
* @return string|false
*/
private static function getEnvVariable($name)
{
if (isset($_SERVER[$name])) {
return (string) $_SERVER[$name];
}
if (PHP_SAPI === 'cli' && ($value = getenv($name)) !== false && $value !== null) {
return (string) $value;
}
return false;
}
/**
* @param string|false $certFile
* @param LoggerInterface|null $logger
* @return bool
*/
private static function caFileUsable($certFile, LoggerInterface $logger = null)
{
return $certFile
&& static::isFile($certFile, $logger)
&& static::isReadable($certFile, $logger)
&& static::validateCaFile($certFile, $logger);
}
/**
* @param string|false $certDir
* @param LoggerInterface|null $logger
* @return bool
*/
private static function caDirUsable($certDir, LoggerInterface $logger = null)
{
return $certDir
&& static::isDir($certDir, $logger)
&& static::isReadable($certDir, $logger)
&& static::glob($certDir . '/*', $logger);
}
/**
* @param string $certFile
* @param LoggerInterface|null $logger
* @return bool
*/
private static function isFile($certFile, LoggerInterface $logger = null)
{
$isFile = @is_file($certFile);
if (!$isFile && $logger) {
$logger->debug(sprintf('Checked CA file %s does not exist or it is not a file.', $certFile));
}
return $isFile;
}
/**
* @param string $certDir
* @param LoggerInterface|null $logger
* @return bool
*/
private static function isDir($certDir, LoggerInterface $logger = null)
{
$isDir = @is_dir($certDir);
if (!$isDir && $logger) {
$logger->debug(sprintf('Checked directory %s does not exist or it is not a directory.', $certDir));
}
return $isDir;
}
/**
* @param string $certFileOrDir
* @param LoggerInterface|null $logger
* @return bool
*/
private static function isReadable($certFileOrDir, LoggerInterface $logger = null)
{
$isReadable = @is_readable($certFileOrDir);
if (!$isReadable && $logger) {
$logger->debug(sprintf('Checked file or directory %s is not readable.', $certFileOrDir));
}
return $isReadable;
}
/**
* @param string $pattern
* @param LoggerInterface|null $logger
* @return bool
*/
private static function glob($pattern, LoggerInterface $logger = null)
{
$certs = glob($pattern);
if ($certs === false) {
if ($logger) {
$logger->debug(sprintf("An error occurred while trying to find certificates for pattern: %s", $pattern));
}
return false;
}
if (count($certs) === 0) {
if ($logger) {
$logger->debug(sprintf("No CA files found for pattern: %s", $pattern));
}
return false;
}
return true;
}
} }

File diff suppressed because it is too large Load diff

View file

@ -1,29 +1,32 @@
# Embed # Embed
[![Build Status][ico-travis]][link-travis]
[![Quality Score][ico-scrutinizer]][link-scrutinizer]
[![Reference Status][ico-references]][link-references]
[![Latest Version on Packagist][ico-version]][link-packagist] [![Latest Version on Packagist][ico-version]][link-packagist]
[![Total Downloads][ico-downloads]][link-packagist] [![Total Downloads][ico-downloads]][link-packagist]
[![Monthly Downloads][ico-m-downloads]][link-packagist] [![Monthly Downloads][ico-m-downloads]][link-packagist]
[![Software License][ico-license]](LICENSE) [![Software License][ico-license]](LICENSE)
[![SensioLabs Insight][ico-sensiolabs]][link-sensiolabs]
PHP library to get information from any web page (using oembed, opengraph, twitter-cards, scrapping the html, etc). It's compatible with any web service (youtube, vimeo, flickr, instagram, etc) and has adapters to some sites like (archive.org, github, facebook, etc). PHP library to get information from any web page (using oembed, opengraph, twitter-cards, scrapping the html, etc). It's compatible with any web service (youtube, vimeo, flickr, instagram, etc) and has adapters to some sites like (archive.org, github, facebook, etc).
Requirements: Requirements:
* PHP 5.5+ * PHP 7.4+
* Curl library installed * Curl library installed
* PSR-17 implementation. By default these libraries are detected automatically:
* [laminas/laminas-diactoros](https://github.com/laminas/laminas-diactoros)
* [guzzle/psr7](https://github.com/guzzle/psr7)
* [nyholm/psr7](https://github.com/Nyholm/psr7)
* [sunrise/http-message](https://github.com/sunrise-php/http-message)
> > If you need PHP 5.5-7.3 support, [use the 3.x version](https://github.com/oscarotero/Embed/tree/v3.x)
* If you need PHP 5.3 support, use the 1.x version
* If you need PHP 5.4 support, use the 2.x version
## Online demo ## Online demo
http://oscarotero.com/embed3/demo http://oscarotero.com/embed/demo
## Video Tutorial
[<img src="https://img.youtube.com/vi/4YCLRpKY1cs/0.jpg" width="250">](https://youtu.be/4YCLRpKY1cs)
## Installation ## Installation
@ -33,270 +36,325 @@ This package is installable and autoloadable via Composer as [embed/embed](https
$ composer require embed/embed $ composer require embed/embed
``` ```
If you cannot (or don't want to) use composer, just include the [PSR-4 autoload.php file](src/autoloader.php) in your code.
## Usage ## Usage
```php ```php
use Embed\Embed; use Embed\Embed;
$embed = new Embed();
//Load any url: //Load any url:
$info = Embed::create('https://www.youtube.com/watch?v=PP1xn5wHtxE'); $info = $embed->get('https://www.youtube.com/watch?v=PP1xn5wHtxE');
//Get content info //Get content info
$info->title; //The page title $info->title; //The page title
$info->description; //The page description $info->description; //The page description
$info->url; //The canonical url $info->url; //The canonical url
$info->type; //The page type (link, video, image, rich) $info->keywords; //The page keywords
$info->tags; //The page keywords (tags)
$info->images; //List of all images found in the page $info->image; //The thumbnail or main image
$info->image; //The image choosen as main image
$info->imageWidth; //The width of the main image
$info->imageHeight; //The height of the main image
$info->code; //The code to embed the image, video, etc $info->code->html; //The code to embed the image, video, etc
$info->width; //The width of the embed code $info->code->width; //The exact width of the embed code (if exists)
$info->height; //The height of the embed code $info->code->height; //The exact height of the embed code (if exists)
$info->aspectRatio; //The aspect ratio (width/height) $info->code->ratio; //The aspect ratio (width/height)
$info->authorName; //The resource author $info->authorName; //The resource author
$info->authorUrl; //The author url $info->authorUrl; //The author url
$info->cms; //The cms used
$info->language; //The language of the page
$info->languages; //The alternative languages
$info->providerName; //The provider name of the page (Youtube, Twitter, Instagram, etc) $info->providerName; //The provider name of the page (Youtube, Twitter, Instagram, etc)
$info->providerUrl; //The provider url $info->providerUrl; //The provider url
$info->providerIcons; //All provider icons found in the page $info->icon; //The big icon of the site
$info->providerIcon; //The icon choosen as main icon $info->favicon; //The favicon of the site (an .ico file or a png with up to 32x32px)
$info->publishedDate; //The published date of the resource $info->publishedTime; //The published time of the resource
$info->license; //The license url of the resource $info->license; //The license url of the resource
$info->linkedData; //The linked-data info (http://json-ld.org/)
$info->feeds; //The RSS/Atom feeds $info->feeds; //The RSS/Atom feeds
``` ```
## The adapter ## Parallel multiple requests
The adapter is the class that get all information of the page from the providers and choose the best result for each value. For example, a page can provide multiple titles from opengraph, twitter cards, oembed, the `<title>` html element, etc, so the adapter get all this titles and choose the best one.
Embed has an generic adapter called "Webpage" to use with any web but has also some specific adapters for sites like archive.org, facebook, google, github, spotify, etc, that provides information using their own apis, or need to fix any specific issue.
The available options for the adapters are:
Name | Type | Description
-----|------|------------
`min_image_width` | `int` | Minimal image width used to choose the main image
`min_image_height` | `int` | Minimal image height used to choose the main image
`choose_bigger_image` | `bool` | Choose the bigger image as the main image (instead the first found, that usually is the most relevant).
`images_blacklist` | `string`&#124;`array` | Images that you don't want to be used. Could be plain text or [Uri](https://github.com/oscarotero/Embed/blob/master/src/Http/Url.php) match pattern.
`url_blacklist` | `string`&#124;`array` | URLs that you don't want to be used. Could be plain text or [Uri](https://github.com/oscarotero/Embed/blob/master/src/Http/Url.php) match pattern.
`follow_canonical` | `bool` | Whether to redirect to the canonical URL or not.
`custom_adapters_namespace` | `string`&#124;`array` | A namespace used to load custom adapters. This allows to override the behaviour of existing adapters or add support for more sites.
## The providers
The providers get the data from different sources. Each source has it's own provider. For example, there is a provider for opengraph, other for twitter cards, for oembed, html, etc. Some providers can be configured and are the following:
### oembed
Used to get data from oembed api if it's available:
Name | Type | Description
-----|------|------------
`parameters` | `array` | Extra query parameters to send with the oembed request
`embedly_key` | `string` | If it's defined, use embed.ly api as fallback oembed provider.
`iframely_key` | `string` | If it's defined, use iframe.ly api as fallback oembed provider.
### html
Used to get data directly from the html code of the page:
Name | Type | Description
-----|------|------------
`max_images` | `int` | Max number of images fetched from the html code (searching for the `<img>` elements). By default is -1 (no limit). Use 0 to no get images.
`external_images` | `bool`&#124;`array` | By default is `false`, this means that images located in other domains are not allowed. You can set `true` (allow all) or provide an array of url patterns.
### google
Used only for google maps to generate the embed code.
Name | Type | Description
-----|------|------------
`key` | `string` | The key used [for the embed api](https://developers.google.com/maps/documentation/embed/)
### soundcloud
Used only for soundcloud pages, to get information using its api.
Name | Type | Description
-----|------|------------
`key` | `string` | The key used to get info from soundcloud API.
### facebook
Used only for facebook events (not needed for posts, images, etc), to get information using its api.
Name | Type | Description
-----|------|------------
`key` | `string` | The access token used to get info from facebook graph API.
`events_fields` | `string` | Comma-separated list of fields to query for a facebook event. Please refer to [Facebook documentation](https://developers.facebook.com/docs/graph-api/reference/event) for the full list of available fields.
`videos_fields` | `string` | Comma-separated list of fields to query for a facebook video. Please refer to [Facebook documentation](https://developers.facebook.com/docs/graph-api/reference/event) for the full list of available fields.
## Example with all options:
The options are passed as the second argument as you can see in the following example:
```php ```php
$info = Embed::create($url, [ use Embed\Embed;
'min_image_width' => 100,
'min_image_height' => 100,
'choose_bigger_image' => true,
'images_blacklist' => 'example.com/*',
'url_blacklist' => 'example.com/*',
'follow_canonical' => true,
'html' => [ $embed = new Embed();
'max_images' => 10,
'external_images' => true
],
'oembed' => [ //Load multiple urls asynchronously:
'parameters' => [], $infos = $embed->getMulti(
'embedly_key' => 'YOUR_KEY', 'https://www.youtube.com/watch?v=PP1xn5wHtxE',
'iframely_key' => 'YOUR_KEY', 'https://twitter.com/carlosmeixidefl/status/1230894146220625933',
], 'https://en.wikipedia.org/wiki/Tordoia',
);
'google' => [ foreach ($infos as $info) {
'key' => 'YOUR_KEY', echo $info->title;
], }
```
'soundcloud' => [ ## Document
'key' => 'YOUR_KEY',
],
'facebook' => [ The document is the object that store the html code of the page. You can use it to extract extra info from the html code:
'key' => 'YOUR_KEY',
'fields' => 'field1,field2,field3' // default : cover,description,end_time,id,name,owner,place,start_time,timezone ```php
], //Get the document object
$document = $info->getDocument();
$document->link('image_src'); //Returns the href of a <link>
$document->getDocument(); //Returns the DOMDocument instance
$html = (string) $document; //Returns the html code
$document->select('.//h1'); //Search
```
You can perform xpath queries in order to select specific elements. A search always return an instance of a `Embed\QueryResult`:
```php
//Search the A elements
$result = $document->select('.//a');
//Filter the results
$result->filter(fn ($node) => $node->getAttribute('href'));
$id = $result->str('id'); //Return the id of the first result as string
$text = $result->str(); //Return the content of the first result
$ids = $result->strAll('id'); //Return an array with the ids of all results as string
$texts = $result->strAll(); //Return an array with the content of all results as string
$tabindex = $result->int('tabindex'); //Return the tabindex attribute of the first result as integer
$number = $result->int(); //Return the content of the first result as integer
$href = $result->url('href'); //Return the href attribute of the first result as url (converts relative urls to absolutes)
$url = $result->url(); //Return the content of the first result as url
$node = $result->node(); //Return the first node found (DOMElement)
$nodes = $result->nodes(); //Return all nodes found
```
## Metas
For convenience, the object `Metas` stores the value of all `<meta>` elements located in the html, so you can get the values easier. The key of every meta is get from the `name`, `property` or `itemprop` attributes and the value is get from `content`.
```php
//Get the Metas object
$metas = $info->getMetas();
$metas->all(); //Return all values
$metas->get('og:title'); //Return a key value
$metas->str('og:title'); //Return the value as string (remove html tags)
$metas->html('og:description'); //Return the value as html
$metas->int('og:video:width'); //Return the value as integer
$metas->url('og:url'); //Return the value as full url (converts relative urls to absolutes)
```
## OEmbed
In addition to the html and metas, this library uses [oEmbed](https://oembed.com/) endpoints to get additional data. You can get this data as following:
```php
//Get the oEmbed object
$oembed = $info->getOEmbed();
$oembed->all(); //Return all raw data
$oembed->get('title'); //Return a key value
$oembed->str('title'); //Return the value as string (remove html tags)
$oembed->html('html'); //Return the value as html
$oembed->int('width'); //Return the value as integer
$oembed->url('url'); //Return the value as full url (converts relative urls to absolutes)
```
Additional oEmbed parameters (like instagrams `hidecaption`) can also be provided:
```php
$embed = new Embed();
$result = $embed->get('https://www.instagram.com/p/B_C0wheCa4V/');
$result->setSettings([
'oembed:query_parameters' => ['hidecaption' => true]
]); ]);
$oembed = $info->getOEmbed();
``` ```
## The dispatcher ## LinkedData
To dispatch the http request, Embed includes the interface `Embed\Http\DispatcherInterface`. By default the curl library is used but you can create your own dispatcher to use any other library like [guzzle](https://github.com/guzzle/guzzle): Another API available by default, used to extract info using the [JsonLD](https://www.w3.org/TR/json-ld/) schema.
```php
//Get the linkedData object
$ld = $info->getLinkedData();
$ld->all(); //Return all data
$ld->get('name'); //Return a key value
$ld->str('name'); //Return the value as string (remove html tags)
$ld->html('description'); //Return the value as html
$ld->int('width'); //Return the value as integer
$ld->url('url'); //Return the value as full url (converts relative urls to absolutes)
```
## Other APIs
Some sites like Wikipedia or Archive.org provide a custom API that is used to fetch more reliable data. You can get the API object with the method `getApi()` but note that not all results have this method. The Api object has the same methods than oEmbed:
```php
//Get the API object
$api = $info->getApi();
$api->all(); //Return all raw data
$api->get('title'); //Return a key value
$api->str('title'); //Return the value as string (remove html tags)
$api->html('html'); //Return the value as html
$api->int('width'); //Return the value as integer
$api->url('url'); //Return the value as full url (converts relative urls to absolutes)
```
## Extending Embed
Depending of your needs, you may want to extend this library with extra features or change the way it makes some operations.
### PSR
Embed use some PSR standards to be the most interoperable possible:
- [PSR-7](https://www.php-fig.org/psr/psr-7/) Standard interfaces to represent http requests, responses and uris
- [PSR-17](https://www.php-fig.org/psr/psr-17/) Standard factories to create PSR-7 objects
- [PSR-18](https://www.php-fig.org/psr/psr-18/) Standard interface to send a http request and return a response
Embed comes with a CURL client compatible with PSR-18 but you need to install a PSR-7 / PSR-17 library. [Here you can see a list of popular libraries](https://github.com/middlewares/awesome-psr15-middlewares#psr-7-implementations) and the library can detect automatically 'laminas\diactoros', 'guzzleHttp\psr7', 'slim\psr7', 'nyholm\psr7' and 'sunrise\http' (in this order). If you want to use a different PSR implementation, you can do it in this way:
```php ```php
use Embed\Embed; use Embed\Embed;
use Embed\Http\DispatcherInteface; use Embed\Http\Crawler;
use Embed\Http\Url;
use Embed\Http\Response;
use Embed\Http\ImageResponse;
class MyDispatcher implements DispatcherInterface $client = new CustomHttpClient();
{ $requestFactory = new CustomRequestFactory();
public function dispatch(Url $url) $uriFactory = new CustomUriFactory();
{
$result = function_to_execute_request($url);
return new Response($url, $result['url'], $result['status'], $result['type'], $result['content'], $result['headers']); //The Crawler is responsible for perform http queries
} $crawler = new Crawler($client, $requestFactory, $uriFactory);
public function dispatchImages(array $urls) //Create an embed instance passing the Crawler
{ $embed = new Embed($crawler);
$responses = [];
foreach ($urls as $url) {
$result = function_to_get_image_size($url);
if ($result) {
$responses[] = new ImageResponse($url, $result['url'], $result['status'], $result['type'], $result['size'], $result['headers']);
}
}
return $responses;
}
}
//Use the dispatcher passing as third argument
$info = Embed::create('http://example.com', null, new MyDispatcher());
``` ```
The default curl dispatcher accepts the same options that the [curl_setopt PHP function](http://php.net/manual/en/function.curl-setopt.php). You can edit the default values: ### Adapters
There are some sites with special needs: because they provide public APIs that allows to extract more info (like Wikipedia or Archive.org) or because we need to change how to extract the data in this particular site. For all that cases we have the adapters, that are classes extending the default classes to provide extra functionality.
Before creating an adapter, you need to understand how Embed work: when you execute this code, you get a `Extractor` class
```php
//Get the Extractor with all info
$info = $embed->get($url);
//The extractor have document and oembed:
$document = $info->getDocument();
$oembed = $info->getOEmbed();
```
The `Extractor` class has many `Detectors`. Each detector is responsible to detect a specific piece of info. For example, there's a detector for the title, other for description, image, code, etc.
So, an adapter is basically an extractor created specifically for a site. It can contains also custom detectors or apis. If you see the `src/Adapters` folder you can see all adapters.
If you create an adapter, you need also register to Embed, so it knows in which website needs to use. To do that, there's the `ExtractorFactory` object, that is responsible for instantiate the right extractor for each site.
```php ```php
use Embed\Embed; use Embed\Embed;
use Embed\Http\CurlDispatcher;
$dispatcher = new CurlDispatcher([ $embed = new Embed();
CURLOPT_MAXREDIRS => 20,
CURLOPT_CONNECTTIMEOUT => 10, $factory = $embed->getExtractorFactory();
CURLOPT_TIMEOUT => 10,
CURLOPT_SSL_VERIFYPEER => false, //Use this MySite adapter for mysite.com
CURLOPT_SSL_VERIFYHOST => false, $factory->addAdapter('mysite.com', MySite::class);
CURLOPT_ENCODING => '',
CURLOPT_AUTOREFERER => true, //Remove the adapter for pinterest.com, so it will use the default extractor
CURLOPT_USERAGENT => 'Embed PHP Library', $factory->removeAdapter('pinterest.com');
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
//Change the default extractor
$factory->setDefault(CustomExtractor::class);
```
### Detectors
Embed comes with several predefined detectors, but you may want to change or add more. Just create a class extending `Embed\Detectors\Detector` class and register it in the extractor factory. For example:
```php
use Embed\Embed;
use Embed\Detectors\Detector;
class Robots extends Detector
{
public function detect(): ?string
{
$response = $this->extractor->getResponse();
$metas = $this->extractor->getMetas();
return $response->getHeaderLine('x-robots-tag'),
?: $metas->str('robots');
}
}
//Register the detector
$embed = new Embed();
$embed->getExtractorFactory()->addDetector('robots', Robots::class);
//Use it
$info = $embed->get('http://example.com');
$robots = $info->robots;
```
### Settings
If you need to pass settings to the CurlClient to perform http queries:
```php
use Embed\Embed;
use Embed\Http\Crawler;
use Embed\Http\CurlClient;
$client = new CurlClient();
$client->setSettings([
'cookies_path' => $cookies_path,
'ignored_errors' => [18],
'max_redirs' => 3, // see CURLOPT_MAXREDIRS
'connect_timeout' => 2, // see CURLOPT_CONNECTTIMEOUT
'timeout' => 2, // see CURLOPT_TIMEOUT
'ssl_verify_host' => 2, // see CURLOPT_SSL_VERIFYHOST
'ssl_verify_peer' => 1, // see CURLOPT_SSL_VERIFYPEER
'follow_location' => true, // see CURLOPT_FOLLOWLOCATION
'user_agent' => 'Mozilla', // see CURLOPT_USERAGENT
]); ]);
$info = Embed::create('http://example.com', null, $dispatcher); $embed = new Embed(new Crawler($client));
``` ```
## Accessing to advanced data If you need to pass settings to your detectors, you can add settings to the `ExtractorFactory`:
The adapter get the data from all providers and choose the best values. But you can get all available values accessing directly to each provider. There's also the possibility to inspect all http requests executed for debug purposes:
```php ```php
use Embed\Embed; use Embed\Embed;
//Get the info $embed = new Embed();
$info = Embed::create('https://www.youtube.com/watch?v=PP1xn5wHtxE'); $embed->setSettings([
'oembed:query_parameters' => [], //Extra parameters send to oembed
//Get all providers 'twitch:parent' => 'example.com', //Required to embed twitch videos as iframe
$providers = $info->getProviders(); 'facebook:token' => '1234|5678', //Required to embed content from Facebook
'instagram:token' => '1234|5678', //Required to embed content from Instagram
//Get the oembed provider 'twitter:token' => 'asdf', //Improve the data from twitter
$oembed = $providers['oembed']; ]);
$info = $embed->get($url);
//Get the oembed title value:
echo $oembed->getTitle();
//Get any value returned by the oembed api
echo $oembed->bag->get('author_name');
//Get the main response object
$response = $info->getResponse();
//Get any http response header
$lastModified = $response->getHeader('Last-Modifier');
//Get the html body as DOMDocument
$html = $response->getHtmlContent();
//Get all http request executed (oembed endpoints, images, apis, etc...)
$dispatcher = $adapter->getDispatcher();
foreach ($dispatcher->getAllResponses() as $response) {
echo 'The request to '.$response->getStartingUrl();
echo ' is resolved to '.$response->getUrl();
}
``` ```
Note: The built-in detectors does not require settings. This feature is only for convenience if you create a specific detector that requires settings.
--- ---
If this library is useful for you, say thanks [buying me a beer :beer:](https://www.paypal.me/oscarotero)!
[ico-version]: https://poser.pugx.org/embed/embed/v/stable [ico-version]: https://poser.pugx.org/embed/embed/v/stable
[ico-travis]: https://travis-ci.org/oscarotero/Embed.svg?branch=master
[ico-license]: https://poser.pugx.org/embed/embed/license [ico-license]: https://poser.pugx.org/embed/embed/license
[ico-scrutinizer]: https://scrutinizer-ci.com/g/oscarotero/Embed/badges/quality-score.png?s=79e37032db280b9795388124c030dcf4309343d1
[ico-sensiolabs]: https://insight.sensiolabs.com/projects/f0beab9f-fe41-47db-8806-373f80c50f9e/big.png
[ico-downloads]: https://poser.pugx.org/embed/embed/downloads [ico-downloads]: https://poser.pugx.org/embed/embed/downloads
[ico-m-downloads]: https://poser.pugx.org/embed/embed/d/monthly [ico-m-downloads]: https://poser.pugx.org/embed/embed/d/monthly
[ico-references]: https://www.versioneye.com/php/embed:embed/reference_badge.svg?style=flat
[link-packagist]: https://packagist.org/packages/embed/embed [link-packagist]: https://packagist.org/packages/embed/embed
[link-travis]: https://travis-ci.org/oscarotero/Embed
[link-scrutinizer]: https://scrutinizer-ci.com/g/oscarotero/Embed/
[link-sensiolabs]: https://insight.sensiolabs.com/projects/f0beab9f-fe41-47db-8806-373f80c50f9e
[link-references]: https://www.versioneye.com/php/embed:embed/references

View file

@ -24,19 +24,36 @@
"issues": "https://github.com/oscarotero/Embed/issues" "issues": "https://github.com/oscarotero/Embed/issues"
}, },
"require": { "require": {
"php": "^5.5|^7.0", "php": "^7.4|^8",
"ext-curl": "*", "ext-curl": "*",
"ext-dom": "*",
"ext-json": "*",
"ext-mbstring": "*", "ext-mbstring": "*",
"composer/ca-bundle": "^1.0" "composer/ca-bundle": "^1.0",
"oscarotero/html-parser": "^0.1.4",
"psr/http-message": "^1.0|^2.0",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"ml/json-ld": "^1.1"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": "^4.8|^5.7", "phpunit/phpunit": "^9.0",
"friendsofphp/php-cs-fixer": "^2.0" "friendsofphp/php-cs-fixer": "^2.0",
"nyholm/psr7": "^1.2",
"oscarotero/php-cs-fixer-config": "^1.0",
"brick/varexporter": "^0.3.1",
"symfony/css-selector": "^5.0"
},
"suggest": {
"symfony/css-selector": "If you want to get elements using css selectors"
}, },
"autoload": { "autoload": {
"psr-4": { "psr-4": {
"Embed\\": "src" "Embed\\": "src"
} },
"files": [
"src/functions.php"
]
}, },
"autoload-dev": { "autoload-dev": {
"psr-4": { "psr-4": {
@ -46,6 +63,10 @@
"scripts": { "scripts": {
"demo": "php -S localhost:8888 demo/index.php", "demo": "php -S localhost:8888 demo/index.php",
"test": "phpunit", "test": "phpunit",
"cs-fix": "php-cs-fixer fix ." "cs-fix": "php-cs-fixer fix",
"update-resources": [
"php scripts/update-oembed.php",
"php scripts/update-suffix.php"
]
} }
} }

View file

@ -1,22 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="All tests">
<directory>tests</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>ignore</group>
</exclude>
</groups>
</phpunit>

View file

@ -1,687 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Bag;
use Embed\DataInterface;
use Embed\Http\DispatcherInterface;
use Embed\Http\ImageResponse;
use Embed\Http\Response;
use Embed\Http\Url;
use Embed\Providers\Provider;
use Embed\Utils;
/**
* Base class extended by all adapters.
*
* @property null|string $title
* @property null|string $description
* @property null|string $url
* @property null|string $type
* @property array $tags
* @property array $feeds
* @property array $images
* @property array $imagesUrls
* @property null|string $image
* @property null|int $imageWidth
* @property null|int $imageHeight
* @property null|string $code
* @property null|int $width
* @property null|int $height
* @property null|float $aspectRatio
* @property null|string $authorName
* @property null|string $authorUrl
* @property array $providerIcons
* @property array $providerIconsUrls
* @property null|string $providerIcon
* @property null|string $providerName
* @property null|string $providerUrl
* @property null|string $publishedTime
*/
abstract class Adapter implements DataInterface
{
protected $config;
protected $dispatcher;
protected $response;
protected $providers = [];
/**
* Checks whether the response is valid to this Adapter.
*
* @param Response $response
*
* @return bool
*/
public static function check(Response $response)
{
return $response->isValid();
}
/**
* Constructor.
*
* @param Response $response
* @param array $config
* @param DispatcherInterface $dispatcher
*/
public function __construct(Response $response, array $config, DispatcherInterface $dispatcher)
{
$this->response = $response;
$this->config = new Bag($config);
$this->dispatcher = $dispatcher;
$this->init();
}
/**
* Initialize the providers
*/
abstract protected function init();
/**
* Magic method to execute methods to return paramaters
* For example, $source->sourceUrl executes $source->getSourceUrl().
*
* @param string $name The property name
*
* @return mixed
*/
public function __get($name)
{
$method = 'get'.$name;
if (method_exists($this, $method)) {
return $this->$name = $this->$method();
}
return null;
}
/**
* Magic method to execute methods to check if parameters are empty
*
* @param string $name The property name
*
* @return bool
*/
public function __isset($name)
{
$value = $this->$name;
return !empty($value);
}
/**
* Returns the dispatcher used.
*
* @return DispatcherInterface
*/
public function getDispatcher()
{
return $this->dispatcher;
}
/**
* Returns the main response instance.
*
* @return Response
*/
public function getResponse()
{
return $this->response;
}
/**
* Get a config value.
*
* @param string $name
* @param mixed $default
*
* @return string|null
*/
public function getConfig($name, $default = null)
{
$value = $this->config->get($name);
return $value === null ? $default : $value;
}
/**
* Get all providers.
*
* @return Provider[]
*/
public function getProviders()
{
return $this->providers;
}
/**
* {@inheritdoc}
*/
public function getTitle()
{
$default = $this->url;
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getTitle();
}, $default);
}
/**
* {@inheritdoc}
*/
public function getDescription()
{
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getDescription();
});
}
/**
* {@inheritdoc}
*/
public function getType()
{
$code = $this->code;
if (empty($code)) {
return 'link';
}
if (strpos($code, '</video>')) {
return 'video';
}
//Get the most repeated type
$types = [];
foreach ($this->providers as $provider) {
$type = $provider->getType();
if ($type !== null) {
if (!isset($types[$type])) {
$types[$type] = 0;
}
++$types[$type];
}
}
//If it has code, it's not a link
unset($types['link']);
return static::getBigger($types) ?: 'rich';
}
/**
* {@inheritdoc}
*/
public function getTags()
{
return $this->getAllFromProviders(function (Provider $provider) {
return $provider->getTags();
});
}
/**
* {@inheritdoc}
*/
public function getFeeds()
{
return $this->getAllFromProviders(function (Provider $provider) {
return $provider->getFeeds();
});
}
/**
* {@inheritdoc}
*/
public function getCode()
{
//Width and height deppends to the code
$this->width = null;
$this->height = null;
$codes = [];
foreach ($this->providers as $provider) {
$code = $provider->getCode();
if (!empty($code)) {
$codes[] = [
'code' => $code,
'width' => $provider->getWidth(),
'height' => $provider->getHeight(),
];
}
}
if (empty($codes)) {
return null;
}
//Use only html5 codes
$html5 = array_filter($codes, function (array $code) {
return strpos($code['code'], '</object>') === false && strpos($code['code'], '</embed>') === false;
});
//If it's not html5 codes, returns flash
if (empty($html5)) {
$code = current($codes);
} else {
$code = current($html5);
}
$this->width = is_numeric($code['width']) ? (int) $code['width'] : $code['width'];
$this->height = is_numeric($code['height']) ? (int) $code['height'] : $code['height'];
return $code['code'];
}
/**
* Returns the code as DOMNodeList elements
*
* @return \DOMNodeList|null
*/
public function getHtml()
{
$code = $this->code;
if (empty($code)) {
return;
}
$errors = libxml_use_internal_errors(true);
$entities = libxml_disable_entity_loader(true);
$dom = new \DOMDocument();
$dom->loadHTML($code);
libxml_use_internal_errors($errors);
libxml_disable_entity_loader($entities);
return Utils::xpathQuery($dom, 'descendant-or-self::body/*', false);
}
/**
* {@inheritdoc}
*/
public function getUrl()
{
$default = (string) $this->getResponse()->getUrl();
$blacklist = $this->getConfig('url_blacklist');
//some sites returns the homepage as canonical
$homeUrl = $this->getResponse()->getUrl()->getAbsolute('/');
return $this->getFirstFromProviders(function (Provider $provider) use ($blacklist, $homeUrl) {
$url = $provider->getUrl();
if ($homeUrl === $url || (!empty($blacklist) && Url::create($url)->match($blacklist))) {
return false;
}
return $url;
}, $default);
}
/**
* {@inheritdoc}
*/
public function getAuthorName()
{
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getAuthorName();
});
}
/**
* {@inheritdoc}
*/
public function getAuthorUrl()
{
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getAuthorUrl();
});
}
/**
* {@inheritdoc}
*/
public function getProviderIconsUrls()
{
$urls = [
$this->getResponse()->getUrl()->getAbsolute('/favicon.ico'),
$this->getResponse()->getUrl()->getAbsolute('/favicon.png'),
];
foreach ($this->providers as $provider) {
foreach ($provider->getProviderIconsUrls() as $url) {
if (!in_array($url, $urls, true)) {
$urls[] = $url;
}
}
}
return $urls;
}
/**
* Gets all icon provider urls found
* It returns also the width, height and mime-type.
*
* @return array
*/
public function getProviderIcons()
{
return $this->dispatchImagesInfo($this->providerIconsUrls);
}
/**
* Gets the best icon provider
*
* @return string|null
*/
public function getProviderIcon()
{
$icons = $this->providerIcons;
if (empty($icons)) {
return null;
}
$sizes = [];
foreach ($icons as $icon) {
$sizes[$icon['url']] = $icon['size'];
}
return static::getBigger($sizes);
}
/**
* {@inheritdoc}
*/
public function getProviderName()
{
$default = $this->getResponse()->getUrl()->getDomain();
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getProviderName();
}, $default);
}
/**
* {@inheritdoc}
*/
public function getProviderUrl()
{
$url = $this->getResponse()->getUrl();
$default = $url->getScheme().'://'.$url->getDomain(true);
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getProviderUrl();
}, $default);
}
/**
* {@inheritdoc}
*/
public function getImagesUrls()
{
$urls = $this->getAllFromProviders(function (Provider $provider) {
return $provider->getImagesUrls();
});
$blacklist = $this->getConfig('images_blacklist');
if (!empty($blacklist)) {
$urls = array_filter($urls, function ($url) use ($blacklist) {
return !Url::create($url)->match($blacklist);
});
}
return array_values($urls);
}
/**
* Gets all images found in the webpage
* It returns also the width, height and mime-type.
*
* @return array
*/
public function getImages()
{
return $this->dispatchImagesInfo($this->imagesUrls);
}
/**
* Gets the best image
*
* @return string|null
*/
public function getImage()
{
$this->imageWidth = null;
$this->imageHeight = null;
$images = $this->images;
$bigger = (bool) $this->getConfig('choose_bigger_image');
$minWidth = $this->getConfig('min_image_width', 1);
$minHeight = $this->getConfig('min_image_height', 1);
$images = array_filter($images, function ($image) use ($minWidth, $minHeight) {
return $image['width'] >= $minWidth && $image['height'] >= $minHeight;
});
if (empty($images)) {
return null;
}
reset($images);
$image = current($images);
if ($bigger) {
$sizes = [];
foreach ($images as $img) {
$sizes[$img['url']] = $img['size'];
}
$biggest = static::getBigger($sizes);
foreach ($images as $img) {
if ($biggest == $img['url']) {
$image = $img;
break;
}
}
}
$this->imageWidth = $image['width'];
$this->imageHeight = $image['height'];
return $image['url'];
}
/**
* Gets the image width.
*
* @return int|null
*/
public function getImageWidth()
{
$this->image = $this->getImage();
return $this->imageWidth;
}
/**
* Gets the image height.
*
* @return int|null
*/
public function getImageHeight()
{
$this->image = $this->getImage();
return $this->imageHeight;
}
/**
* {@inheritdoc}
*/
public function getWidth()
{
$this->code = $this->getCode();
return $this->width;
}
/**
* {@inheritdoc}
*/
public function getHeight()
{
$this->code = $this->getCode();
return $this->height;
}
/**
* Gets the aspect ratio of the embedded widget
* (useful to make it responsive).
*
* @return float|null
*/
public function getAspectRatio()
{
if ($this->width !== null
&& (strpos($this->width, '%') === false)
&& $this->height !== null && (strpos($this->height, '%') === false)) {
return round(($this->height / $this->width) * 100, 3);
}
return null;
}
/**
* {@inheritdoc}
*/
public function getPublishedTime()
{
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getPublishedTime();
});
}
/**
* {@inheritdoc}
*/
public function getLicense()
{
return $this->getFirstFromProviders(function (Provider $provider) {
return $provider->getLicense();
});
}
/**
* {@inheritdoc}
*/
public function getLinkedData()
{
return $this->getAllFromProviders(function (Provider $provider) {
return $provider->getLinkedData();
});
}
/**
* Get images info.
*
* @param array $urls
*
* @return array
*/
private function dispatchImagesInfo($urls)
{
if (empty($urls)) {
return [];
}
$requests = [];
foreach ($urls as $url) {
$requests[] = Url::create($url);
}
return array_map(
function (ImageResponse $response) {
return [
'url' => (string) $response->getUrl(),
'width' => $response->getWidth(),
'height' => $response->getHeight(),
'size' => $response->getWidth() * $response->getHeight(),
'mime' => $response->getContentType(),
];
},
$this->getDispatcher()->dispatchImages($requests)
);
}
/**
* Returns the key of the bigger value in an array
*
* @param array $values
*
* @return string|null
*/
protected static function getBigger(array $values)
{
$bigger = null;
foreach ($values as $value => $repeat) {
if ($bigger === null || $repeat > $values[$bigger]) {
$bigger = $value;
}
}
return $bigger;
}
/**
* Returns the first value of the providers
*
* @param callable $callable
* @param string|null $default
*
* @return string|null
*/
protected function getFirstFromProviders(callable $callable, $default = null)
{
$values = array_filter(array_map($callable, $this->providers));
return empty($values) ? $default : current($values);
}
/**
* Returns the all values from the providers
*
* @param callable $callable
*
* @return array
*/
protected function getAllFromProviders(callable $callable)
{
$values = array_filter(array_map($callable, $this->providers));
$all = [];
foreach ($values as $value) {
foreach ($value as $v) {
if (!in_array($v, $all, true)) {
$all[] = $v;
}
}
}
return $all;
}
}

View file

@ -1,57 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Http\Response;
use Embed\Utils;
use Embed\Providers\Api;
/**
* Adapter to provide information from archive.org API.
*/
class Archive extends Webpage
{
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && $response->getUrl()->match([
'archive.org/details/*',
]);
}
/**
* {@inheritdoc}
*/
protected function init()
{
parent::init();
$this->providers = ['archive' => new Api\Archive($this)] + $this->providers;
}
/**
* {@inheritdoc}
*/
public function getCode()
{
return Utils::iframe(str_replace('/details/', '/embed/', $this->url), $this->width, $this->height);
}
/**
* {@inheritdoc}
*/
public function getWidth()
{
return 640;
}
/**
* {@inheritdoc}
*/
public function getHeight()
{
return 480;
}
}

View file

@ -1,48 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Utils;
use Embed\Http\Response;
/**
* Adapter to get the embed code from play.cadenaser.com.
*/
class Cadenaser extends Webpage
{
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && $response->getUrl()->match([
'play.cadenaser.com/audio/*',
]);
}
/**
* {@inheritdoc}
*/
public function getCode()
{
$url = $this->getResponse()->getUrl();
return Utils::iframe($url->withPath('/widget/'.$url->getPath()), $this->width, $this->height);
}
/**
* {@inheritdoc}
*/
public function getWidth()
{
return 620;
}
/**
* {@inheritdoc}
*/
public function getHeight()
{
return 100;
}
}

View file

@ -1,35 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Http\Response;
use Embed\Utils;
/**
* Adapter to get the embed code from cartodb.
*/
class Carto extends Webpage
{
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && $response->getUrl()->match([
'*.carto.com/viz/*/public_map',
]);
}
/**
* {@inheritdoc}
*/
public function getCode()
{
$this->width = null;
$this->height = 520;
$url = $this->getResponse()->getUrl()->withDirectoryPosition(2, 'embed_map');
return Utils::iframe($url, '100%', $this->height);
}
}

View file

@ -1,41 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Http\Response;
use Embed\Http\Url;
use Embed\Utils;
/**
* Adapter provider more information from cnn.com.
*/
class Cnn extends Webpage
{
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && $response->getUrl()->match([
'*.cnn.com/videos/*',
]);
}
/**
* {@inheritdoc}
*/
public function getCode()
{
$url = Url::create('https://fave.api.cnn.io/v1/fav/')
->withQueryParameters([
'video' => implode('/', $this->getResponse()->getUrl()->getSlicePath(1)),
'customer' => 'cnn',
'env' => 'prod'
]);
$this->width = 416;
$this->height = 234;
return Utils::iframe($url, $this->width, $this->height);
}
}

View file

@ -1,33 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Http\Response;
use Embed\Utils;
use Embed\Providers\Api;
/**
* Adapter provider more information from some facebook pages.
*/
class Facebook extends Webpage
{
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && $response->getUrl()->match([
'www.facebook.com/*',
]);
}
/**
* {@inheritdoc}
*/
protected function init()
{
parent::init();
$this->providers = ['facebook' => new Api\Facebook($this)] + $this->providers;
}
}

View file

@ -1,98 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Http\Response;
use Embed\Utils;
use Embed\Providers;
/**
* Adapter to provide information from raw files.
*/
class File extends Adapter
{
private static $contentTypes = [
'video/ogg' => ['video', 'videoHtml'],
'application/ogg' => ['video', 'videoHtml'],
'video/ogv' => ['video', 'videoHtml'],
'video/webm' => ['video', 'videoHtml'],
'video/mp4' => ['video', 'videoHtml'],
'audio/ogg' => ['audio', 'audioHtml'],
'audio/mp3' => ['audio', 'audioHtml'],
'audio/mpeg' => ['audio', 'audioHtml'],
'audio/webm' => ['audio', 'audioHtml'],
'image/jpeg' => ['photo', 'imageHtml'],
'image/jpg' => ['photo', 'imageHtml'],
'image/gif' => ['photo', 'imageHtml'],
'image/png' => ['photo', 'imageHtml'],
'image/bmp' => ['photo', 'imageHtml'],
'image/ico' => ['photo', 'imageHtml'],
'text/rtf' => ['rich', 'google'],
'application/pdf' => ['rich', 'google'],
'application/msword' => ['rich', 'google'],
'application/vnd.ms-powerpoint' => ['rich', 'google'],
'application/vnd.ms-excel' => ['rich', 'google'],
'application/zip' => ['rich', 'google'],
'application/postscript' => ['rich', 'google'],
'application/octet-stream' => ['rich', 'google'],
];
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && isset(self::$contentTypes[$response->getContentType()]);
}
/**
* {@inheritdoc}
*/
protected function init()
{
$this->providers = [
'oembed' => new Providers\OEmbed($this),
];
}
/**
* {@inheritdoc}
*/
public function getType()
{
return self::$contentTypes[$this->getResponse()->getContentType()][0];
}
/**
* {@inheritdoc}
*/
public function getCode()
{
if (($code = parent::getcode())) {
return $code;
}
switch (self::$contentTypes[$this->getResponse()->getContentType()][1]) {
case 'videoHtml':
return Utils::videoHtml($this->image, $this->url, $this->imageWidth, $this->imageHeight);
case 'audioHtml':
return Utils::audioHtml($this->url);
case 'google':
return Utils::google($this->url);
}
}
/**
* {@inheritdoc}
*/
public function getImagesUrls()
{
if ($this->type === 'photo') {
return [$this->url];
}
return [];
}
}

View file

@ -1,47 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Http\Response;
use Embed\Utils;
/**
* Adapter provider more information from flickr.
*/
class Flickr extends Webpage
{
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && $response->getUrl()->match([
'www.flickr.com/photos/*',
]);
}
/**
* {@inheritdoc}
*/
public function getCode()
{
$code = parent::getCode();
if (empty($code)) {
$this->width = 640;
$this->height = 425;
$code = Utils::iframe($this->getResponse()->getUrl()->withAddedPath('player'), $this->width, $this->height);
}
return $code;
}
/**
* {@inheritdoc}
*/
public function getProviderName()
{
return 'Flickr';
}
}

View file

@ -1,74 +0,0 @@
<?php
namespace Embed\Adapters;
use Embed\Http\Response;
use Embed\Providers\Api;
/**
* Adapter to get the embed code from gist.github.com.
*/
class Github extends Webpage
{
/**
* {@inheritdoc}
*/
public static function check(Response $response)
{
return $response->isValid() && $response->getUrl()->match([
'gist.github.com/*/*',
'github.com/*',
]);
}
/**
* {@inheritdoc}
*/
protected function init()
{
parent::init();
if ($this->getResponse()->getUrl()->getHost() === 'gist.github.com') {
$this->providers = ['gist' => new Api\Gist($this)] + $this->providers;
}
}
/**
* {@inheritdoc}
*/
public function getUrl()
{
//Open graph returns as canonical url the main repo url, instead the file
return (string) $this->getResponse()->getUrl();
}
/**
* {@inheritdoc}
*/
public function getCode()
{
$this->width = null;
$this->height = null;
$url = $this->getResponse()->getUrl();
if ($url->match('github.com/*/*/blob/*')) {
$username = $url->getDirectoryPosition(0);
$repo = $url->getDirectoryPosition(1);
$ref = $url->getDirectoryPosition(3);
$path_to_file = implode('/', $url->getSlicePath(4));
switch ($url->getExtension()) {
case 'geojson':
//https://help.github.com/articles/mapping-geojson-files-on-github/#embedding-your-map-elsewhere
return "<script src=\"https://embed.githubusercontent.com/view/geojson/{$username}/{$repo}/{$ref}/{$path_to_file}\"></script>";
case 'stl':
//https://help.github.com/articles/3d-file-viewer/#embedding-your-model-elsewhere
return "<script src=\"https://embed.githubusercontent.com/view/3d/{$username}/{$repo}/{$ref}/{$path_to_file}\"></script>";
}
}
return parent::getCode();
}
}

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