feat(cloudron): add tirreno package artifacts

- Add CloudronStack/output/CloudronPackages-Artifacts/tirreno/ directory and its contents
- Includes package manifest, Dockerfile, source code, documentation, and build artifacts
- Add tirreno-1761840148.tar.gz as a build artifact
- Add tirreno-cloudron-package-1761841304.tar.gz as the Cloudron package
- Include all necessary files for the tirreno Cloudron package

This adds the complete tirreno Cloudron package artifacts to the repository.
This commit is contained in:
2025-10-30 11:43:06 -05:00
parent 0ce353ea9d
commit 91d52d2de5
1692 changed files with 202851 additions and 0 deletions

View File

@@ -0,0 +1,2 @@
github: ikkez
buy_me_a_coffee: ikkez

View File

@@ -0,0 +1,621 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

View File

@@ -0,0 +1,29 @@
# fatfree-core
Fat-Free Framework core library
### Usage:
First make sure to add a proper url rewrite configuration to your server, see https://fatfreeframework.com/3.6/routing-engine#DynamicWebSites
**without composer:**
```php
$f3 = require('lib/base.php');
```
**with composer:**
```
composer require bcosca/fatfree-core
```
```php
require("vendor/autoload.php");
$f3 = \Base::instance();
```
---
For the main repository (demo package), see https://github.com/bcosca/fatfree
For the test bench and unit tests, see https://github.com/f3-factory/fatfree-dev
For the user guide, see https://fatfreeframework.com/user-guide
For the documentation, see https://fatfreeframework.com/api-reference

View File

@@ -0,0 +1,202 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Data validator
class Audit extends Prefab {
//@{ User agents
const
UA_Mobile='android|blackberry|phone|ipod|palm|windows\s+ce',
UA_Desktop='bsd|linux|os\s+[x9]|solaris|windows',
UA_Bot='bot|crawl|slurp|spider';
//@}
/**
* Return TRUE if string is a valid URL
* @return bool
* @param $str string
**/
function url($str) {
return is_string(filter_var($str,FILTER_VALIDATE_URL))
&& !preg_match('/^(javascript|php):\/\/.*$/i', $str);
}
/**
* Return TRUE if string is a valid e-mail address;
* Check DNS MX records if specified
* @return bool
* @param $str string
* @param $mx boolean
**/
function email($str,$mx=TRUE) {
$hosts=[];
return is_string(filter_var($str,FILTER_VALIDATE_EMAIL)) &&
(!$mx || getmxrr(substr($str,strrpos($str,'@')+1),$hosts));
}
/**
* Return TRUE if string is a valid IPV4 address
* @return bool
* @param $addr string
**/
function ipv4($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_IP,FILTER_FLAG_IPV4);
}
/**
* Return TRUE if string is a valid IPV6 address
* @return bool
* @param $addr string
**/
function ipv6($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_IP,FILTER_FLAG_IPV6);
}
/**
* Return TRUE if IP address is within private range
* @return bool
* @param $addr string
**/
function isprivate($addr) {
return (bool)filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)
&& !(bool)filter_var($addr, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE);
}
/**
* Return TRUE if IP address is within reserved range
* @return bool
* @param $addr string
**/
function isreserved($addr) {
return !(bool)filter_var($addr,FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4|FILTER_FLAG_IPV6|FILTER_FLAG_NO_RES_RANGE);
}
/**
* Return TRUE if IP address is neither private nor reserved
* @return bool
* @param $addr string
**/
function ispublic($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4|FILTER_FLAG_IPV6|
FILTER_FLAG_NO_PRIV_RANGE|FILTER_FLAG_NO_RES_RANGE);
}
/**
* Return TRUE if user agent is a desktop browser
* @return bool
* @param $agent string
**/
function isdesktop($agent=NULL) {
if (!isset($agent))
$agent=Base::instance()->AGENT;
return (bool)preg_match('/('.self::UA_Desktop.')/i',$agent) &&
!$this->ismobile($agent);
}
/**
* Return TRUE if user agent is a mobile device
* @return bool
* @param $agent string
**/
function ismobile($agent=NULL) {
if (!isset($agent))
$agent=Base::instance()->AGENT;
return (bool)preg_match('/('.self::UA_Mobile.')/i',$agent);
}
/**
* Return TRUE if user agent is a Web bot
* @return bool
* @param $agent string
**/
function isbot($agent=NULL) {
if (!isset($agent))
$agent=Base::instance()->AGENT;
return (bool)preg_match('/('.self::UA_Bot.')/i',$agent);
}
/**
* Return TRUE if specified ID has a valid (Luhn) Mod-10 check digit
* @return bool
* @param $id string
**/
function mod10($id) {
if (!ctype_digit($id))
return FALSE;
$id=strrev($id);
$sum=0;
for ($i=0,$l=strlen($id);$i<$l;++$i)
$sum+=$id[$i]+$i%2*(($id[$i]>4)*-4+$id[$i]%5);
return !($sum%10);
}
/**
* Return credit card type if number is valid
* @return string|FALSE
* @param $id string
**/
function card($id) {
$id=preg_replace('/[^\d]/','',$id);
if ($this->mod10($id)) {
if (preg_match('/^3[47][0-9]{13}$/',$id))
return 'American Express';
if (preg_match('/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/',$id))
return 'Diners Club';
if (preg_match('/^6(?:011|5[0-9][0-9])[0-9]{12}$/',$id))
return 'Discover';
if (preg_match('/^(?:2131|1800|35\d{3})\d{11}$/',$id))
return 'JCB';
if (preg_match('/^5[1-5][0-9]{14}$|'.
'^(222[1-9]|2[3-6]\d{2}|27[0-1]\d|2720)\d{12}$/',$id))
return 'MasterCard';
if (preg_match('/^4[0-9]{12}(?:[0-9]{3})?$/',$id))
return 'Visa';
}
return FALSE;
}
/**
* Return entropy estimate of a password (NIST 800-63)
* @return int|float
* @param $str string
**/
function entropy($str) {
$len=strlen($str);
return 4*min($len,1)+($len>1?(2*(min($len,8)-1)):0)+
($len>8?(1.5*(min($len,20)-8)):0)+($len>20?($len-20):0)+
6*(bool)(preg_match(
'/[A-Z].*?[0-9[:punct:]]|[0-9[:punct:]].*?[A-Z]/',$str));
}
/**
* Return TRUE if string is a valid MAC address including EUI-64 format
* @return bool
* @param $addr string
**/
function mac($addr) {
return (bool)filter_var($addr,FILTER_VALIDATE_MAC)
|| preg_match('/^([0-9a-f]{2}:){3}ff:fe(:[0-9a-f]{2}){3}$/i', $addr);
}
}

View File

@@ -0,0 +1,262 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Authorization/authentication plug-in
class Auth {
//@{ Error messages
const
E_LDAP='LDAP connection failure',
E_SMTP='SMTP connection failure';
//@}
protected
//! Auth storage
$storage,
//! Mapper object
$mapper,
//! Storage options
$args,
//! Custom compare function
$func;
/**
* Jig storage handler
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
protected function _jig($id,$pw,$realm) {
$success = (bool)
call_user_func_array(
[$this->mapper,'load'],
[
array_merge(
[
'@'.$this->args['id'].'==?'.
($this->func?'':' AND @'.$this->args['pw'].'==?').
(isset($this->args['realm'])?
(' AND @'.$this->args['realm'].'==?'):''),
$id
],
($this->func?[]:[$pw]),
(isset($this->args['realm'])?[$realm]:[])
)
]
);
if ($success && $this->func)
$success = call_user_func($this->func,$pw,$this->mapper->get($this->args['pw']));
return $success;
}
/**
* MongoDB storage handler
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
protected function _mongo($id,$pw,$realm) {
$success = (bool)
$this->mapper->load(
[$this->args['id']=>$id]+
($this->func?[]:[$this->args['pw']=>$pw])+
(isset($this->args['realm'])?
[$this->args['realm']=>$realm]:[])
);
if ($success && $this->func)
$success = call_user_func($this->func,$pw,$this->mapper->get($this->args['pw']));
return $success;
}
/**
* SQL storage handler
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
protected function _sql($id,$pw,$realm) {
$success = (bool)
call_user_func_array(
[$this->mapper,'load'],
[
array_merge(
[
$this->args['id'].'=?'.
($this->func?'':' AND '.$this->args['pw'].'=?').
(isset($this->args['realm'])?
(' AND '.$this->args['realm'].'=?'):''),
$id
],
($this->func?[]:[$pw]),
(isset($this->args['realm'])?[$realm]:[])
)
]
);
if ($success && $this->func)
$success = call_user_func($this->func,$pw,$this->mapper->get($this->args['pw']));
return $success;
}
/**
* LDAP storage handler
* @return bool
* @param $id string
* @param $pw string
**/
protected function _ldap($id,$pw) {
$port=(int)($this->args['port']?:389);
$filter=$this->args['filter']=$this->args['filter']?:"uid=".$id;
$this->args['attr']=$this->args['attr']?:["uid"];
array_walk($this->args['attr'],
function($attr)use(&$filter,$id) {
$filter=str_ireplace($attr."=*",$attr."=".$id,$filter);});
$dc=@ldap_connect($this->args['dc'],$port);
if ($dc &&
ldap_set_option($dc,LDAP_OPT_PROTOCOL_VERSION,3) &&
ldap_set_option($dc,LDAP_OPT_REFERRALS,0) &&
ldap_bind($dc,$this->args['rdn'],$this->args['pw']) &&
($result=ldap_search($dc,$this->args['base_dn'],
$filter,$this->args['attr'])) &&
ldap_count_entries($dc,$result) &&
($info=ldap_get_entries($dc,$result)) &&
$info['count']==1 &&
@ldap_bind($dc,$info[0]['dn'],$pw) &&
@ldap_close($dc)) {
return in_array($id,(array_map(function($value){return $value[0];},
array_intersect_key($info[0],
array_flip($this->args['attr'])))),TRUE);
}
throw new \Exception(self::E_LDAP);
}
/**
* SMTP storage handler
* @return bool
* @param $id string
* @param $pw string
**/
protected function _smtp($id,$pw) {
$socket=@fsockopen(
(strtolower($this->args['scheme'])=='ssl'?
'ssl://':'').$this->args['host'],
$this->args['port']);
$dialog=function($cmd=NULL) use($socket) {
if (!is_null($cmd))
fputs($socket,$cmd."\r\n");
$reply='';
while (!feof($socket) &&
($info=stream_get_meta_data($socket)) &&
!$info['timed_out'] && $str=fgets($socket,4096)) {
$reply.=$str;
if (preg_match('/(?:^|\n)\d{3} .+\r\n/s',
$reply))
break;
}
return $reply;
};
if ($socket) {
stream_set_blocking($socket,TRUE);
$dialog();
$fw=Base::instance();
$dialog('EHLO '.$fw->HOST);
if (strtolower($this->args['scheme'])=='tls') {
$dialog('STARTTLS');
stream_socket_enable_crypto(
$socket,TRUE,STREAM_CRYPTO_METHOD_TLS_CLIENT);
$dialog('EHLO '.$fw->HOST);
}
// Authenticate
$dialog('AUTH LOGIN');
$dialog(base64_encode($id));
$reply=$dialog(base64_encode($pw));
$dialog('QUIT');
fclose($socket);
return (bool)preg_match('/^235 /',$reply);
}
throw new \Exception(self::E_SMTP);
}
/**
* Login auth mechanism
* @return bool
* @param $id string
* @param $pw string
* @param $realm string
**/
function login($id,$pw,$realm=NULL) {
return $this->{'_'.$this->storage}($id,$pw,$realm);
}
/**
* HTTP basic auth mechanism
* @return bool
* @param $func callback
**/
function basic($func=NULL) {
$fw=Base::instance();
$realm=$fw->REALM;
$hdr=NULL;
if (isset($_SERVER['HTTP_AUTHORIZATION']))
$hdr=$_SERVER['HTTP_AUTHORIZATION'];
elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
$hdr=$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
if (!empty($hdr))
list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW'])=
explode(':',base64_decode(substr($hdr,6)));
if (isset($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) &&
$this->login(
$_SERVER['PHP_AUTH_USER'],
$func?
$fw->call($func,$_SERVER['PHP_AUTH_PW']):
$_SERVER['PHP_AUTH_PW'],
$realm
))
return TRUE;
if (PHP_SAPI!='cli')
header('WWW-Authenticate: Basic realm="'.$realm.'"');
$fw->status(401);
return FALSE;
}
/**
* Instantiate class
* @return object
* @param $storage string|object
* @param $args array
* @param $func callback
**/
function __construct($storage,?array $args=NULL,$func=NULL) {
if (is_object($storage) && is_a($storage,'DB\Cursor')) {
$this->storage=$storage->dbtype();
$this->mapper=$storage;
unset($ref);
}
else
$this->storage=$storage;
$this->args=$args;
$this->func=$func;
}
}

View File

@@ -0,0 +1,238 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Session-based pseudo-mapper
class Basket extends Magic {
//@{ Error messages
const
E_Field='Undefined field %s';
//@}
protected
//! Session key
$key,
//! Current item identifier
$id,
//! Current item contents
$item=[];
/**
* Return TRUE if field is defined
* @return bool
* @param $key string
**/
function exists($key) {
return array_key_exists($key,$this->item);
}
/**
* Assign value to field
* @return scalar|FALSE
* @param $key string
* @param $val scalar
**/
function set($key,$val) {
return ($key=='_id')?FALSE:($this->item[$key]=$val);
}
/**
* Retrieve value of field
* @return scalar|FALSE
* @param $key string
**/
function &get($key) {
if ($key=='_id')
return $this->id;
if (array_key_exists($key,$this->item))
return $this->item[$key];
throw new \Exception(sprintf(self::E_Field,$key));
}
/**
* Delete field
* @return NULL
* @param $key string
**/
function clear($key) {
unset($this->item[$key]);
}
/**
* Return items that match key/value pair;
* If no key/value pair specified, return all items
* @return array
* @param $key string
* @param $val mixed
**/
function find($key=NULL,$val=NULL) {
$out=[];
if (isset($_SESSION[$this->key])) {
foreach ($_SESSION[$this->key] as $id=>$item)
if (!isset($key) ||
array_key_exists($key,$item) && $item[$key]==$val ||
$key=='_id' && $id==$val) {
$obj=clone($this);
$obj->id=$id;
$obj->item=$item;
$out[]=$obj;
}
}
return $out;
}
/**
* Return first item that matches key/value pair
* @return object|FALSE
* @param $key string
* @param $val mixed
**/
function findone($key,$val) {
return ($data=$this->find($key,$val))?$data[0]:FALSE;
}
/**
* Map current item to matching key/value pair
* @return array
* @param $key string
* @param $val mixed
**/
function load($key,$val) {
if ($found=$this->find($key,$val)) {
$this->id=$found[0]->id;
return $this->item=$found[0]->item;
}
$this->reset();
return [];
}
/**
* Return TRUE if current item is empty/undefined
* @return bool
**/
function dry() {
return !$this->item;
}
/**
* Return number of items in basket
* @return int
**/
function count() {
return isset($_SESSION[$this->key])?count($_SESSION[$this->key]):0;
}
/**
* Save current item
* @return array
**/
function save() {
if (!$this->id)
$this->id=uniqid('',TRUE);
$_SESSION[$this->key][$this->id]=$this->item;
return $this->item;
}
/**
* Erase item matching key/value pair
* @return bool
* @param $key string
* @param $val mixed
**/
function erase($key,$val) {
$found=$this->find($key,$val);
if ($found && $id=$found[0]->id) {
unset($_SESSION[$this->key][$id]);
if ($id==$this->id)
$this->reset();
return TRUE;
}
return FALSE;
}
/**
* Reset cursor
* @return NULL
**/
function reset() {
$this->id=NULL;
$this->item=[];
}
/**
* Empty basket
* @return NULL
**/
function drop() {
unset($_SESSION[$this->key]);
}
/**
* Hydrate item using hive array variable
* @return NULL
* @param $var array|string
**/
function copyfrom($var) {
if (is_string($var))
$var=\Base::instance()->$var;
foreach ($var as $key=>$val)
$this->set($key,$val);
}
/**
* Populate hive array variable with item contents
* @return NULL
* @param $key string
**/
function copyto($key) {
$var=&\Base::instance()->ref($key);
foreach ($this->item as $key=>$field)
$var[$key]=$field;
}
/**
* Check out basket contents
* @return array
**/
function checkout() {
if (isset($_SESSION[$this->key])) {
$out=$_SESSION[$this->key];
unset($_SESSION[$this->key]);
return $out;
}
return [];
}
/**
* Instantiate class
* @return void
* @param $key string
**/
function __construct($key='basket') {
$this->key=$key;
if (session_status()!=PHP_SESSION_ACTIVE)
session_start();
Base::instance()->sync('SESSION');
$this->reset();
}
}

View File

@@ -0,0 +1,96 @@
<?php
/**
* Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
*
* This file is part of the Fat-Free Framework (http://fatfreeframework.com).
*
* This 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 later.
*
* Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*
**/
/**
* Lightweight password hashing library (PHP 5.5+ only)
* @deprecated Use http://php.net/manual/en/ref.password.php instead
**/
class Bcrypt extends Prefab {
//@{ Error messages
const
E_CostArg='Invalid cost parameter',
E_SaltArg='Salt must be at least 22 alphanumeric characters';
//@}
//! Default cost
const
COST=10;
/**
* Generate bcrypt hash of string
* @return string|FALSE
* @param $pw string
* @param $salt string
* @param $cost int
**/
function hash($pw,$salt=NULL,$cost=self::COST) {
if ($cost<4 || $cost>31)
throw new \Exception(self::E_CostArg);
$len=22;
if ($salt) {
if (!preg_match('/^[[:alnum:]\.\/]{'.$len.',}$/',$salt))
throw new \Exception(self::E_SaltArg);
}
else {
$raw=16;
$iv='';
if (!$iv && extension_loaded('openssl'))
$iv=openssl_random_pseudo_bytes($raw);
if (!$iv)
for ($i=0;$i<$raw;++$i)
$iv.=chr(mt_rand(0,255));
$salt=str_replace('+','.',base64_encode($iv));
}
$salt=substr($salt,0,$len);
$hash=crypt($pw,sprintf('$2y$%02d$',$cost).$salt);
return strlen($hash)>13?$hash:FALSE;
}
/**
* Check if password is still strong enough
* @return bool
* @param $hash string
* @param $cost int
**/
function needs_rehash($hash,$cost=self::COST) {
list($pwcost)=sscanf($hash,"$2y$%d$");
return $pwcost<$cost;
}
/**
* Verify password against hash using timing attack resistant approach
* @return bool
* @param $pw string
* @param $hash string
**/
function verify($pw,$hash) {
$val=crypt($pw,$hash);
$len=strlen($val);
if ($len!=strlen($hash) || $len<14)
return FALSE;
$out=0;
for ($i=0;$i<$len;++$i)
$out|=(ord($val[$i])^ord($hash[$i]));
return $out===0;
}
}

View File

@@ -0,0 +1,487 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace CLI;
//! RFC6455 WebSocket server
class WS {
const
//! UUID magic string
Magic='258EAFA5-E914-47DA-95CA-C5AB0DC85B11',
//! Max packet size
Packet=65536;
//@{ Mask bits for first byte of header
const
Text=0x01,
Binary=0x02,
Close=0x08,
Ping=0x09,
Pong=0x0a,
OpCode=0x0f,
Finale=0x80;
//@}
//@{ Mask bits for second byte of header
const
Length=0x7f;
//@}
protected
$addr,
$ctx,
$wait,
$sockets,
$protocol,
$agents=[],
$events=[];
/**
* Allocate stream socket
* @return NULL
* @param $socket resource
**/
function alloc($socket) {
if (is_bool($buf=$this->read($socket)))
return;
// Get WebSocket headers
$hdrs=[];
$EOL="\r\n";
$verb=NULL;
$uri=NULL;
foreach (explode($EOL,trim($buf)) as $line)
if (preg_match('/^(\w+)\s(.+)\sHTTP\/[\d.]{1,3}$/',
trim($line),$match)) {
$verb=$match[1];
$uri=$match[2];
}
else
if (preg_match('/^(.+): (.+)/',trim($line),$match))
// Standardize header
$hdrs[
strtr(
ucwords(
strtolower(
strtr($match[1],'-',' ')
)
),' ','-'
)
]=$match[2];
else {
$this->close($socket);
return;
}
if (empty($hdrs['Upgrade']) &&
empty($hdrs['Sec-Websocket-Key'])) {
// Not a WebSocket request
if ($verb && $uri)
$this->write(
$socket,
'HTTP/1.1 400 Bad Request'.$EOL.
'Connection: close'.$EOL.$EOL
);
$this->close($socket);
return;
}
// Handshake
$buf='HTTP/1.1 101 Switching Protocols'.$EOL.
'Upgrade: websocket'.$EOL.
'Connection: Upgrade'.$EOL;
if (isset($hdrs['Sec-Websocket-Protocol']))
$buf.='Sec-WebSocket-Protocol: '.
$hdrs['Sec-Websocket-Protocol'].$EOL;
$buf.='Sec-WebSocket-Accept: '.
base64_encode(
sha1($hdrs['Sec-Websocket-Key'].WS::Magic,TRUE)
).$EOL.$EOL;
if ($this->write($socket,$buf)) {
// Connect agent to server
$this->sockets[(int)$socket]=$socket;
$this->agents[(int)$socket]=
new Agent($this,$socket,$verb,$uri,$hdrs);
}
}
/**
* Close stream socket
* @return NULL
* @param $socket resource
**/
function close($socket) {
if (isset($this->agents[(int)$socket]))
unset($this->sockets[(int)$socket],$this->agents[(int)$socket]);
stream_socket_shutdown($socket,STREAM_SHUT_WR);
@fclose($socket);
}
/**
* Read from stream socket
* @return string|FALSE
* @param $socket resource
* @param $len int
**/
function read($socket,$len=0) {
if (!$len)
$len=WS::Packet;
if (is_string($buf=@fread($socket,$len)) &&
strlen($buf) && strlen($buf)<$len)
return $buf;
if (isset($this->events['error']) &&
is_callable($func=$this->events['error']))
$func($this);
$this->close($socket);
return FALSE;
}
/**
* Write to stream socket
* @return int|FALSE
* @param $socket resource
* @param $buf string
**/
function write($socket,$buf) {
for ($i=0,$bytes=0;$i<strlen($buf);$i+=$bytes) {
if (($bytes=@fwrite($socket,substr($buf,$i))) &&
@fflush($socket))
continue;
if (isset($this->events['error']) &&
is_callable($func=$this->events['error']))
$func($this);
$this->close($socket);
return FALSE;
}
return $bytes;
}
/**
* Return socket agents
* @return array
* @param $uri string
***/
function agents($uri=NULL) {
return array_filter(
$this->agents,
/**
* @var $val Agent
* @return bool
*/
function($val) use($uri) {
return $uri?($val->uri()==$uri):TRUE;
}
);
}
/**
* Return event handlers
* @return array
**/
function events() {
return $this->events;
}
/**
* Bind function to event handler
* @return object
* @param $event string
* @param $func callable
**/
function on($event,$func) {
$this->events[$event]=$func;
return $this;
}
/**
* Terminate server
**/
function kill() {
die;
}
/**
* Execute the server process
**/
function run() {
// Assign signal handlers
declare(ticks=1);
pcntl_signal(SIGINT,[$this,'kill']);
pcntl_signal(SIGTERM,[$this,'kill']);
gc_enable();
// Activate WebSocket listener
$listen=stream_socket_server(
$this->addr,$errno,$errstr,
STREAM_SERVER_BIND|STREAM_SERVER_LISTEN,
$this->ctx
);
$socket=socket_import_stream($listen);
register_shutdown_function(function() use($listen) {
foreach ($this->sockets as $socket)
if ($socket!=$listen)
$this->close($socket);
$this->close($listen);
if (isset($this->events['stop']) &&
is_callable($func=$this->events['stop']))
$func($this);
});
if ($errstr)
throw new \Exception($errstr);
if (isset($this->events['start']) &&
is_callable($func=$this->events['start']))
$func($this);
$this->sockets=[(int)$listen=>$listen];
$empty=[];
$wait=$this->wait;
while (TRUE) {
$active=$this->sockets;
$mark=microtime(TRUE);
$count=@stream_select(
$active,$empty,$empty,(int)$wait,round(1e6*($wait-(int)$wait))
);
if (is_bool($count) && $wait) {
if (isset($this->events['error']) &&
is_callable($func=$this->events['error']))
$func($this);
die;
}
if ($count) {
// Process active connections
foreach ($active as $socket) {
if (!is_resource($socket))
continue;
if ($socket==$listen) {
if ($socket=@stream_socket_accept($listen,0))
$this->alloc($socket);
else
if (isset($this->events['error']) &&
is_callable($func=$this->events['error']))
$func($this);
}
else {
$id=(int)$socket;
if (isset($this->agents[$id]))
$this->agents[$id]->fetch();
}
}
$wait-=microtime(TRUE)-$mark;
while ($wait<1e-6) {
$wait+=$this->wait;
$count=0;
}
}
if (!$count) {
$mark=microtime(TRUE);
foreach ($this->sockets as $id=>$socket) {
if (!is_resource($socket))
continue;
if ($socket!=$listen &&
isset($this->agents[$id]) &&
isset($this->events['idle']) &&
is_callable($func=$this->events['idle']))
$func($this->agents[$id]);
}
$wait=$this->wait-microtime(TRUE)+$mark;
}
gc_collect_cycles();
}
}
/**
* @param $addr string
* @param $ctx resource
* @param $wait int
**/
function __construct($addr,$ctx=NULL,$wait=60) {
$this->addr=$addr;
$this->ctx=$ctx?:stream_context_create();
$this->wait=$wait;
$this->events=[];
}
}
//! RFC6455 remote socket
class Agent {
protected
$server,
$id,
$socket,
$flag,
$verb,
$uri,
$headers;
/**
* Return server instance
* @return WS
**/
function server() {
return $this->server;
}
/**
* Return socket ID
* @return string
**/
function id() {
return $this->id;
}
/**
* Return socket
* @return resource
**/
function socket() {
return $this->socket;
}
/**
* Return request method
* @return string
**/
function verb() {
return $this->verb;
}
/**
* Return request URI
* @return string
**/
function uri() {
return $this->uri;
}
/**
* Return socket headers
* @return array
**/
function headers() {
return $this->headers;
}
/**
* Frame and transmit payload
* @return string|FALSE
* @param $op int
* @param $data string
**/
function send($op,$data='') {
$server=$this->server;
$mask=WS::Finale | $op & WS::OpCode;
$len=strlen($data);
$buf='';
if ($len>0xffff)
$buf=pack('CCNN',$mask,0x7f,$len);
elseif ($len>0x7d)
$buf=pack('CCn',$mask,0x7e,$len);
else
$buf=pack('CC',$mask,$len);
$buf.=$data;
if (is_bool($server->write($this->socket,$buf)))
return FALSE;
if (!in_array($op,[WS::Pong,WS::Close]) &&
isset($this->server->events()['send']) &&
is_callable($func=$this->server->events()['send']))
$func($this,$op,$data);
return $data;
}
/**
* Retrieve and unmask payload
* @return bool|NULL
**/
function fetch() {
// Unmask payload
$server=$this->server;
if (is_bool($buf=$server->read($this->socket)))
return FALSE;
while($buf) {
$op=ord($buf[0]) & WS::OpCode;
$len=ord($buf[1]) & WS::Length;
$pos=2;
if ($len==0x7e) {
$len=ord($buf[2])*256+ord($buf[3]);
$pos+=2;
}
else
if ($len==0x7f) {
for ($i=0,$len=0;$i<8;++$i)
$len=$len*256+ord($buf[$i+2]);
$pos+=8;
}
for ($i=0,$mask=[];$i<4;++$i)
$mask[$i]=ord($buf[$pos+$i]);
$pos+=4;
if (strlen($buf)<$len+$pos)
return FALSE;
for ($i=0,$data='';$i<$len;++$i)
$data.=chr(ord($buf[$pos+$i])^$mask[$i%4]);
// Dispatch
switch ($op & WS::OpCode) {
case WS::Ping:
$this->send(WS::Pong);
break;
case WS::Close:
$server->close($this->socket);
break;
case WS::Text:
$data=trim($data);
case WS::Binary:
if (isset($this->server->events()['receive']) &&
is_callable($func=$this->server->events()['receive']))
$func($this,$op,$data);
break;
}
$buf = substr($buf, $len+$pos);
}
}
/**
* Destroy object
**/
function __destruct() {
if (isset($this->server->events()['disconnect']) &&
is_callable($func=$this->server->events()['disconnect']))
$func($this);
}
/**
* @param $server WS
* @param $socket resource
* @param $verb string
* @param $uri string
* @param $hdrs array
**/
function __construct($server,$socket,$verb,$uri,array $hdrs) {
$this->server=$server;
$this->id=stream_socket_get_name($socket,TRUE);
$this->socket=$socket;
$this->verb=$verb;
$this->uri=$uri;
$this->headers=$hdrs;
if (isset($server->events()['connect']) &&
is_callable($func=$server->events()['connect']))
$func($this);
}
}

View File

@@ -0,0 +1 @@
code{word-wrap:break-word;color:black}.comment,.doc_comment,.ml_comment{color:dimgray;font-style:italic}.variable{color:blueviolet}.const,.constant_encapsed_string,.class_c,.dir,.file,.func_c,.halt_compiler,.line,.method_c,.lnumber,.dnumber{color:crimson}.string,.and_equal,.boolean_and,.boolean_or,.concat_equal,.dec,.div_equal,.inc,.is_equal,.is_greater_or_equal,.is_identical,.is_not_equal,.is_not_identical,.is_smaller_or_equal,.logical_and,.logical_or,.logical_xor,.minus_equal,.mod_equal,.mul_equal,.ns_c,.ns_separator,.or_equal,.plus_equal,.sl,.sl_equal,.sr,.sr_equal,.xor_equal,.start_heredoc,.end_heredoc,.object_operator,.paamayim_nekudotayim{color:black}.abstract,.array,.array_cast,.as,.break,.case,.catch,.class,.clone,.continue,.declare,.default,.do,.echo,.else,.elseif,.empty.enddeclare,.endfor,.endforach,.endif,.endswitch,.endwhile,.eval,.exit,.extends,.final,.for,.foreach,.function,.global,.goto,.if,.implements,.include,.include_once,.instanceof,.interface,.isset,.list,.namespace,.new,.print,.private,.public,.protected,.require,.require_once,.return,.static,.switch,.throw,.try,.unset,.use,.var,.while{color:royalblue}.open_tag,.open_tag_with_echo,.close_tag{color:orange}.ini_section{color:black}.ini_key{color:royalblue}.ini_value{color:crimson}.xml_tag{color:dodgerblue}.xml_attr{color:blueviolet}.xml_data{color:red}.section{color:black}.directive{color:blue}.data{color:dimgray}

View File

@@ -0,0 +1,12 @@
{
"name": "bcosca/fatfree-core",
"description": "A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!",
"homepage": "http://fatfreeframework.com/",
"license": "GPL-3.0",
"require": {
"php": ">=7.2"
},
"autoload": {
"classmap": ["."]
}
}

View File

@@ -0,0 +1,389 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB;
//! Simple cursor implementation
abstract class Cursor extends \Magic implements \IteratorAggregate {
//@{ Error messages
const
E_Field='Undefined field %s';
//@}
protected
//! Query results
$query=[],
//! Current position
$ptr=0,
//! Event listeners
$trigger=[];
/**
* Return database type
* @return string
**/
abstract function dbtype();
/**
* Return field names
* @return array
**/
abstract function fields();
/**
* Return fields of mapper object as an associative array
* @return array
* @param $obj object
**/
abstract function cast($obj=NULL);
/**
* Return records (array of mapper objects) that match criteria
* @return array
* @param $filter string|array
* @param $options array
* @param $ttl int
**/
abstract function find($filter=NULL,?array $options=NULL,$ttl=0);
/**
* Count records that match criteria
* @return int
* @param $filter array
* @param $options array
* @param $ttl int
**/
abstract function count($filter=NULL,?array $options=NULL,$ttl=0);
/**
* Insert new record
* @return array
**/
abstract function insert();
/**
* Update current record
* @return array
**/
abstract function update();
/**
* Hydrate mapper object using hive array variable
* @return NULL
* @param $var array|string
* @param $func callback
**/
abstract function copyfrom($var,$func=NULL);
/**
* Populate hive array variable with mapper fields
* @return NULL
* @param $key string
**/
abstract function copyto($key);
/**
* Get cursor's equivalent external iterator
* Causes a fatal error in PHP 5.3.5 if uncommented
* return ArrayIterator
**/
#[\ReturnTypeWillChange]
abstract function getiterator();
/**
* Return TRUE if current cursor position is not mapped to any record
* @return bool
**/
function dry() {
return empty($this->query[$this->ptr]);
}
/**
* Return first record (mapper object) that matches criteria
* @return static|FALSE
* @param $filter string|array
* @param $options array
* @param $ttl int
**/
function findone($filter=NULL,?array $options=NULL,$ttl=0) {
if (!$options)
$options=[];
// Override limit
$options['limit']=1;
return ($data=$this->find($filter,$options,$ttl))?$data[0]:FALSE;
}
/**
* Return array containing subset of records matching criteria,
* total number of records in superset, specified limit, number of
* subsets available, and actual subset position
* @return array
* @param $pos int
* @param $size int
* @param $filter string|array
* @param $options array
* @param $ttl int
* @param $bounce bool
**/
function paginate(
$pos=0,$size=10,$filter=NULL,?array $options=NULL,$ttl=0,$bounce=TRUE) {
$total=$this->count($filter,$options,$ttl);
$count=(int)ceil($total/$size);
if ($bounce)
$pos=max(0,min($pos,$count-1));
return [
'subset'=>($bounce || $pos<$count)?$this->find($filter,
array_merge(
$options?:[],
['limit'=>$size,'offset'=>$pos*$size]
),
$ttl
):[],
'total'=>$total,
'limit'=>$size,
'count'=>$count,
'pos'=>$bounce?($pos<$count?$pos:0):$pos
];
}
/**
* Map to first record that matches criteria
* @return \DB\SQL\Mapper|FALSE
* @param $filter string|array
* @param $options array
* @param $ttl int
**/
function load($filter=NULL,?array $options=NULL,$ttl=0) {
$this->reset();
return ($this->query=$this->find($filter,$options,$ttl)) &&
$this->skip(0)?$this->query[$this->ptr]:FALSE;
}
/**
* Return the count of records loaded
* @return int
**/
function loaded() {
return count($this->query);
}
/**
* Map to first record in cursor
* @return mixed
**/
function first() {
return $this->skip(-$this->ptr);
}
/**
* Map to last record in cursor
* @return mixed
**/
function last() {
return $this->skip(($ofs=count($this->query)-$this->ptr)?$ofs-1:0);
}
/**
* Map to nth record relative to current cursor position
* @return mixed
* @param $ofs int
**/
function skip($ofs=1) {
$this->ptr+=$ofs;
return $this->ptr>-1 && $this->ptr<count($this->query)?
$this->query[$this->ptr]:FALSE;
}
/**
* Map next record
* @return mixed
**/
function next() {
return $this->skip();
}
/**
* Map previous record
* @return mixed
**/
function prev() {
return $this->skip(-1);
}
/**
* Return whether current iterator position is valid.
*/
function valid() {
return !$this->dry();
}
/**
* Save mapped record
* @return mixed
**/
function save() {
return $this->query?$this->update():$this->insert();
}
/**
* Delete current record
* @return int|bool
**/
function erase() {
$this->query=array_slice($this->query,0,$this->ptr,TRUE)+
array_slice($this->query,$this->ptr,NULL,TRUE);
$this->skip(0);
}
/**
* Define onload trigger
* @return callback
* @param $func callback
**/
function onload($func) {
return $this->trigger['load']=$func;
}
/**
* Define beforeinsert trigger
* @return callback
* @param $func callback
**/
function beforeinsert($func) {
return $this->trigger['beforeinsert']=$func;
}
/**
* Define afterinsert trigger
* @return callback
* @param $func callback
**/
function afterinsert($func) {
return $this->trigger['afterinsert']=$func;
}
/**
* Define oninsert trigger
* @return callback
* @param $func callback
**/
function oninsert($func) {
return $this->afterinsert($func);
}
/**
* Define beforeupdate trigger
* @return callback
* @param $func callback
**/
function beforeupdate($func) {
return $this->trigger['beforeupdate']=$func;
}
/**
* Define afterupdate trigger
* @return callback
* @param $func callback
**/
function afterupdate($func) {
return $this->trigger['afterupdate']=$func;
}
/**
* Define onupdate trigger
* @return callback
* @param $func callback
**/
function onupdate($func) {
return $this->afterupdate($func);
}
/**
* Define beforesave trigger
* @return callback
* @param $func callback
**/
function beforesave($func) {
$this->trigger['beforeinsert']=$func;
$this->trigger['beforeupdate']=$func;
return $func;
}
/**
* Define aftersave trigger
* @return callback
* @param $func callback
**/
function aftersave($func) {
$this->trigger['afterinsert']=$func;
$this->trigger['afterupdate']=$func;
return $func;
}
/**
* Define onsave trigger
* @return callback
* @param $func callback
**/
function onsave($func) {
return $this->aftersave($func);
}
/**
* Define beforeerase trigger
* @return callback
* @param $func callback
**/
function beforeerase($func) {
return $this->trigger['beforeerase']=$func;
}
/**
* Define aftererase trigger
* @return callback
* @param $func callback
**/
function aftererase($func) {
return $this->trigger['aftererase']=$func;
}
/**
* Define onerase trigger
* @return callback
* @param $func callback
**/
function onerase($func) {
return $this->aftererase($func);
}
/**
* Reset cursor
* @return NULL
**/
function reset() {
$this->query=[];
$this->ptr=0;
}
}

View File

@@ -0,0 +1,178 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB;
//! In-memory/flat-file DB wrapper
class Jig {
//@{ Storage formats
const
FORMAT_JSON=0,
FORMAT_Serialized=1;
//@}
protected
//! UUID
$uuid,
//! Storage location
$dir,
//! Current storage format
$format,
//! Jig log
$log,
//! Memory-held data
$data,
//! lazy load/save files
$lazy;
/**
* Read data from memory/file
* @return array
* @param $file string
**/
function &read($file) {
if (!$this->dir || !is_file($dst=$this->dir.$file)) {
if (!isset($this->data[$file]))
$this->data[$file]=[];
return $this->data[$file];
}
if ($this->lazy && isset($this->data[$file]))
return $this->data[$file];
$fw=\Base::instance();
$raw=$fw->read($dst);
switch ($this->format) {
case self::FORMAT_JSON:
$data=json_decode($raw,TRUE);
break;
case self::FORMAT_Serialized:
$data=$fw->unserialize($raw);
break;
}
$this->data[$file] = $data;
return $this->data[$file];
}
/**
* Write data to memory/file
* @return int
* @param $file string
* @param $data array
**/
function write($file,?array $data=NULL) {
if (!$this->dir || $this->lazy)
return count($this->data[$file]=$data);
$fw=\Base::instance();
switch ($this->format) {
case self::FORMAT_JSON:
if(version_compare(PHP_VERSION, '7.2.0') >= 0)
$out=json_encode($data,JSON_PRETTY_PRINT | JSON_INVALID_UTF8_IGNORE);
else
$out=json_encode($data,JSON_PRETTY_PRINT | JSON_PARTIAL_OUTPUT_ON_ERROR);
break;
case self::FORMAT_Serialized:
$out=$fw->serialize($data);
break;
}
return $fw->write($this->dir.$file,$out);
}
/**
* Return directory
* @return string
**/
function dir() {
return $this->dir;
}
/**
* Return UUID
* @return string
**/
function uuid() {
return $this->uuid;
}
/**
* Return profiler results (or disable logging)
* @param $flag bool
* @return string
**/
function log($flag=TRUE) {
if ($flag)
return $this->log;
$this->log=FALSE;
}
/**
* Jot down log entry
* @return NULL
* @param $frame string
**/
function jot($frame) {
if ($frame)
$this->log.=date('r').' '.$frame.PHP_EOL;
}
/**
* Clean storage
* @return NULL
**/
function drop() {
if ($this->lazy) // intentional
$this->data=[];
if (!$this->dir)
$this->data=[];
elseif ($glob=@glob($this->dir.'/*',GLOB_NOSORT))
foreach ($glob as $file)
@unlink($file);
}
//! Prohibit cloning
private function __clone() {
}
/**
* Instantiate class
* @param $dir string
* @param $format int
**/
function __construct($dir=NULL,$format=self::FORMAT_JSON,$lazy=FALSE) {
if ($dir && !is_dir($dir))
mkdir($dir,\Base::MODE,TRUE);
$this->uuid=\Base::instance()->hash($this->dir=$dir);
$this->format=$format;
$this->lazy=$lazy;
}
/**
* save file on destruction
**/
function __destruct() {
if ($this->lazy) {
$this->lazy = FALSE;
foreach ($this->data?:[] as $file => $data)
$this->write($file,$data);
}
}
}

View File

@@ -0,0 +1,541 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB\Jig;
//! Flat-file DB mapper
class Mapper extends \DB\Cursor {
protected
//! Flat-file DB wrapper
$db,
//! Data file
$file,
//! Document identifier
$id,
//! Document contents
$document=[],
//! field map-reduce handlers
$_reduce;
/**
* Return database type
* @return string
**/
function dbtype() {
return 'Jig';
}
/**
* Return TRUE if field is defined
* @return bool
* @param $key string
**/
function exists($key) {
return array_key_exists($key,$this->document);
}
/**
* Assign value to field
* @return scalar|FALSE
* @param $key string
* @param $val scalar
**/
function set($key,$val) {
return ($key=='_id')?FALSE:($this->document[$key]=$val);
}
/**
* Retrieve value of field
* @return scalar|FALSE
* @param $key string
**/
function &get($key) {
if ($key=='_id')
return $this->id;
if (array_key_exists($key,$this->document))
return $this->document[$key];
throw new \Exception(sprintf(self::E_Field,$key));
}
/**
* Delete field
* @return NULL
* @param $key string
**/
function clear($key) {
if ($key!='_id')
unset($this->document[$key]);
}
/**
* Convert array to mapper object
* @return object
* @param $id string
* @param $row array
**/
function factory($id,$row) {
$mapper=clone($this);
$mapper->reset();
$mapper->id=$id;
foreach ($row as $field=>$val)
$mapper->document[$field]=$val;
$mapper->query=[clone($mapper)];
if (isset($mapper->trigger['load']))
\Base::instance()->call($mapper->trigger['load'],$mapper);
return $mapper;
}
/**
* Return fields of mapper object as an associative array
* @return array
* @param $obj object
**/
function cast($obj=NULL) {
if (!$obj)
$obj=$this;
return $obj->document+['_id'=>$this->id];
}
/**
* Convert tokens in string expression to variable names
* @return string
* @param $str string
**/
function token($str) {
$str=preg_replace_callback(
'/(?<!\w)@(\w(?:[\w\.\[\]])*)/',
function($token) {
// Convert from JS dot notation to PHP array notation
return '$'.preg_replace_callback(
'/(\.\w+)|\[((?:[^\[\]]*|(?R))*)\]/',
function($expr) {
$fw=\Base::instance();
return
'['.
($expr[1]?
$fw->stringify(substr($expr[1],1)):
(preg_match('/^\w+/',
$mix=$this->token($expr[2]))?
$fw->stringify($mix):
$mix)).
']';
},
$token[1]
);
},
$str
);
return trim($str);
}
/**
* Return records that match criteria
* @return static[]|FALSE
* @param $filter array
* @param $options array
* @param $ttl int|array
* @param $log bool
**/
function find($filter=NULL,?array $options=NULL,$ttl=0,$log=TRUE) {
if (!$options)
$options=[];
$options+=[
'order'=>NULL,
'limit'=>0,
'offset'=>0,
'group'=>NULL,
];
$fw=\Base::instance();
$cache=\Cache::instance();
$db=$this->db;
$now=microtime(TRUE);
$data=[];
$tag='';
if (is_array($ttl))
list($ttl,$tag)=$ttl;
if (!$fw->CACHE || !$ttl || !($cached=$cache->exists(
$hash=$fw->hash($this->db->dir().
$fw->stringify([$filter,$options])).($tag?'.'.$tag:'').'.jig',$data)) ||
$cached[0]+$ttl<microtime(TRUE)) {
$data=$db->read($this->file);
if (is_null($data))
return FALSE;
foreach ($data as $id=>&$doc) {
$doc['_id']=$id;
unset($doc);
}
if ($filter) {
if (!is_array($filter))
return FALSE;
// Normalize equality operator
$expr=preg_replace('/(?<=[^<>!=])=(?!=)/','==',$filter[0]);
// Prepare query arguments
$args=isset($filter[1]) && is_array($filter[1])?
$filter[1]:
array_slice($filter,1,NULL,TRUE);
$args=is_array($args)?$args:[1=>$args];
$keys=$vals=[];
$tokens=array_slice(
token_get_all('<?php '.$this->token($expr)),1);
$data=array_filter($data,
function($_row) use($fw,$args,$tokens) {
$_expr='';
$ctr=0;
$named=FALSE;
foreach ($tokens as $token) {
if (is_string($token))
if ($token=='?') {
// Positional
++$ctr;
$key=$ctr;
}
else {
if ($token==':')
$named=TRUE;
else
$_expr.=$token;
continue;
}
elseif ($named &&
token_name($token[0])=='T_STRING') {
$key=':'.$token[1];
$named=FALSE;
}
else {
$_expr.=$token[1];
continue;
}
$_expr.=$fw->stringify(
is_string($args[$key])?
addcslashes($args[$key],'\''):
$args[$key]);
}
// Avoid conflict with user code
unset($fw,$tokens,$args,$ctr,$token,$key,$named);
extract($_row);
// Evaluate pseudo-SQL expression
return eval('return '.$_expr.';');
}
);
}
if (isset($options['group'])) {
$cols=array_reverse($fw->split($options['group']));
// sort into groups
$data=$this->sort($data,$options['group']);
foreach($data as $i=>&$row) {
if (!isset($prev)) {
$prev=$row;
$prev_i=$i;
}
$drop=false;
foreach ($cols as $col)
if ($prev_i!=$i && array_key_exists($col,$row) &&
array_key_exists($col,$prev) && $row[$col]==$prev[$col])
// reduce/modify
$drop=!isset($this->_reduce[$col]) || call_user_func_array(
$this->_reduce[$col][0],[&$prev,&$row])!==FALSE;
elseif (isset($this->_reduce[$col])) {
$null=null;
// initial
call_user_func_array($this->_reduce[$col][0],[&$row,&$null]);
}
if ($drop)
unset($data[$i]);
else {
$prev=&$row;
$prev_i=$i;
}
unset($row);
}
// finalize
if ($this->_reduce[$col][1])
foreach($data as $i=>&$row) {
$row=call_user_func($this->_reduce[$col][1],$row);
if (!$row)
unset($data[$i]);
unset($row);
}
}
if (isset($options['order']))
$data=$this->sort($data,$options['order']);
$data=array_slice($data,
$options['offset'],$options['limit']?:NULL,TRUE);
if ($fw->CACHE && $ttl)
// Save to cache backend
$cache->set($hash,$data,$ttl);
}
$out=[];
foreach ($data as $id=>&$doc) {
unset($doc['_id']);
$out[]=$this->factory($id,$doc);
unset($doc);
}
if ($log && isset($args)) {
if ($filter)
foreach ($args as $key=>$val) {
$vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
$keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
}
$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
$this->file.' [find] '.
($filter?preg_replace($keys,$vals,$filter[0],1):''));
}
return $out;
}
/**
* Sort a collection
* @param $data
* @param $cond
* @return mixed
*/
protected function sort($data,$cond) {
$cols=\Base::instance()->split($cond);
uasort(
$data,
function($val1,$val2) use($cols) {
foreach ($cols as $col) {
$parts=explode(' ',$col,2);
$order=empty($parts[1])?
SORT_ASC:
constant($parts[1]);
$col=$parts[0];
if (!array_key_exists($col,$val1))
$val1[$col]=NULL;
if (!array_key_exists($col,$val2))
$val2[$col]=NULL;
list($v1,$v2)=[$val1[$col],$val2[$col]];
if ($out=strnatcmp($v1?:'',$v2?:'')*
(($order==SORT_ASC)*2-1))
return $out;
}
return 0;
}
);
return $data;
}
/**
* Add reduce handler for grouped fields
* @param $key string
* @param $handler callback
* @param $finalize callback
*/
function reduce($key,$handler,$finalize=null){
$this->_reduce[$key]=[$handler,$finalize];
}
/**
* Count records that match criteria
* @return int
* @param $filter array
* @param $options array
* @param $ttl int|array
**/
function count($filter=NULL,?array $options=NULL,$ttl=0) {
$now=microtime(TRUE);
$out=count($this->find($filter,$options,$ttl,FALSE));
$this->db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
$this->file.' [count] '.($filter?json_encode($filter):''));
return $out;
}
/**
* Return record at specified offset using criteria of previous
* load() call and make it active
* @return array
* @param $ofs int
**/
function skip($ofs=1) {
$this->document=($out=parent::skip($ofs))?$out->document:[];
$this->id=$out?$out->id:NULL;
if ($this->document && isset($this->trigger['load']))
\Base::instance()->call($this->trigger['load'],$this);
return $out;
}
/**
* Insert new record
* @return array
**/
function insert() {
if ($this->id)
return $this->update();
$db=$this->db;
$now=microtime(TRUE);
while (($id=uniqid('',TRUE)) &&
($data=&$db->read($this->file)) && isset($data[$id]) &&
!connection_aborted())
usleep(mt_rand(0,100));
$this->id=$id;
$pkey=['_id'=>$this->id];
if (isset($this->trigger['beforeinsert']) &&
\Base::instance()->call($this->trigger['beforeinsert'],
[$this,$pkey])===FALSE)
return $this->document;
$data[$id]=$this->document;
$db->write($this->file,$data);
$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
$this->file.' [insert] '.json_encode($this->document));
if (isset($this->trigger['afterinsert']))
\Base::instance()->call($this->trigger['afterinsert'],
[$this,$pkey]);
$this->load(['@_id=?',$this->id]);
return $this->document;
}
/**
* Update current record
* @return array
**/
function update() {
$db=$this->db;
$now=microtime(TRUE);
$data=&$db->read($this->file);
if (isset($this->trigger['beforeupdate']) &&
\Base::instance()->call($this->trigger['beforeupdate'],
[$this,['_id'=>$this->id]])===FALSE)
return $this->document;
$data[$this->id]=$this->document;
$db->write($this->file,$data);
$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
$this->file.' [update] '.json_encode($this->document));
if (isset($this->trigger['afterupdate']))
\Base::instance()->call($this->trigger['afterupdate'],
[$this,['_id'=>$this->id]]);
return $this->document;
}
/**
* Delete current record
* @return bool
* @param $filter array
* @param $quick bool
**/
function erase($filter=NULL,$quick=FALSE) {
$db=$this->db;
$now=microtime(TRUE);
$data=&$db->read($this->file);
$pkey=['_id'=>$this->id];
if ($filter) {
foreach ($this->find($filter,NULL,FALSE) as $mapper)
if (!$mapper->erase(null,$quick))
return FALSE;
return TRUE;
}
elseif (isset($this->id)) {
unset($data[$this->id]);
parent::erase();
}
else
return FALSE;
if (!$quick && isset($this->trigger['beforeerase']) &&
\Base::instance()->call($this->trigger['beforeerase'],
[$this,$pkey])===FALSE)
return FALSE;
$db->write($this->file,$data);
if ($filter) {
$args=isset($filter[1]) && is_array($filter[1])?
$filter[1]:
array_slice($filter,1,NULL,TRUE);
$args=is_array($args)?$args:[1=>$args];
foreach ($args as $key=>$val) {
$vals[]=\Base::instance()->
stringify(is_array($val)?$val[0]:$val);
$keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
}
}
$db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
$this->file.' [erase] '.
($filter?preg_replace($keys,$vals,$filter[0],1):''));
if (!$quick && isset($this->trigger['aftererase']))
\Base::instance()->call($this->trigger['aftererase'],
[$this,$pkey]);
return TRUE;
}
/**
* Reset cursor
* @return NULL
**/
function reset() {
$this->id=NULL;
$this->document=[];
parent::reset();
}
/**
* Hydrate mapper object using hive array variable
* @return NULL
* @param $var array|string
* @param $func callback
**/
function copyfrom($var,$func=NULL) {
if (is_string($var))
$var=\Base::instance()->$var;
if ($func)
$var=call_user_func($func,$var);
foreach ($var as $key=>$val)
$this->set($key,$val);
}
/**
* Populate hive array variable with mapper fields
* @return NULL
* @param $key string
**/
function copyto($key) {
$var=&\Base::instance()->ref($key);
foreach ($this->document as $key=>$field)
$var[$key]=$field;
}
/**
* Return field names
* @return array
**/
function fields() {
return array_keys($this->document);
}
/**
* Retrieve external iterator for fields
* @return object
**/
function getiterator() {
return new \ArrayIterator($this->cast());
}
/**
* Instantiate class
* @return void
* @param $db object
* @param $file string
**/
function __construct(\DB\Jig $db,$file) {
$this->db=$db;
$this->file=$file;
$this->reset();
}
}

View File

@@ -0,0 +1,207 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB\Jig;
use ReturnTypeWillChange;
use SessionAdapter;
//! Jig-managed session handler
class Session extends Mapper {
protected
//! Session ID
$sid,
//! Anti-CSRF token
$_csrf,
//! User agent
$_agent,
//! IP,
$_ip,
//! Suspect callback
$onsuspect;
/**
* Open session
* @return TRUE
* @param $path string
* @param $name string
**/
function open(string $path, string $name): bool
{
return TRUE;
}
/**
* Close session
* @return TRUE
**/
function close(): bool
{
$this->reset();
$this->sid=NULL;
return TRUE;
}
/**
* Return session data in serialized format
* @return string|false
* @param $id string
**/
#[ReturnTypeWillChange]
function read($id)
{
$this->load(['@session_id=?',$this->sid=$id]);
if ($this->dry())
return '';
if ($this->get('ip')!=$this->_ip || $this->get('agent')!=$this->_agent) {
$fw=\Base::instance();
if (!isset($this->onsuspect) ||
$fw->call($this->onsuspect,[$this,$id])===FALSE) {
// NB: `session_destroy` can't be called at that stage;
// `session_start` not completed
$this->destroy($id);
$this->close();
unset($fw->{'COOKIE.'.session_name()});
$fw->error(403);
}
}
return $this->get('data');
}
/**
* Write session data
* @return TRUE
* @param $id string
* @param $data string
**/
function write(string $id, string $data): bool
{
$this->set('session_id',$id);
$this->set('data',$data);
$this->set('ip',$this->_ip);
$this->set('agent',$this->_agent);
$this->set('stamp',time());
$this->save();
return TRUE;
}
/**
* Destroy session
* @return TRUE
* @param $id string
**/
function destroy($id): bool
{
$this->erase(['@session_id=?',$id]);
return TRUE;
}
/**
* Garbage collector
**/
#[ReturnTypeWillChange]
function gc(int $max_lifetime): int
{
return (int) $this->erase(['@stamp+?<?',$max_lifetime,time()]);
}
/**
* Return session id (if session has started)
* @return string|NULL
**/
function sid() {
return $this->sid;
}
/**
* Return anti-CSRF token
* @return string
**/
function csrf() {
return $this->_csrf;
}
/**
* Return IP address
* @return string
**/
function ip() {
return $this->_ip;
}
/**
* Return Unix timestamp
* @return string|FALSE
**/
function stamp() {
if (!$this->sid)
session_start();
return $this->dry()?FALSE:$this->get('stamp');
}
/**
* Return HTTP user agent
* @return string|FALSE
**/
function agent() {
return $this->_agent;
}
/**
* Instantiate class
* @param $db \DB\Jig
* @param $file string
* @param $onsuspect callback
* @param $key string
**/
function __construct(\DB\Jig $db,$file='sessions',$onsuspect=NULL,$key=NULL) {
parent::__construct($db,$file);
$this->onsuspect=$onsuspect;
if (version_compare(PHP_VERSION, '8.4.0')>=0) {
// TODO: remove this when php7 support is dropped
session_set_save_handler(new SessionAdapter($this));
} else {
session_set_save_handler(
[$this,'open'],
[$this,'close'],
[$this,'read'],
[$this,'write'],
[$this,'destroy'],
[$this,'gc']
);
}
register_shutdown_function('session_commit');
$fw=\Base::instance();
$headers=$fw->HEADERS;
$this->_csrf=$fw->hash($fw->SEED.
extension_loaded('openssl')?
implode(unpack('L',openssl_random_pseudo_bytes(4))):
mt_rand()
);
if ($key)
$fw->$key=$this->_csrf;
$this->_agent=isset($headers['User-Agent'])?$headers['User-Agent']:'';
$this->_ip=$fw->IP;
}
}

View File

@@ -0,0 +1,145 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB;
//! MongoDB wrapper
class Mongo {
//@{
const
E_Profiler='MongoDB profiler is disabled';
//@}
protected
//! UUID
$uuid,
//! Data source name
$dsn,
//! MongoDB object
$db,
//! Legacy flag
$legacy,
//! MongoDB log
$log;
/**
* Return data source name
* @return string
**/
function dsn() {
return $this->dsn;
}
/**
* Return UUID
* @return string
**/
function uuid() {
return $this->uuid;
}
/**
* Return MongoDB profiler results (or disable logging)
* @param $flag bool
* @return string
**/
function log($flag=TRUE) {
if ($flag) {
$cursor=$this->db->selectcollection('system.profile')->find();
foreach (iterator_to_array($cursor) as $frame)
if (!preg_match('/\.system\..+$/',$frame['ns']))
$this->log.=date('r',$this->legacy() ?
$frame['ts']->sec : (round((string)$frame['ts'])/1000)).
' ('.sprintf('%.1f',$frame['millis']).'ms) '.
$frame['ns'].' ['.$frame['op'].'] '.
(empty($frame['query'])?
'':json_encode($frame['query'])).
(empty($frame['command'])?
'':json_encode($frame['command'])).
PHP_EOL;
} else {
$this->log=FALSE;
if ($this->legacy)
$this->db->setprofilinglevel(-1);
else
$this->db->command(['profile'=>-1]);
}
return $this->log;
}
/**
* Intercept native call to re-enable profiler
* @return int
**/
function drop() {
$out=$this->db->drop();
if ($this->log!==FALSE) {
if ($this->legacy)
$this->db->setprofilinglevel(2);
else
$this->db->command(['profile'=>2]);
}
return $out;
}
/**
* Redirect call to MongoDB object
* @return mixed
* @param $func string
* @param $args array
**/
function __call($func,array $args) {
return call_user_func_array([$this->db,$func],$args);
}
/**
* Return TRUE if legacy driver is loaded
* @return bool
**/
function legacy() {
return $this->legacy;
}
//! Prohibit cloning
private function __clone() {
}
/**
* Instantiate class
* @param $dsn string
* @param $dbname string
* @param $options array
**/
function __construct($dsn,$dbname,?array $options=NULL) {
$this->uuid=\Base::instance()->hash($this->dsn=$dsn);
if ($this->legacy=class_exists('\MongoClient')) {
$this->db=new \MongoDB(new \MongoClient($dsn,$options?:[]),$dbname);
$this->db->setprofilinglevel(2);
}
else {
$this->db=(new \MongoDB\Client($dsn,$options?:[]))->$dbname;
$this->db->command(['profile'=>2]);
}
}
}

View File

@@ -0,0 +1,405 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB\Mongo;
//! MongoDB mapper
class Mapper extends \DB\Cursor {
protected
//! MongoDB wrapper
$db,
//! Legacy flag
$legacy,
//! Mongo collection
$collection,
//! Mongo document
$document=[],
//! Mongo cursor
$cursor,
//! Defined fields
$fields;
/**
* Return database type
* @return string
**/
function dbtype() {
return 'Mongo';
}
/**
* Return TRUE if field is defined
* @return bool
* @param $key string
**/
function exists($key) {
return array_key_exists($key,$this->document);
}
/**
* Assign value to field
* @return scalar|FALSE
* @param $key string
* @param $val scalar
**/
function set($key,$val) {
return $this->document[$key]=$val;
}
/**
* Retrieve value of field
* @return scalar|FALSE
* @param $key string
**/
function &get($key) {
if ($this->exists($key))
return $this->document[$key];
throw new \Exception(sprintf(self::E_Field,$key));
}
/**
* Delete field
* @return NULL
* @param $key string
**/
function clear($key) {
unset($this->document[$key]);
}
/**
* Convert array to mapper object
* @return static
* @param $row array
**/
function factory($row) {
$mapper=clone($this);
$mapper->reset();
foreach ($row as $key=>$val)
$mapper->document[$key]=$val;
$mapper->query=[clone($mapper)];
if (isset($mapper->trigger['load']))
\Base::instance()->call($mapper->trigger['load'],$mapper);
return $mapper;
}
/**
* Return fields of mapper object as an associative array
* @return array
* @param $obj object
**/
function cast($obj=NULL) {
if (!$obj)
$obj=$this;
return $obj->document;
}
/**
* Build query and execute
* @return static[]
* @param $fields string
* @param $filter array
* @param $options array
* @param $ttl int|array
**/
function select($fields=NULL,$filter=NULL,?array $options=NULL,$ttl=0) {
if (!$options)
$options=[];
$options+=[
'group'=>NULL,
'order'=>NULL,
'limit'=>0,
'offset'=>0
];
$tag='';
if (is_array($ttl))
list($ttl,$tag)=$ttl;
$fw=\Base::instance();
$cache=\Cache::instance();
if (!($cached=$cache->exists($hash=$fw->hash($this->db->dsn().
$fw->stringify([$fields,$filter,$options])).($tag?'.'.$tag:'').'.mongo',
$result)) || !$ttl || $cached[0]+$ttl<microtime(TRUE)) {
if ($options['group']) {
$grp=$this->collection->group(
$options['group']['keys'],
$options['group']['initial'],
$options['group']['reduce'],
[
'condition'=>$filter,
'finalize'=>$options['group']['finalize']
]
);
$tmp=$this->db->selectcollection(
$fw->HOST.'.'.$fw->BASE.'.'.
uniqid('',TRUE).'.tmp'
);
$tmp->batchinsert($grp['retval'],['w'=>1]);
$filter=[];
$collection=$tmp;
}
else {
$filter=$filter?:[];
$collection=$this->collection;
}
if ($this->legacy) {
$this->cursor=$collection->find($filter,$fields?:[]);
if ($options['order'])
$this->cursor=$this->cursor->sort($options['order']);
if ($options['limit'])
$this->cursor=$this->cursor->limit($options['limit']);
if ($options['offset'])
$this->cursor=$this->cursor->skip($options['offset']);
$result=[];
while ($this->cursor->hasnext())
$result[]=$this->cursor->getnext();
}
else {
$this->cursor=$collection->find($filter,[
'sort'=>$options['order'],
'limit'=>$options['limit'],
'skip'=>$options['offset']
]);
$result=$this->cursor->toarray();
}
if ($options['group'])
$tmp->drop();
if ($fw->CACHE && $ttl)
// Save to cache backend
$cache->set($hash,$result,$ttl);
}
$out=[];
foreach ($result as $doc)
$out[]=$this->factory($doc);
return $out;
}
/**
* Return records that match criteria
* @return static[]
* @param $filter array
* @param $options array
* @param $ttl int|array
**/
function find($filter=NULL,?array $options=NULL,$ttl=0) {
if (!$options)
$options=[];
$options+=[
'group'=>NULL,
'order'=>NULL,
'limit'=>0,
'offset'=>0
];
return $this->select($this->fields,$filter,$options,$ttl);
}
/**
* Count records that match criteria
* @return int
* @param $filter array
* @param $options array
* @param $ttl int|array
**/
function count($filter=NULL,?array $options=NULL,$ttl=0) {
$fw=\Base::instance();
$cache=\Cache::instance();
$tag='';
if (is_array($ttl))
list($ttl,$tag)=$ttl;
if (!($cached=$cache->exists($hash=$fw->hash($fw->stringify(
[$filter])).($tag?'.'.$tag:'').'.mongo',$result)) || !$ttl ||
$cached[0]+$ttl<microtime(TRUE)) {
$result=$this->collection->count($filter?:[]);
if ($fw->CACHE && $ttl)
// Save to cache backend
$cache->set($hash,$result,$ttl);
}
return $result;
}
/**
* Return record at specified offset using criteria of previous
* load() call and make it active
* @return array
* @param $ofs int
**/
function skip($ofs=1) {
$this->document=($out=parent::skip($ofs))?$out->document:[];
if ($this->document && isset($this->trigger['load']))
\Base::instance()->call($this->trigger['load'],$this);
return $out;
}
/**
* Insert new record
* @return array
**/
function insert() {
if (isset($this->document['_id']))
return $this->update();
if (isset($this->trigger['beforeinsert']) &&
\Base::instance()->call($this->trigger['beforeinsert'],
[$this,['_id'=>$this->document['_id']]])===FALSE)
return $this->document;
if ($this->legacy) {
$this->collection->insert($this->document);
$pkey=['_id'=>$this->document['_id']];
}
else {
$result=$this->collection->insertone($this->document);
$pkey=['_id'=>$result->getinsertedid()];
}
if (isset($this->trigger['afterinsert']))
\Base::instance()->call($this->trigger['afterinsert'],
[$this,$pkey]);
$this->load($pkey);
return $this->document;
}
/**
* Update current record
* @return array
**/
function update() {
$pkey=['_id'=>$this->document['_id']];
if (isset($this->trigger['beforeupdate']) &&
\Base::instance()->call($this->trigger['beforeupdate'],
[$this,$pkey])===FALSE)
return $this->document;
$upsert=['upsert'=>TRUE];
if ($this->legacy)
$this->collection->update($pkey,$this->document,$upsert);
else
$this->collection->replaceone($pkey,$this->document,$upsert);
if (isset($this->trigger['afterupdate']))
\Base::instance()->call($this->trigger['afterupdate'],
[$this,$pkey]);
return $this->document;
}
/**
* Delete current record
* @return bool
* @param $quick bool
* @param $filter array
**/
function erase($filter=NULL,$quick=TRUE) {
if ($filter) {
if (!$quick) {
foreach ($this->find($filter) as $mapper)
if (!$mapper->erase())
return FALSE;
return TRUE;
}
return $this->legacy?
$this->collection->remove($filter):
$this->collection->deletemany($filter);
}
$pkey=['_id'=>$this->document['_id']];
if (isset($this->trigger['beforeerase']) &&
\Base::instance()->call($this->trigger['beforeerase'],
[$this,$pkey])===FALSE)
return FALSE;
$result=$this->legacy?
$this->collection->remove(['_id'=>$this->document['_id']]):
$this->collection->deleteone(['_id'=>$this->document['_id']]);
parent::erase();
if (isset($this->trigger['aftererase']))
\Base::instance()->call($this->trigger['aftererase'],
[$this,$pkey]);
return $result;
}
/**
* Reset cursor
* @return NULL
**/
function reset() {
$this->document=[];
parent::reset();
}
/**
* Hydrate mapper object using hive array variable
* @return NULL
* @param $var array|string
* @param $func callback
**/
function copyfrom($var,$func=NULL) {
if (is_string($var))
$var=\Base::instance()->$var;
if ($func)
$var=call_user_func($func,$var);
foreach ($var as $key=>$val)
$this->set($key,$val);
}
/**
* Populate hive array variable with mapper fields
* @return NULL
* @param $key string
**/
function copyto($key) {
$var=&\Base::instance()->ref($key);
foreach ($this->document as $key=>$field)
$var[$key]=$field;
}
/**
* Return field names
* @return array
**/
function fields() {
return array_keys($this->document);
}
/**
* Return the cursor from last query
* @return object|NULL
**/
function cursor() {
return $this->cursor;
}
/**
* Retrieve external iterator for fields
* @return object
**/
function getiterator() {
return new \ArrayIterator($this->cast());
}
/**
* Instantiate class
* @return void
* @param $db object
* @param $collection string
* @param $fields array
**/
function __construct(\DB\Mongo $db,$collection,$fields=NULL) {
$this->db=$db;
$this->legacy=$db->legacy();
$this->collection=$db->selectcollection($collection);
$this->fields=$fields;
$this->reset();
}
}

View File

@@ -0,0 +1,207 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB\Mongo;
use ReturnTypeWillChange;
use SessionAdapter;
//! MongoDB-managed session handler
class Session extends Mapper {
protected
//! Session ID
$sid,
//! Anti-CSRF token
$_csrf,
//! User agent
$_agent,
//! IP,
$_ip,
//! Suspect callback
$onsuspect;
/**
* Open session
* @return TRUE
* @param $path string
* @param $name string
**/
function open(string $path, string $name): bool
{
return TRUE;
}
/**
* Close session
* @return TRUE
**/
function close(): bool
{
$this->reset();
$this->sid=NULL;
return TRUE;
}
/**
* Return session data in serialized format
* @return string
* @param $id string
**/
#[ReturnTypeWillChange]
function read(string $id)
{
$this->load(['session_id'=>$this->sid=$id]);
if ($this->dry())
return '';
if ($this->get('ip')!=$this->_ip || $this->get('agent')!=$this->_agent) {
$fw=\Base::instance();
if (!isset($this->onsuspect) ||
$fw->call($this->onsuspect,[$this,$id])===FALSE) {
// NB: `session_destroy` can't be called at that stage;
// `session_start` not completed
$this->destroy($id);
$this->close();
unset($fw->{'COOKIE.'.session_name()});
$fw->error(403);
}
}
return $this->get('data');
}
/**
* Write session data
* @return TRUE
* @param $id string
* @param $data string
**/
function write(string $id, string $data): bool
{
$this->set('session_id',$id);
$this->set('data',$data);
$this->set('ip',$this->_ip);
$this->set('agent',$this->_agent);
$this->set('stamp',time());
$this->save();
return TRUE;
}
/**
* Destroy session
* @return TRUE
* @param $id string
**/
function destroy($id): bool
{
$this->erase(['session_id'=>$id]);
return TRUE;
}
/**
* Garbage collector
**/
#[ReturnTypeWillChange]
function gc(int $max_lifetime): int
{
return (int) $this->erase(['$where'=>'this.stamp+'.$max_lifetime.'<'.time()]);
}
/**
* Return session id (if session has started)
* @return string|NULL
**/
function sid() {
return $this->sid;
}
/**
* Return anti-CSRF token
* @return string
**/
function csrf() {
return $this->_csrf;
}
/**
* Return IP address
* @return string
**/
function ip() {
return $this->_ip;
}
/**
* Return Unix timestamp
* @return string|FALSE
**/
function stamp() {
if (!$this->sid)
session_start();
return $this->dry()?FALSE:$this->get('stamp');
}
/**
* Return HTTP user agent
* @return string
**/
function agent() {
return $this->_agent;
}
/**
* Instantiate class
* @param $db \DB\Mongo
* @param $table string
* @param $onsuspect callback
* @param $key string
**/
function __construct(\DB\Mongo $db,$table='sessions',$onsuspect=NULL,$key=NULL) {
parent::__construct($db,$table);
$this->onsuspect=$onsuspect;
if (version_compare(PHP_VERSION, '8.4.0')>=0) {
// TODO: remove this when php7 support is dropped
session_set_save_handler(new SessionAdapter($this));
} else {
session_set_save_handler(
[$this,'open'],
[$this,'close'],
[$this,'read'],
[$this,'write'],
[$this,'destroy'],
[$this,'gc']
);
}
register_shutdown_function('session_commit');
$fw=\Base::instance();
$headers=$fw->HEADERS;
$this->_csrf=$fw->hash($fw->SEED.
extension_loaded('openssl')?
implode(unpack('L',openssl_random_pseudo_bytes(4))):
mt_rand()
);
if ($key)
$fw->$key=$this->_csrf;
$this->_agent=isset($headers['User-Agent'])?$headers['User-Agent']:'';
$this->_ip=$fw->IP;
}
}

View File

@@ -0,0 +1,552 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB;
//! PDO wrapper
class SQL {
//@{ Error messages
const
E_PKey='Table %s does not have a primary key';
//@}
const
PARAM_FLOAT='float';
protected
//! UUID
$uuid,
//! Raw PDO
$pdo,
//! Data source name
$dsn,
//! Database engine
$engine,
//! Database name
$dbname,
//! Transaction flag
$trans=FALSE,
//! Number of rows affected by query
$rows=0,
//! SQL log
$log;
/**
* Begin SQL transaction
* @return bool
**/
function begin() {
$out=$this->pdo->begintransaction();
$this->trans=TRUE;
return $out;
}
/**
* Rollback SQL transaction
* @return bool
**/
function rollback() {
$out=FALSE;
if ($this->pdo->inTransaction())
$out=$this->pdo->rollback();
$this->trans=FALSE;
return $out;
}
/**
* Commit SQL transaction
* @return bool
**/
function commit() {
$out=FALSE;
if ($this->pdo->inTransaction())
$out=$this->pdo->commit();
$this->trans=FALSE;
return $out;
}
/**
* Return transaction flag
* @return bool
**/
function trans() {
return $this->trans;
}
/**
* Map data type of argument to a PDO constant
* @return int
* @param $val scalar
**/
function type($val) {
switch (gettype($val)) {
case 'NULL':
return \PDO::PARAM_NULL;
case 'boolean':
return \PDO::PARAM_BOOL;
case 'integer':
return \PDO::PARAM_INT;
case 'resource':
return \PDO::PARAM_LOB;
case 'float':
return self::PARAM_FLOAT;
default:
return \PDO::PARAM_STR;
}
}
/**
* Cast value to PHP type
* @return mixed
* @param $type string
* @param $val mixed
**/
function value($type,$val) {
switch ($type) {
case self::PARAM_FLOAT:
if (!is_string($val) && $val !== NULL)
$val=str_replace(',','.',(string) $val);
return $val;
case \PDO::PARAM_NULL:
return NULL;
case \PDO::PARAM_INT:
return (int)$val;
case \PDO::PARAM_BOOL:
return (bool)$val;
case \PDO::PARAM_STR:
return (string)$val;
case \PDO::PARAM_LOB:
return (binary)$val;
}
}
/**
* Execute SQL statement(s)
* @return array|int|FALSE
* @param $cmds string|array
* @param $args string|array
* @param $ttl int|array
* @param $log bool
* @param $stamp bool
**/
function exec($cmds,$args=NULL,$ttl=0,$log=TRUE,$stamp=FALSE) {
$tag='';
if (is_array($ttl))
list($ttl,$tag)=$ttl;
$auto=FALSE;
if (is_null($args))
$args=[];
elseif (is_scalar($args))
$args=[1=>$args];
if (is_array($cmds)) {
if (count($args)<($count=count($cmds)))
// Apply arguments to SQL commands
$args=array_fill(0,$count,$args);
if (!$this->trans) {
$this->begin();
$auto=TRUE;
}
}
else {
$count=1;
$cmds=[$cmds];
$args=[$args];
}
if ($this->log===FALSE)
$log=FALSE;
$fw=\Base::instance();
$cache=\Cache::instance();
$result=FALSE;
for ($i=0;$i<$count;++$i) {
$cmd=$cmds[$i];
$arg=$args[$i];
// ensure 1-based arguments
if (array_key_exists(0,$arg)) {
array_unshift($arg,'');
unset($arg[0]);
}
if (!preg_replace('/(^\s+|[\s;]+$)/','',$cmd))
continue;
$now=microtime(TRUE);
$keys=$vals=[];
if ($fw->CACHE && $ttl && ($cached=$cache->exists(
$hash=$fw->hash($this->dsn.$cmd.
$fw->stringify($arg)).($tag?'.'.$tag:'').'.sql',$result)) &&
$cached[0]+$ttl>microtime(TRUE)) {
foreach ($arg as $key=>$val) {
$vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
$keys[]='/'.preg_quote(is_numeric($key)?chr(0).'?':$key).
'/';
}
if ($log)
$this->log.=($stamp?(date('r').' '):'').'('.
sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
'[CACHED] '.
preg_replace($keys,$vals,
str_replace('?',chr(0).'?',$cmd),1).PHP_EOL;
}
elseif (is_object($query=$this->pdo->prepare($cmd))) {
foreach ($arg as $key=>$val) {
if (is_array($val)) {
// User-specified data type
$query->bindvalue($key,$val[0],
$val[1]==self::PARAM_FLOAT?\PDO::PARAM_STR:$val[1]);
$vals[]=$fw->stringify($this->value($val[1],$val[0]));
}
else {
// Convert to PDO data type
$query->bindvalue($key,$val,
($type=$this->type($val))==self::PARAM_FLOAT?
\PDO::PARAM_STR:$type);
$vals[]=$fw->stringify($this->value($type,$val));
}
$keys[]='/'.preg_quote(is_numeric($key)?chr(0).'?':$key).
'/';
}
if ($log)
$this->log.=($stamp?(date('r').' '):'').'(-0ms) '.
preg_replace($keys,$vals,
str_replace('?',chr(0).'?',$cmd),1).PHP_EOL;
$query->execute();
if ($log)
$this->log=str_replace('(-0ms)',
'('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms)',
$this->log);
if (($error=$query->errorinfo()) && $error[0]!=\PDO::ERR_NONE) {
// Statement-level error occurred
if ($this->trans)
$this->rollback();
throw new \Exception('PDOStatement: '.$error[2]);
}
if (preg_match('/(?:^[\s\(]*'.
'(?:WITH|EXPLAIN|SELECT|PRAGMA|SHOW)|RETURNING)\b/is',$cmd) ||
(preg_match('/^\s*(?:CALL|EXEC)\b/is',$cmd) &&
$query->columnCount())) {
$result=$query->fetchall(\PDO::FETCH_ASSOC);
// Work around SQLite quote bug
if (preg_match('/sqlite2?/',$this->engine))
foreach ($result as $pos=>$rec) {
unset($result[$pos]);
$result[$pos]=[];
foreach ($rec as $key=>$val)
$result[$pos][trim($key,'\'"[]`')]=$val;
}
$this->rows=count($result);
if ($fw->CACHE && $ttl)
// Save to cache backend
$cache->set($hash,$result,$ttl);
}
else
$this->rows=$result=$query->rowcount();
$query->closecursor();
unset($query);
}
elseif (($error=$this->pdo->errorInfo()) && $error[0]!=\PDO::ERR_NONE) {
// PDO-level error occurred
if ($this->trans)
$this->rollback();
throw new \Exception('PDO: '.$error[2]);
}
}
if ($this->trans && $auto)
$this->commit();
return $result;
}
/**
* Return number of rows affected by last query
* @return int
**/
function count() {
return $this->rows;
}
/**
* Return SQL profiler results (or disable logging)
* @return string
* @param $flag bool
**/
function log($flag=TRUE) {
if ($flag)
return $this->log;
$this->log=FALSE;
}
/**
* Return TRUE if table exists
* @return bool
* @param $table string
**/
function exists($table) {
$mode=$this->pdo->getAttribute(\PDO::ATTR_ERRMODE);
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_SILENT);
$out=$this->pdo->
query('SELECT 1 FROM '.$this->quotekey($table).' LIMIT 1');
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE,$mode);
return is_object($out);
}
/**
* Retrieve schema of SQL table
* @return array|FALSE
* @param $table string
* @param $fields array|string
* @param $ttl int|array
**/
function schema($table,$fields=NULL,$ttl=0) {
$fw=\Base::instance();
$cache=\Cache::instance();
if ($fw->CACHE && $ttl &&
($cached=$cache->exists(
$hash=$fw->hash($this->dsn.$table.(is_array($fields) ? implode(',',$fields) : $fields)).'.schema',$result)) &&
$cached[0]+$ttl>microtime(TRUE))
return $result;
if (strpos($table,'.'))
list($schema,$table)=explode('.',$table);
// Supported engines
// format: engine_name => array of:
// 0: query
// 1: field name of column name
// 2: field name of column type
// 3: field name of default value
// 4: field name of nullable value
// 5: expected field value to be nullable
// 6: field name of primary key flag
// 7: expected field value to be a primary key
// 8: field name of auto increment check (optional)
// 9: expected field value to be an auto-incremented identifier
$cmd=[
'sqlite2?'=>[
'SELECT * FROM pragma_table_info('.$this->quote($table).') JOIN ('.
'SELECT sql FROM sqlite_master WHERE (type=\'table\' OR type=\'view\') AND '.
'name='.$this->quote($table).')',
'name','type','dflt_value','notnull',0,'pk',TRUE,'sql',
'/\W(%s)\W+[^,]+?AUTOINCREMENT\W/i'],
'mysql'=>[
'SHOW columns FROM `'.$this->dbname.'`.`'.$table.'`',
'Field','Type','Default','Null','YES','Key','PRI','Extra','auto_increment'],
'mssql|sqlsrv|sybase|dblib|pgsql|odbc'=>[
'SELECT '.
'C.COLUMN_NAME AS field,'.
'C.DATA_TYPE AS type,'.
'C.COLUMN_DEFAULT AS defval,'.
'C.IS_NULLABLE AS nullable,'.
($this->engine=='pgsql'
?'COALESCE(POSITION(\'nextval\' IN C.COLUMN_DEFAULT),0) AS autoinc,'
:'columnproperty(object_id(C.TABLE_NAME),C.COLUMN_NAME,\'IsIdentity\')'
.' AS autoinc,').
'T.CONSTRAINT_TYPE AS pkey '.
'FROM INFORMATION_SCHEMA.COLUMNS AS C '.
'LEFT OUTER JOIN '.
'INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K '.
'ON '.
'C.TABLE_NAME=K.TABLE_NAME AND '.
'C.COLUMN_NAME=K.COLUMN_NAME AND '.
'C.TABLE_SCHEMA=K.TABLE_SCHEMA '.
($this->dbname?
('AND C.TABLE_CATALOG=K.TABLE_CATALOG '):'').
'LEFT OUTER JOIN '.
'INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS T ON '.
'K.TABLE_NAME=T.TABLE_NAME AND '.
'K.CONSTRAINT_NAME=T.CONSTRAINT_NAME AND '.
'K.TABLE_SCHEMA=T.TABLE_SCHEMA '.
($this->dbname?
('AND K.TABLE_CATALOG=T.TABLE_CATALOG '):'').
'WHERE '.
'C.TABLE_NAME='.$this->quote($table).
(empty($schema) ? '' : ' AND C.TABLE_SCHEMA='.$this->quote($schema)).
($this->dbname?
(' AND C.TABLE_CATALOG='.
$this->quote($this->dbname)):''),
'field','type','defval','nullable','YES','pkey','PRIMARY KEY','autoinc',1],
'oci'=>[
'SELECT c.column_name AS field, '.
'c.data_type AS type, '.
'c.data_default AS defval, '.
'c.nullable AS nullable, '.
'(SELECT t.constraint_type '.
'FROM all_cons_columns acc '.
'LEFT OUTER JOIN all_constraints t '.
'ON acc.constraint_name=t.constraint_name '.
'WHERE acc.table_name='.$this->quote($table).' '.
'AND acc.column_name=c.column_name '.
'AND constraint_type='.$this->quote('P').') AS pkey '.
'FROM all_tab_cols c '.
'WHERE c.table_name='.$this->quote($table),
'FIELD','TYPE','DEFVAL','NULLABLE','Y','PKEY','P']
];
if (is_string($fields))
$fields=\Base::instance()->split($fields);
$conv=[
'int\b|integer'=>\PDO::PARAM_INT,
'bool'=>\PDO::PARAM_BOOL,
'blob|bytea|image|binary'=>\PDO::PARAM_LOB,
'float|real|double|decimal|numeric'=>self::PARAM_FLOAT,
'.+'=>\PDO::PARAM_STR
];
foreach ($cmd as $key=>$val)
if (preg_match('/'.$key.'/',$this->engine)) {
$rows=[];
foreach ($this->exec($val[0],NULL) as $row)
if (!$fields || in_array($row[$val[1]],$fields)) {
foreach ($conv as $regex=>$type)
if (preg_match('/'.$regex.'/i',$row[$val[2]]))
break;
if (!isset($rows[$row[$val[1]]])) // handle duplicate rows in PgSQL
$rows[$row[$val[1]]]=[
'type'=>$row[$val[2]],
'pdo_type'=>$type,
'default'=>is_string($row[$val[3]])?
preg_replace('/^\s*([\'"])(.*)\1\s*/','\2',
$row[$val[3]]):$row[$val[3]],
'nullable'=>$row[$val[4]]==$val[5],
'pkey'=>$row[$val[6]]==$val[7],
'auto_inc'=>isset($val[8]) && isset($row[$val[8]])
? ($this->engine=='sqlite'?
(bool) preg_match(sprintf($val[9],$row[$val[1]]),
$row[$val[8]]):
($row[$val[8]]==$val[9])
) : NULL,
];
}
if ($fw->CACHE && $ttl)
// Save to cache backend
$cache->set($hash,$rows,$ttl);
return $rows;
}
throw new \Exception(sprintf(self::E_PKey,$table));
}
/**
* Quote string
* @return string
* @param $val mixed
* @param $type int
**/
function quote($val,$type=\PDO::PARAM_STR) {
return $this->engine=='odbc'?
(is_string($val)?
\Base::instance()->stringify(str_replace('\'','\'\'',$val)):
$val):
$this->pdo->quote($val,$type);
}
/**
* Return UUID
* @return string
**/
function uuid() {
return $this->uuid;
}
/**
* Return parent object
* @return \PDO
**/
function pdo() {
return $this->pdo;
}
/**
* Return database engine
* @return string
**/
function driver() {
return $this->engine;
}
/**
* Return server version
* @return string
**/
function version() {
return $this->pdo->getattribute(\PDO::ATTR_SERVER_VERSION);
}
/**
* Return database name
* @return string
**/
function name() {
return $this->dbname;
}
/**
* Return quoted identifier name
* @return string
* @param $key
* @param bool $split
**/
function quotekey($key, $split=TRUE) {
$delims=[
'sqlite2?|mysql'=>'``',
'pgsql|oci'=>'""',
'mssql|sqlsrv|odbc|sybase|dblib'=>'[]'
];
$use='';
foreach ($delims as $engine=>$delim)
if (preg_match('/'.$engine.'/',$this->engine)) {
$use=$delim;
break;
}
return $use[0].($split ? implode($use[1].'.'.$use[0],explode('.',$key))
: $key).$use[1];
}
/**
* Redirect call to PDO object
* @return mixed
* @param $func string
* @param $args array
**/
function __call($func,array $args) {
return call_user_func_array([$this->pdo,$func],$args);
}
//! Prohibit cloning
private function __clone() {
}
/**
* Instantiate class
* @param $dsn string
* @param $user string
* @param $pw string
* @param $options array
**/
function __construct($dsn,$user=NULL,$pw=NULL,?array $options=NULL) {
$fw=\Base::instance();
$this->uuid=$fw->hash($this->dsn=$dsn);
if (preg_match('/^.+?(?:dbname|database)=(.+?)(?=;|$)/is',$dsn,$parts))
$this->dbname=str_replace('\\ ',' ',$parts[1]);
if (!$options)
$options=[];
if (isset($parts[0]) && strstr($parts[0],':',TRUE)=='mysql')
$options+=[\PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES '.
strtolower(str_replace('-','',$fw->ENCODING)).';'];
$this->pdo=new \PDO($dsn,$user,$pw,$options);
$this->engine=$this->pdo->getattribute(\PDO::ATTR_DRIVER_NAME);
}
}

View File

@@ -0,0 +1,767 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB\SQL;
//! SQL data mapper
class Mapper extends \DB\Cursor {
//@{ Error messages
const
E_PKey='Table %s does not have a primary key';
//@}
protected
//! PDO wrapper
$db,
//! Database engine
$engine,
//! SQL table
$source,
//! SQL table (quoted)
$table,
//! Alias for SQL table
$as,
//! Last insert ID
$_id,
//! Defined fields
$fields,
//! Adhoc fields
$adhoc=[],
//! Dynamic properties
$props=[];
/**
* Return database type
* @return string
**/
function dbtype() {
return 'SQL';
}
/**
* Return mapped table
* @return string
**/
function table() {
return $this->source;
}
/**
* Return TRUE if any/specified field value has changed
* @return bool
* @param $key string
**/
function changed($key=NULL) {
if (isset($key))
return $this->fields[$key]['changed'];
foreach($this->fields as $key=>$field)
if ($field['changed'])
return TRUE;
return FALSE;
}
/**
* Return TRUE if field is defined
* @return bool
* @param $key string
**/
function exists($key) {
return array_key_exists($key,$this->fields+$this->adhoc);
}
/**
* Assign value to field
* @return scalar
* @param $key string
* @param $val scalar
**/
function set($key,$val) {
if (array_key_exists($key,$this->fields)) {
$val=is_null($val) && $this->fields[$key]['nullable']?
NULL:$this->db->value($this->fields[$key]['pdo_type'],$val);
if ($this->fields[$key]['initial']!==$val ||
$this->fields[$key]['default']!==$val && is_null($val))
$this->fields[$key]['changed']=TRUE;
return $this->fields[$key]['value']=$val;
}
// Adjust result on existing expressions
if (isset($this->adhoc[$key]))
$this->adhoc[$key]['value']=$val;
elseif (is_string($val))
// Parenthesize expression in case it's a subquery
$this->adhoc[$key]=['expr'=>'('.$val.')','value'=>NULL];
else
$this->props[$key]=$val;
return $val;
}
/**
* Retrieve value of field
* @return scalar
* @param $key string
**/
function &get($key) {
if ($key=='_id')
return $this->_id;
elseif (array_key_exists($key,$this->fields))
return $this->fields[$key]['value'];
elseif (array_key_exists($key,$this->adhoc))
return $this->adhoc[$key]['value'];
elseif (array_key_exists($key,$this->props))
return $this->props[$key];
throw new \Exception(sprintf(self::E_Field,$key));
}
/**
* Clear value of field
* @return NULL
* @param $key string
**/
function clear($key) {
if (array_key_exists($key,$this->adhoc))
unset($this->adhoc[$key]);
else
unset($this->props[$key]);
}
/**
* Invoke dynamic method
* @return mixed
* @param $func string
* @param $args array
* @deprecated (this is only used for custom dynamic properties that are callables
**/
function __call($func,$args) {
$callable = (array_key_exists($func,$this->props) ? $this->props[$func] : $this->$func);
return $callable ? call_user_func_array($callable,$args) : null;
}
/**
* Convert array to mapper object
* @return static
* @param $row array
**/
function factory($row) {
$mapper=clone($this);
$mapper->reset();
foreach ($row as $key=>$val) {
if (array_key_exists($key,$this->fields))
$var='fields';
elseif (array_key_exists($key,$this->adhoc))
$var='adhoc';
else
continue;
$mapper->{$var}[$key]['value']=$val;
$mapper->{$var}[$key]['initial']=$val;
if ($var=='fields' && $mapper->{$var}[$key]['pkey'])
$mapper->{$var}[$key]['previous']=$val;
}
$mapper->query=[clone($mapper)];
if (isset($mapper->trigger['load']))
\Base::instance()->call($mapper->trigger['load'],$mapper);
return $mapper;
}
/**
* Return fields of mapper object as an associative array
* @return array
* @param $obj object
**/
function cast($obj=NULL) {
if (!$obj)
$obj=$this;
return array_map(
function($row) {
return $row['value'];
},
$obj->fields+$obj->adhoc
);
}
/**
* Build query string and arguments
* @return array
* @param $fields string
* @param $filter string|array
* @param $options array
**/
function stringify($fields,$filter=NULL,?array $options=NULL) {
if (!$options)
$options=[];
$options+=[
'group'=>NULL,
'order'=>NULL,
'limit'=>0,
'offset'=>0,
'comment'=>NULL
];
$db=$this->db;
$sql='SELECT '.$fields.' FROM '.$this->table;
if (isset($this->as))
$sql.=' AS '.$this->db->quotekey($this->as);
$args=[];
if (is_array($filter) && !empty($filter)) {
$args=isset($filter[1]) && is_array($filter[1])?
$filter[1]:
array_slice($filter,1,NULL,TRUE);
$args=is_array($args)?$args:[1=>$args];
list($filter)=$filter;
}
if ($filter)
$sql.=' WHERE '.$filter;
if ($options['group']) {
$sql.=' GROUP BY '.implode(',',array_map(
function($str) use($db) {
return preg_replace_callback(
'/\b(\w+[._\-\w]*)\h*(HAVING.+|$)/i',
function($parts) use($db) {
return $db->quotekey($parts[1]).
(isset($parts[2])?(' '.$parts[2]):'');
},
$str
);
},
explode(',',$options['group'])));
}
if ($options['order']) {
$char=substr($db->quotekey(''),0,1);// quoting char
$order=' ORDER BY '.(is_bool(strpos($options['order'],$char))?
implode(',',array_map(function($str) use($db) {
return preg_match('/^\h*(\w+[._\-\w]*)'.
'(?:\h+((?:ASC|DESC)[\w\h]*))?\h*$/i',
$str,$parts)?
($db->quotekey($parts[1]).
(isset($parts[2])?(' '.$parts[2]):'')):$str;
},explode(',',$options['order']))):
$options['order']);
}
// SQL Server fixes
if (preg_match('/mssql|sqlsrv|odbc/', $this->engine) &&
($options['limit'] || $options['offset'])) {
// order by pkey when no ordering option was given
if (!$options['order'])
foreach ($this->fields as $key=>$field)
if ($field['pkey']) {
$order=' ORDER BY '.$db->quotekey($key);
break;
}
$ofs=$options['offset']?(int)$options['offset']:0;
$lmt=$options['limit']?(int)$options['limit']:0;
if (strncmp($db->version(),'11',2)>=0) {
// SQL Server >= 2012
$sql.=$order.' OFFSET '.$ofs.' ROWS';
if ($lmt)
$sql.=' FETCH NEXT '.$lmt.' ROWS ONLY';
}
else {
// SQL Server 2008
$sql=preg_replace('/SELECT/',
'SELECT '.
($lmt>0?'TOP '.($ofs+$lmt):'').' ROW_NUMBER() '.
'OVER ('.$order.') AS rnum,',$sql.$order,1);
$sql='SELECT * FROM ('.$sql.') x WHERE rnum > '.($ofs);
}
}
else {
if (isset($order))
$sql.=$order;
if ($options['limit'])
$sql.=' LIMIT '.(int)$options['limit'];
if ($options['offset'])
$sql.=' OFFSET '.(int)$options['offset'];
}
if ($options['comment'])
$sql.="\n".' /* '.$options['comment'].' */';
return [$sql,$args];
}
/**
* Build query string and execute
* @return static[]
* @param $fields string
* @param $filter string|array
* @param $options array
* @param $ttl int|array
**/
function select($fields,$filter=NULL,?array $options=NULL,$ttl=0) {
list($sql,$args)=$this->stringify($fields,$filter,$options);
$result=$this->db->exec($sql,$args,$ttl);
$out=[];
foreach ($result as &$row) {
foreach ($row as $field=>&$val) {
if (array_key_exists($field,$this->fields)) {
if (!is_null($val) || !$this->fields[$field]['nullable'])
$val=$this->db->value(
$this->fields[$field]['pdo_type'],$val);
}
unset($val);
}
$out[]=$this->factory($row);
unset($row);
}
return $out;
}
/**
* Return records that match criteria
* @return static[]
* @param $filter string|array
* @param $options array
* @param $ttl int|array
**/
function find($filter=NULL,?array $options=NULL,$ttl=0) {
if (!$options)
$options=[];
$options+=[
'group'=>NULL,
'order'=>NULL,
'limit'=>0,
'offset'=>0
];
$adhoc='';
foreach ($this->adhoc as $key=>$field)
$adhoc.=','.$field['expr'].' AS '.$this->db->quotekey($key);
return $this->select(
($options['group'] && !preg_match('/mysql|sqlite/',$this->engine)?
$options['group']:
implode(',',array_map([$this->db,'quotekey'],
array_keys($this->fields)))).$adhoc,$filter,$options,$ttl);
}
/**
* Count records that match criteria
* @return int
* @param $filter string|array
* @param $options array
* @param $ttl int|array
**/
function count($filter=NULL,?array $options=NULL,$ttl=0) {
$adhoc=[];
// with grouping involved, we need to wrap the actualy query and count the results
if ($subquery_mode=($options && !empty($options['group']))) {
$group_string=preg_replace('/HAVING.+$/i','',$options['group']);
$group_fields=array_flip(array_map('trim',explode(',',$group_string)));
foreach ($this->adhoc as $key=>$field)
// add adhoc fields that are used for grouping
if (isset($group_fields[$key]))
$adhoc[]=$field['expr'].' AS '.$this->db->quotekey($key);
$fields=implode(',',$adhoc);
if (empty($fields))
// Select at least one field, ideally the grouping fields
// or sqlsrv fails
$fields=$group_string;
if (preg_match('/mssql|dblib|sqlsrv/',$this->engine))
$fields='TOP 100 PERCENT '.$fields;
} else {
// for simple count just add a new adhoc counter
$fields='COUNT(*) AS '.$this->db->quotekey('_rows');
}
// no need to order for a count query as that could include virtual
// field references that are not present here
unset($options['order']);
list($sql,$args)=$this->stringify($fields,$filter,$options);
if ($subquery_mode)
$sql='SELECT COUNT(*) AS '.$this->db->quotekey('_rows').' '.
'FROM ('.$sql.') AS '.$this->db->quotekey('_temp');
$result=$this->db->exec($sql,$args,$ttl);
unset($this->adhoc['_rows']);
return (int)$result[0]['_rows'];
}
/**
* Return record at specified offset using same criteria as
* previous load() call and make it active
* @return static
* @param $ofs int
**/
function skip($ofs=1) {
$out=parent::skip($ofs);
$dry=$this->dry();
foreach ($this->fields as $key=>&$field) {
$field['value']=$dry?NULL:$out->fields[$key]['value'];
$field['initial']=$field['value'];
$field['changed']=FALSE;
if ($field['pkey'])
$field['previous']=$dry?NULL:$out->fields[$key]['value'];
unset($field);
}
foreach ($this->adhoc as $key=>&$field) {
$field['value']=$dry?NULL:$out->adhoc[$key]['value'];
unset($field);
}
if (!$dry && isset($this->trigger['load']))
\Base::instance()->call($this->trigger['load'],$this);
return $out;
}
/**
* Insert new record
* @return static
**/
function insert() {
$args=[];
$actr=0;
$nctr=0;
$fields='';
$values='';
$filter='';
$pkeys=[];
$aikeys=[];
$nkeys=[];
$ckeys=[];
$inc=NULL;
foreach ($this->fields as $key=>$field)
if ($field['pkey'])
$pkeys[$key]=$field['previous'];
if (isset($this->trigger['beforeinsert']) &&
\Base::instance()->call($this->trigger['beforeinsert'],
[$this,$pkeys])===FALSE)
return $this;
if ($this->valid())
// duplicate record
foreach ($this->fields as $key=>&$field) {
$field['changed']=true;
if ($field['pkey'] && !$inc && ($field['auto_inc'] === TRUE ||
($field['auto_inc'] === NULL && !$field['nullable']
&& $field['pdo_type']==\PDO::PARAM_INT)
))
$inc=$key;
unset($field);
}
foreach ($this->fields as $key=>&$field) {
if ($field['auto_inc']) {
$aikeys[] = $key;
}
if ($field['pkey']) {
$field['previous']=$field['value'];
if (!$inc && empty($field['value']) &&
($field['auto_inc'] === TRUE || ($field['auto_inc'] === NULL
&& $field['pdo_type']==\PDO::PARAM_INT && !$field['nullable']))
)
$inc=$key;
$filter.=($filter?' AND ':'').$this->db->quotekey($key).'=?';
$nkeys[$nctr+1]=[$field['value'],$field['pdo_type']];
++$nctr;
}
if ($field['changed'] && $key!=$inc) {
$fields.=($actr?',':'').$this->db->quotekey($key);
$values.=($actr?',':'').'?';
$args[$actr+1]=[$field['value'],$field['pdo_type']];
++$actr;
$ckeys[]=$key;
}
unset($field);
}
if ($fields) {
$add=$aik='';
if ($this->engine=='pgsql' && !empty($pkeys)) {
$names=array_keys($pkeys);
$aik=end($names);
$add=' RETURNING '.$this->db->quotekey($aik);
}
$lID=$this->db->exec(
(preg_match('/mssql|dblib|sqlsrv/',$this->engine) &&
array_intersect(array_keys($aikeys),$ckeys)?
'SET IDENTITY_INSERT '.$this->table.' ON;':'').
'INSERT INTO '.$this->table.' ('.$fields.') '.
'VALUES ('.$values.')'.$add,$args
);
if ($this->engine=='pgsql' && $lID && $aik)
$this->_id=$lID[0][$aik];
elseif ($this->engine!='oci')
$this->_id=$this->db->lastinsertid();
// Reload to obtain default and auto-increment field values
if ($reload=(($inc && $this->_id) || $filter))
$this->load($inc?
[$inc.'=?',$this->db->value(
$this->fields[$inc]['pdo_type'],$this->_id)]:
[$filter,$nkeys]);
if (isset($this->trigger['afterinsert']))
\Base::instance()->call($this->trigger['afterinsert'],
[$this,$pkeys]);
// reset changed flag after calling afterinsert
if (!$reload)
foreach ($this->fields as $key=>&$field) {
$field['changed']=FALSE;
$field['initial']=$field['value'];
unset($field);
}
}
return $this;
}
/**
* Update current record
* @return static
**/
function update() {
$args=[];
$ctr=0;
$pairs='';
$pkeys=[];
foreach ($this->fields as $key=>$field)
if ($field['pkey'])
$pkeys[$key]=$field['previous'];
if (isset($this->trigger['beforeupdate']) &&
\Base::instance()->call($this->trigger['beforeupdate'],
[$this,$pkeys])===FALSE)
return $this;
foreach ($this->fields as $key=>$field)
if ($field['changed']) {
$pairs.=($pairs?',':'').$this->db->quotekey($key).'=?';
$args[++$ctr]=[$field['value'],$field['pdo_type']];
}
if ($pairs) {
$filter='';
foreach ($this->fields as $key=>$field)
if ($field['pkey']) {
$filter.=($filter?' AND ':' WHERE ').
$this->db->quotekey($key).'=?';
$args[++$ctr]=[$field['previous'],$field['pdo_type']];
}
if (!$filter)
throw new \Exception(sprintf(self::E_PKey,$this->source));
$sql='UPDATE '.$this->table.' SET '.$pairs.$filter;
$this->db->exec($sql,$args);
}
if (isset($this->trigger['afterupdate']))
\Base::instance()->call($this->trigger['afterupdate'],
[$this,$pkeys]);
// reset changed flag after calling afterupdate
foreach ($this->fields as $key=>&$field) {
$field['changed']=FALSE;
$field['initial']=$field['value'];
unset($field);
}
return $this;
}
/**
* batch-update multiple records at once
* @param string|array $filter
* @return int
*/
function updateAll($filter=NULL) {
$args=[];
$ctr=$out=0;
$pairs='';
foreach ($this->fields as $key=>$field)
if ($field['changed']) {
$pairs.=($pairs?',':'').$this->db->quotekey($key).'=?';
$args[++$ctr]=[$field['value'],$field['pdo_type']];
}
if ($filter)
if (is_array($filter)) {
$cond=array_shift($filter);
$args=array_merge($args,$filter);
$filter=' WHERE '.$cond;
} else
$filter=' WHERE '.$filter;
if ($pairs) {
$sql='UPDATE '.$this->table.' SET '.$pairs.$filter;
$out = $this->db->exec($sql,$args);
}
// reset changed flag after calling afterupdate
foreach ($this->fields as $key=>&$field) {
$field['changed']=FALSE;
$field['initial']=$field['value'];
unset($field);
}
return $out;
}
/**
* Delete current record
* @return int
* @param $quick bool
* @param $filter string|array
**/
function erase($filter=NULL,$quick=TRUE) {
if (isset($filter)) {
if (!$quick) {
$out=0;
foreach ($this->find($filter) as $mapper)
$out+=$mapper->erase();
return $out;
}
$args=[];
if (is_array($filter)) {
$args=isset($filter[1]) && is_array($filter[1])?
$filter[1]:
array_slice($filter,1,NULL,TRUE);
$args=is_array($args)?$args:[1=>$args];
list($filter)=$filter;
}
return $this->db->
exec('DELETE FROM '.$this->table.
($filter?' WHERE '.$filter:'').';',$args);
}
$args=[];
$ctr=0;
$filter='';
$pkeys=[];
foreach ($this->fields as $key=>&$field) {
if ($field['pkey']) {
$filter.=($filter?' AND ':'').$this->db->quotekey($key).'=?';
$args[$ctr+1]=[$field['previous'],$field['pdo_type']];
$pkeys[$key]=$field['previous'];
++$ctr;
}
$field['value']=NULL;
$field['changed']=(bool)$field['default'];
if ($field['pkey'])
$field['previous']=NULL;
unset($field);
}
if (!$filter)
throw new \Exception(sprintf(self::E_PKey,$this->source));
foreach ($this->adhoc as &$field) {
$field['value']=NULL;
unset($field);
}
parent::erase();
if (isset($this->trigger['beforeerase']) &&
\Base::instance()->call($this->trigger['beforeerase'],
[$this,$pkeys])===FALSE)
return 0;
$out=$this->db->
exec('DELETE FROM '.$this->table.' WHERE '.$filter.';',$args);
if (isset($this->trigger['aftererase']))
\Base::instance()->call($this->trigger['aftererase'],
[$this,$pkeys]);
return $out;
}
/**
* Reset cursor
* @return NULL
**/
function reset() {
foreach ($this->fields as &$field) {
$field['value']=NULL;
$field['initial']=NULL;
$field['changed']=FALSE;
if ($field['pkey'])
$field['previous']=NULL;
unset($field);
}
foreach ($this->adhoc as &$field) {
$field['value']=NULL;
unset($field);
}
parent::reset();
}
/**
* Hydrate mapper object using hive array variable
* @return NULL
* @param $var array|string
* @param $func callback
**/
function copyfrom($var,$func=NULL) {
if (is_string($var))
$var=\Base::instance()->$var;
if ($func)
$var=call_user_func($func,$var);
foreach ($var as $key=>$val)
if (in_array($key,array_keys($this->fields)))
$this->set($key,$val);
}
/**
* Populate hive array variable with mapper fields
* @return NULL
* @param $key string
**/
function copyto($key) {
$var=&\Base::instance()->ref($key);
foreach ($this->fields+$this->adhoc as $key=>$field)
$var[$key]=$field['value'];
}
/**
* Return schema and, if the first argument is provided, update it
* @return array
* @param $fields NULL|array
**/
function schema($fields=null) {
if ($fields)
$this->fields = $fields;
return $this->fields;
}
/**
* Return field names
* @return array
* @param $adhoc bool
**/
function fields($adhoc=TRUE) {
return array_keys($this->fields+($adhoc?$this->adhoc:[]));
}
/**
* Return TRUE if field is not nullable
* @return bool
* @param $field string
**/
function required($field) {
return isset($this->fields[$field]) &&
!$this->fields[$field]['nullable'];
}
/**
* Retrieve external iterator for fields
* @return object
**/
function getiterator() {
return new \ArrayIterator($this->cast());
}
/**
* Assign alias for table
* @param $alias string
**/
function alias($alias) {
$this->as=$alias;
return $this;
}
/**
* Instantiate class
* @param $db \DB\SQL
* @param $table string
* @param $fields array|string
* @param $ttl int|array
**/
function __construct(\DB\SQL $db,$table,$fields=NULL,$ttl=60) {
$this->db=$db;
$this->engine=$db->driver();
if ($this->engine=='oci')
$table=strtoupper($table);
$this->source=$table;
$this->table=$this->db->quotekey($table);
$this->fields=$db->schema($table,$fields,$ttl);
$this->reset();
}
}

View File

@@ -0,0 +1,235 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace DB\SQL;
use ReturnTypeWillChange;
use SessionAdapter;
//! SQL-managed session handler
class Session extends Mapper {
protected
//! Session ID
$sid,
//! Anti-CSRF token
$_csrf,
//! User agent
$_agent,
//! IP,
$_ip,
//! Suspect callback
$onsuspect;
/**
* Open session
* @return TRUE
* @param $path string
* @param $name string
**/
function open(string $path, string $name): bool
{
return TRUE;
}
/**
* Close session
* @return TRUE
**/
function close(): bool
{
$this->reset();
$this->sid=NULL;
return TRUE;
}
/**
* Return session data in serialized format
* @return string|false
* @param $id string
**/
#[ReturnTypeWillChange]
function read(string $id)
{
$this->load(['session_id=?',$this->sid=$id]);
if ($this->dry())
return '';
if ($this->get('ip')!=$this->_ip || $this->get('agent')!=$this->_agent) {
$fw=\Base::instance();
if (!isset($this->onsuspect) ||
$fw->call($this->onsuspect,[$this,$id])===FALSE) {
//NB: `session_destroy` can't be called at that stage (`session_start` not completed)
$this->destroy($id);
$this->close();
unset($fw->{'COOKIE.'.session_name()});
$fw->error(403);
}
}
return $this->get('data');
}
/**
* Write session data
* @return TRUE
* @param $id string
* @param $data string
**/
function write(string $id, string $data): bool
{
$this->set('session_id',$id);
$this->set('data',$data);
$this->set('ip',$this->_ip);
$this->set('agent',$this->_agent);
$this->set('stamp',time());
$this->save();
return TRUE;
}
/**
* Destroy session
* @return TRUE
* @param $id string
**/
function destroy($id): bool
{
$this->erase(['session_id=?',$id]);
return TRUE;
}
/**
* Garbage collector
**/
#[ReturnTypeWillChange]
function gc(int $max_lifetime): int
{
return (int) $this->erase(['stamp+?<?',$max_lifetime,time()]);
}
/**
* Return session id (if session has started)
* @return string|NULL
**/
function sid() {
return $this->sid;
}
/**
* Return anti-CSRF token
* @return string
**/
function csrf() {
return $this->_csrf;
}
/**
* Return IP address
* @return string
**/
function ip() {
return $this->_ip;
}
/**
* Return Unix timestamp
* @return string|FALSE
**/
function stamp() {
if (!$this->sid)
session_start();
return $this->dry()?FALSE:$this->get('stamp');
}
/**
* Return HTTP user agent
* @return string
**/
function agent() {
return $this->_agent;
}
/**
* Instantiate class
* @param $db \DB\SQL
* @param $table string
* @param $force bool
* @param $onsuspect callback
* @param $key string
* @param $type string, column type for data field
**/
function __construct(\DB\SQL $db,$table='sessions',$force=TRUE,$onsuspect=NULL,$key=NULL,$type='TEXT') {
if ($force) {
$eol="\n";
$tab="\t";
$sqlsrv=preg_match('/mssql|sqlsrv|sybase/',$db->driver());
$db->exec(
($sqlsrv?
('IF NOT EXISTS (SELECT * FROM sysobjects WHERE '.
'name='.$db->quote($table).' AND xtype=\'U\') '.
'CREATE TABLE dbo.'):
('CREATE TABLE IF NOT EXISTS '.
((($name=$db->name())&&$db->driver()!='pgsql')?
($db->quotekey($name,FALSE).'.'):''))).
$db->quotekey($table,FALSE).' ('.$eol.
($sqlsrv?$tab.$db->quotekey('id').' INT IDENTITY,'.$eol:'').
$tab.$db->quotekey('session_id').' VARCHAR(255),'.$eol.
$tab.$db->quotekey('data').' '.$type.','.$eol.
$tab.$db->quotekey('ip').' VARCHAR(45),'.$eol.
$tab.$db->quotekey('agent').' VARCHAR(300),'.$eol.
$tab.$db->quotekey('stamp').' INTEGER,'.$eol.
$tab.'PRIMARY KEY ('.$db->quotekey($sqlsrv?'id':'session_id').')'.$eol.
($sqlsrv?',CONSTRAINT [UK_session_id] UNIQUE(session_id)':'').
');'
);
}
parent::__construct($db,$table);
$this->onsuspect=$onsuspect;
if (version_compare(PHP_VERSION, '8.4.0')>=0) {
// TODO: remove this when php7 support is dropped
session_set_save_handler(new SessionAdapter($this));
} else {
session_set_save_handler(
[$this,'open'],
[$this,'close'],
[$this,'read'],
[$this,'write'],
[$this,'destroy'],
[$this,'gc']
);
}
register_shutdown_function('session_commit');
$fw=\Base::instance();
$headers=$fw->HEADERS;
$this->_csrf=$fw->hash($fw->SEED.
extension_loaded('openssl')?
implode(unpack('L',openssl_random_pseudo_bytes(4))):
mt_rand()
);
if ($key)
$fw->$key=$this->_csrf;
$this->_agent=isset($headers['User-Agent'])?$headers['User-Agent']:'';
if (strlen($this->_agent) > 300) {
$this->_agent = substr($this->_agent, 0, 300);
}
$this->_ip=$fw->IP;
}
}

View File

@@ -0,0 +1,42 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Legacy mode enabler
class F3 {
static
//! Framework instance
$fw;
/**
* Forward function calls to framework
* @return mixed
* @param $func callback
* @param $args array
**/
static function __callstatic($func,array $args) {
if (!self::$fw)
self::$fw=Base::instance();
return call_user_func_array([self::$fw,$func],$args);
}
}

View File

@@ -0,0 +1,617 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Image manipulation tools
class Image {
//@{ Messages
const
E_Color='Invalid color specified: %s',
E_File='File not found',
E_Font='CAPTCHA font not found',
E_TTF='No TrueType support in GD module',
E_Length='Invalid CAPTCHA length: %s';
//@}
//@{ Positional cues
const
POS_Left=1,
POS_Center=2,
POS_Right=4,
POS_Top=8,
POS_Middle=16,
POS_Bottom=32;
//@}
protected
//! Source filename
$file,
//! Image resource
$data,
//! Enable/disable history
$flag=FALSE,
//! Filter count
$count=0;
/**
* Convert RGB hex triad to array
* @return array|FALSE
* @param $color int|string
**/
function rgb($color) {
if (is_string($color))
$color=hexdec($color);
$hex=str_pad($hex=dechex($color),$color<4096?3:6,'0',STR_PAD_LEFT);
if (($len=strlen($hex))>6)
throw new \Exception(sprintf(self::E_Color,'0x'.$hex));
$color=str_split($hex,$len/3);
foreach ($color as &$hue) {
$hue=hexdec(str_repeat($hue,6/$len));
unset($hue);
}
return $color;
}
/**
* Invert image
* @return object
**/
function invert() {
imagefilter($this->data,IMG_FILTER_NEGATE);
return $this->save();
}
/**
* Adjust brightness (range:-255 to 255)
* @return object
* @param $level int
**/
function brightness($level) {
imagefilter($this->data,IMG_FILTER_BRIGHTNESS,$level);
return $this->save();
}
/**
* Adjust contrast (range:-100 to 100)
* @return object
* @param $level int
**/
function contrast($level) {
imagefilter($this->data,IMG_FILTER_CONTRAST,$level);
return $this->save();
}
/**
* Convert to grayscale
* @return object
**/
function grayscale() {
imagefilter($this->data,IMG_FILTER_GRAYSCALE);
return $this->save();
}
/**
* Adjust smoothness
* @return object
* @param $level int
**/
function smooth($level) {
imagefilter($this->data,IMG_FILTER_SMOOTH,$level);
return $this->save();
}
/**
* Emboss the image
* @return object
**/
function emboss() {
imagefilter($this->data,IMG_FILTER_EMBOSS);
return $this->save();
}
/**
* Apply sepia effect
* @return object
**/
function sepia() {
imagefilter($this->data,IMG_FILTER_GRAYSCALE);
imagefilter($this->data,IMG_FILTER_COLORIZE,90,60,45);
return $this->save();
}
/**
* Pixelate the image
* @return object
* @param $size int
**/
function pixelate($size) {
imagefilter($this->data,IMG_FILTER_PIXELATE,$size,TRUE);
return $this->save();
}
/**
* Blur the image using Gaussian filter
* @return object
* @param $selective bool
**/
function blur($selective=FALSE) {
imagefilter($this->data,
$selective?IMG_FILTER_SELECTIVE_BLUR:IMG_FILTER_GAUSSIAN_BLUR);
return $this->save();
}
/**
* Apply sketch effect
* @return object
**/
function sketch() {
imagefilter($this->data,IMG_FILTER_MEAN_REMOVAL);
return $this->save();
}
/**
* Flip on horizontal axis
* @return object
**/
function hflip() {
$tmp=imagecreatetruecolor(
$width=$this->width(),$height=$this->height());
imagesavealpha($tmp,TRUE);
imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
imagecopyresampled($tmp,$this->data,
0,0,$width-1,0,$width,$height,-$width,$height);
imagedestroy($this->data);
$this->data=$tmp;
return $this->save();
}
/**
* Flip on vertical axis
* @return object
**/
function vflip() {
$tmp=imagecreatetruecolor(
$width=$this->width(),$height=$this->height());
imagesavealpha($tmp,TRUE);
imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
imagecopyresampled($tmp,$this->data,
0,0,0,$height-1,$width,$height,$width,-$height);
imagedestroy($this->data);
$this->data=$tmp;
return $this->save();
}
/**
* Crop the image
* @return object
* @param $x1 int
* @param $y1 int
* @param $x2 int
* @param $y2 int
**/
function crop($x1,$y1,$x2,$y2) {
$tmp=imagecreatetruecolor($width=$x2-$x1+1,$height=$y2-$y1+1);
imagesavealpha($tmp,TRUE);
imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
imagecopyresampled($tmp,$this->data,
0,0,$x1,$y1,$width,$height,$width,$height);
imagedestroy($this->data);
$this->data=$tmp;
return $this->save();
}
/**
* Resize image (Maintain aspect ratio); Crop relative to center
* if flag is enabled; Enlargement allowed if flag is enabled
* @return object
* @param $width int
* @param $height int
* @param $crop bool
* @param $enlarge bool
**/
function resize($width=NULL,$height=NULL,$crop=TRUE,$enlarge=TRUE) {
if (is_null($width) && is_null($height))
return $this;
$origw=$this->width();
$origh=$this->height();
if (is_null($width))
$width=round(($height/$origh)*$origw);
if (is_null($height))
$height=round(($width/$origw)*$origh);
// Adjust dimensions; retain aspect ratio
$ratio=$origw/$origh;
if (!$crop) {
if ($width/$ratio<=$height)
$height=round($width/$ratio);
else
$width=round($height*$ratio);
}
if (!$enlarge) {
$width=min($origw,$width);
$height=min($origh,$height);
}
// Create blank image
$tmp=imagecreatetruecolor($width,$height);
imagesavealpha($tmp,TRUE);
imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
// Resize
if ($crop) {
if ($width/$ratio<=$height) {
$cropw=round($origh*$width/$height);
imagecopyresampled($tmp,$this->data,
0,0,round(($origw-$cropw)/2),0,$width,$height,$cropw,$origh);
}
else {
$croph=round($origw*$height/$width);
imagecopyresampled($tmp,$this->data,
0,0,0,round(($origh-$croph)/2),$width,$height,$origw,$croph);
}
}
else
imagecopyresampled($tmp,$this->data,
0,0,0,0,$width,$height,$origw,$origh);
imagedestroy($this->data);
$this->data=$tmp;
return $this->save();
}
/**
* Rotate image
* @return object
* @param $angle int
**/
function rotate($angle) {
$this->data=imagerotate($this->data,$angle,
imagecolorallocatealpha($this->data,0,0,0,127));
imagesavealpha($this->data,TRUE);
return $this->save();
}
/**
* Apply an image overlay
* @return object
* @param $img object
* @param $align int|array
* @param $alpha int
**/
function overlay(Image $img,$align=NULL,$alpha=100) {
if (is_null($align))
$align=self::POS_Right|self::POS_Bottom;
if (is_array($align)) {
list($posx,$posy)=$align;
$align = 0;
}
$ovr=imagecreatefromstring($img->dump());
imagesavealpha($ovr,TRUE);
$imgw=$this->width();
$imgh=$this->height();
$ovrw=imagesx($ovr);
$ovrh=imagesy($ovr);
if ($align & self::POS_Left)
$posx=0;
if ($align & self::POS_Center)
$posx=round(($imgw-$ovrw)/2);
if ($align & self::POS_Right)
$posx=$imgw-$ovrw;
if ($align & self::POS_Top)
$posy=0;
if ($align & self::POS_Middle)
$posy=round(($imgh-$ovrh)/2);
if ($align & self::POS_Bottom)
$posy=$imgh-$ovrh;
if (empty($posx))
$posx=0;
if (empty($posy))
$posy=0;
if ($alpha==100)
imagecopy($this->data,$ovr,$posx,$posy,0,0,$ovrw,$ovrh);
else {
$cut=imagecreatetruecolor($ovrw,$ovrh);
imagecopy($cut,$this->data,0,0,$posx,$posy,$ovrw,$ovrh);
imagecopy($cut,$ovr,0,0,0,0,$ovrw,$ovrh);
imagecopymerge($this->data,
$cut,$posx,$posy,0,0,$ovrw,$ovrh,$alpha);
}
return $this->save();
}
/**
* Generate identicon
* @return object
* @param $str string
* @param $size int
* @param $blocks int
**/
function identicon($str,$size=64,$blocks=4) {
$sprites=[
[.5,1,1,0,1,1],
[.5,0,1,0,.5,1,0,1],
[.5,0,1,0,1,1,.5,1,1,.5],
[0,.5,.5,0,1,.5,.5,1,.5,.5],
[0,.5,1,0,1,1,0,1,1,.5],
[1,0,1,1,.5,1,1,.5,.5,.5],
[0,0,1,0,1,.5,0,0,.5,1,0,1],
[0,0,.5,0,1,.5,.5,1,0,1,.5,.5],
[.5,0,.5,.5,1,.5,1,1,.5,1,.5,.5,0,.5],
[0,0,1,0,.5,.5,1,.5,.5,1,.5,.5,0,1],
[0,.5,.5,1,1,.5,.5,0,1,0,1,1,0,1],
[.5,0,1,0,1,1,.5,1,1,.75,.5,.5,1,.25],
[0,.5,.5,0,.5,.5,1,0,1,.5,.5,1,.5,.5,0,1],
[0,0,1,0,1,1,0,1,1,.5,.5,.25,.5,.75,0,.5,.5,.25],
[0,.5,.5,.5,.5,0,1,0,.5,.5,1,.5,.5,1,.5,.5,0,1],
[0,0,1,0,.5,.5,.5,0,0,.5,1,.5,.5,1,.5,.5,0,1]
];
$hash=sha1($str);
$this->data=imagecreatetruecolor($size,$size);
list($r,$g,$b)=$this->rgb(hexdec(substr($hash,-3)));
$fg=imagecolorallocate($this->data,$r,$g,$b);
imagefill($this->data,0,0,IMG_COLOR_TRANSPARENT);
$ctr=count($sprites);
$dim=$blocks*floor($size/$blocks)*2/$blocks;
for ($j=0,$y=ceil($blocks/2);$j<$y;++$j)
for ($i=$j,$x=$blocks-1-$j;$i<$x;++$i) {
$sprite=imagecreatetruecolor($dim,$dim);
imagefill($sprite,0,0,IMG_COLOR_TRANSPARENT);
$block=$sprites[hexdec($hash[($j*$blocks+$i)*2])%$ctr];
for ($k=0,$pts=count($block);$k<$pts;++$k)
$block[$k]*=$dim;
if (version_compare(PHP_VERSION, '8.1.0') >= 0) {
imagefilledpolygon($sprite,$block,$fg);
} else {
imagefilledpolygon($sprite,$block,$pts/2,$fg);
}
for ($k=0;$k<4;++$k) {
imagecopyresampled($this->data,$sprite,
round($i*$dim/2),round($j*$dim/2),0,0,round($dim/2),round($dim/2),$dim,$dim);
$this->data=imagerotate($this->data,90,
imagecolorallocatealpha($this->data,0,0,0,127));
}
imagedestroy($sprite);
}
imagesavealpha($this->data,TRUE);
return $this->save();
}
/**
* Generate CAPTCHA image
* @return object|FALSE
* @param $font string
* @param $size int
* @param $len int
* @param $key string
* @param $path string
* @param $fg int
* @param $bg int
**/
function captcha($font,$size=24,$len=5,
$key=NULL,$path='',$fg=0xFFFFFF,$bg=0x000000) {
if ((!$ssl=extension_loaded('openssl')) && ($len<4 || $len>13)) {
throw new \Exception(sprintf(self::E_Length,$len));
}
if (!function_exists('imagettftext')) {
throw new \Exception(self::E_TTF);
}
$fw=Base::instance();
foreach ($fw->split($path?:$fw->UI.';./') as $dir)
if (is_file($path=realpath($dir.$font))) {
$seed=strtoupper(substr(
$ssl?bin2hex(openssl_random_pseudo_bytes($len)):uniqid(),
-$len));
$block=$size*3;
$tmp=[];
for ($i=0,$width=0,$height=0;$i<$len;++$i) {
// Process at 2x magnification
$box=imagettfbbox($size*2,0,$path,$seed[$i]);
$w=$box[2]-$box[0];
$h=$box[1]-$box[5];
$char=imagecreatetruecolor($block,$block);
imagefill($char,0,0,$bg);
imagettftext($char,$size*2,0,
round(($block-$w)/2),round($block-($block-$h)/2),
$fg,$path,$seed[$i]);
$char=imagerotate($char,mt_rand(-30,30),
imagecolorallocatealpha($char,0,0,0,127));
// Reduce to normal size
$tmp[$i]=imagecreatetruecolor(
round(($w=imagesx($char))/2),round(($h=imagesy($char))/2));
imagefill($tmp[$i],0,0,IMG_COLOR_TRANSPARENT);
imagecopyresampled($tmp[$i],
$char,0,0,0,0,round($w/2),round($h/2),$w,$h);
imagedestroy($char);
$width+=$i+1<$len?$block/2:$w/2;
$height=max($height,$h/2);
}
$this->data=imagecreatetruecolor(round($width),round($height));
imagefill($this->data,0,0,IMG_COLOR_TRANSPARENT);
for ($i=0;$i<$len;++$i) {
imagecopy($this->data,$tmp[$i],
round($i*$block/2),round(($height-imagesy($tmp[$i]))/2),0,0,
imagesx($tmp[$i]),imagesy($tmp[$i]));
imagedestroy($tmp[$i]);
}
imagesavealpha($this->data,TRUE);
if ($key)
$fw->$key=$seed;
return $this->save();
}
throw new \Exception(self::E_Font);
}
/**
* Return image width
* @return int
**/
function width() {
return imagesx($this->data);
}
/**
* Return image height
* @return int
**/
function height() {
return imagesy($this->data);
}
/**
* Send image to HTTP client
* @return NULL
**/
function render() {
$args=func_get_args();
$format=$args?array_shift($args):'png';
if (PHP_SAPI!='cli') {
header('Content-Type: image/'.$format);
header('X-Powered-By: '.Base::instance()->PACKAGE);
}
call_user_func_array(
'image'.$format,
array_merge([$this->data,NULL],$args)
);
}
/**
* Return image as a string
* @return string
**/
function dump() {
$args=func_get_args();
$format=$args?array_shift($args):'png';
ob_start();
call_user_func_array(
'image'.$format,
array_merge([$this->data,NULL],$args)
);
return ob_get_clean();
}
/**
* Return image resource
* @return resource
**/
function data() {
return $this->data;
}
/**
* Save current state
* @return object
**/
function save() {
$fw=Base::instance();
if ($this->flag) {
if (!is_dir($dir=$fw->TEMP))
mkdir($dir,Base::MODE,TRUE);
++$this->count;
$fw->write($dir.'/'.$fw->SEED.'.'.
$fw->hash($this->file).'-'.$this->count.'.png',
$this->dump());
}
return $this;
}
/**
* Revert to specified state
* @return object
* @param $state int
**/
function restore($state=1) {
$fw=Base::instance();
if ($this->flag && is_file($file=($path=$fw->TEMP.
$fw->SEED.'.'.$fw->hash($this->file).'-').$state.'.png')) {
if (is_resource($this->data))
imagedestroy($this->data);
$this->data=imagecreatefromstring($fw->read($file));
imagesavealpha($this->data,TRUE);
foreach (glob($path.'*.png',GLOB_NOSORT) as $match)
if (preg_match('/-(\d+)\.png/',$match,$parts) &&
$parts[1]>$state)
@unlink($match);
$this->count=$state;
}
return $this;
}
/**
* Undo most recently applied filter
* @return object
**/
function undo() {
if ($this->flag) {
if ($this->count)
$this->count--;
return $this->restore($this->count);
}
return $this;
}
/**
* Load string
* @return object|FALSE
* @param $str string
**/
function load($str) {
if (!$this->data=@imagecreatefromstring($str))
return FALSE;
imagesavealpha($this->data,TRUE);
$this->save();
return $this;
}
/**
* Instantiate image
* @param $file string
* @param $flag bool
* @param $path string
**/
function __construct($file=NULL,$flag=FALSE,$path=NULL) {
$this->flag=$flag;
if ($file) {
$fw=Base::instance();
// Create image from file
$this->file=$file;
if (!isset($path))
$path=$fw->UI.';./';
foreach ($fw->split($path,FALSE) as $dir)
if (is_file($dir.$file))
return $this->load($fw->read($dir.$file));
throw new \Exception(self::E_File);
}
}
/**
* Wrap-up
* @return NULL
**/
function __destruct() {
if (is_resource($this->data)) {
imagedestroy($this->data);
$fw=Base::instance();
$path=$fw->TEMP.$fw->SEED.'.'.$fw->hash($this->file);
if ($glob=@glob($path.'*.png',GLOB_NOSORT))
foreach ($glob as $match)
if (preg_match('/-(\d+)\.png/',$match))
@unlink($match);
}
}
}

View File

@@ -0,0 +1,71 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Custom logger
class Log {
protected
//! File name
$file;
/**
* Write specified text to log file
* @return string
* @param $text string
* @param $format string
**/
function write($text,$format='r') {
$fw=Base::instance();
foreach (preg_split('/\r?\n|\r/',trim($text)) as $line)
$fw->write(
$this->file,
date($format).
(isset($_SERVER['REMOTE_ADDR'])?
(' ['.$_SERVER['REMOTE_ADDR'].
(($fwd=filter_var($fw->get('HEADERS.X-Forwarded-For'),
FILTER_VALIDATE_IP))?(' ('.$fwd.')'):'')
.']'):'').' '.
trim($line).PHP_EOL,
TRUE
);
}
/**
* Erase log
* @return NULL
**/
function erase() {
@unlink($this->file);
}
/**
* Instantiate class
* @param $file string
**/
function __construct($file) {
$fw=Base::instance();
if (!is_dir($dir=$fw->LOGS))
mkdir($dir,Base::MODE,TRUE);
$this->file=$dir.$file;
}
}

View File

@@ -0,0 +1,143 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! PHP magic wrapper
abstract class Magic implements ArrayAccess {
/**
* Return TRUE if key is not empty
* @return bool
* @param $key string
**/
abstract function exists($key);
/**
* Bind value to key
* @return mixed
* @param $key string
* @param $val mixed
**/
abstract function set($key,$val);
/**
* Retrieve contents of key
* @return mixed
* @param $key string
**/
abstract function &get($key);
/**
* Unset key
* @return NULL
* @param $key string
**/
abstract function clear($key);
/**
* Convenience method for checking property value
* @return mixed
* @param $key string
**/
#[\ReturnTypeWillChange]
function offsetexists($key) {
return Base::instance()->visible($this,$key)?
isset($this->$key):
($this->exists($key) && $this->get($key)!==NULL);
}
/**
* Convenience method for assigning property value
* @return mixed
* @param $key string
* @param $val mixed
**/
#[\ReturnTypeWillChange]
function offsetset($key,$val) {
return Base::instance()->visible($this,$key)?
($this->$key=$val):$this->set($key,$val);
}
/**
* Convenience method for retrieving property value
* @return mixed
* @param $key string
**/
#[\ReturnTypeWillChange]
function &offsetget($key) {
if (Base::instance()->visible($this,$key))
$val=&$this->$key;
else
$val=&$this->get($key);
return $val;
}
/**
* Convenience method for removing property value
* @return NULL
* @param $key string
**/
#[\ReturnTypeWillChange]
function offsetunset($key) {
if (Base::instance()->visible($this,$key))
unset($this->$key);
else
$this->clear($key);
}
/**
* Alias for offsetexists()
* @return mixed
* @param $key string
**/
function __isset($key) {
return $this->offsetexists($key);
}
/**
* Alias for offsetset()
* @return mixed
* @param $key string
* @param $val mixed
**/
function __set($key,$val) {
return $this->offsetset($key,$val);
}
/**
* Alias for offsetget()
* @return mixed
* @param $key string
**/
function &__get($key) {
$val=&$this->offsetget($key);
return $val;
}
/**
* Alias for offsetunset()
* @param $key string
**/
function __unset($key) {
$this->offsetunset($key);
}
}

View File

@@ -0,0 +1,569 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Markdown-to-HTML converter
class Markdown extends Prefab {
protected
//! Parsing rules
$blocks,
//! Special characters
$special;
/**
* Process blockquote
* @return string
* @param $str string
**/
protected function _blockquote($str) {
$str=preg_replace('/(?<=^|\n)\h?>\h?(.*?(?:\n+|$))/','\1',$str);
return strlen($str)?
('<blockquote>'.$this->build($str).'</blockquote>'."\n\n"):'';
}
/**
* Process whitespace-prefixed code block
* @return string
* @param $str string
**/
protected function _pre($str) {
$str=preg_replace('/(?<=^|\n)(?: {4}|\t)(.+?(?:\n+|$))/','\1',
$this->esc($str));
return strlen($str)?
('<pre><code>'.
$this->esc($this->snip($str)).
'</code></pre>'."\n\n"):
'';
}
/**
* Process fenced code block
* @return string
* @param $hint string
* @param $str string
**/
protected function _fence($hint,$str) {
$str=$this->snip($str);
$fw=Base::instance();
if ($fw->HIGHLIGHT) {
switch (strtolower($hint)) {
case 'php':
$str=$fw->highlight($str);
break;
case 'apache':
preg_match_all('/(?<=^|\n)(\h*)'.
'(?:(<\/?)(\w+)((?:\h+[^>]+)*)(>)|'.
'(?:(\w+)(\h.+?)))(\h*(?:\n+|$))/',
$str,$matches,PREG_SET_ORDER);
$out='';
foreach ($matches as $match)
$out.=$match[1].
($match[3]?
('<span class="section">'.
$this->esc($match[2]).$match[3].
'</span>'.
($match[4]?
('<span class="data">'.
$this->esc($match[4]).
'</span>'):
'').
'<span class="section">'.
$this->esc($match[5]).
'</span>'):
('<span class="directive">'.
$match[6].
'</span>'.
'<span class="data">'.
$this->esc($match[7]).
'</span>')).
$match[8];
$str='<code>'.$out.'</code>';
break;
case 'html':
preg_match_all(
'/(?:(?:<(\/?)(\w+)'.
'((?:\h+(?:\w+\h*=\h*)?".+?"|[^>]+)*|'.
'\h+.+?)(\h*\/?)>)|(.+?))/s',
$str,$matches,PREG_SET_ORDER
);
$out='';
foreach ($matches as $match) {
if ($match[2]) {
$out.='<span class="xml_tag">&lt;'.
$match[1].$match[2].'</span>';
if ($match[3]) {
preg_match_all(
'/(?:\h+(?:(?:(\w+)\h*=\h*)?'.
'(".+?")|(.+)))/',
$match[3],$parts,PREG_SET_ORDER
);
foreach ($parts as $part)
$out.=' '.
(empty($part[3])?
((empty($part[1])?
'':
('<span class="xml_attr">'.
$part[1].'</span>=')).
'<span class="xml_data">'.
$part[2].'</span>'):
('<span class="xml_tag">'.
$part[3].'</span>'));
}
$out.='<span class="xml_tag">'.
$match[4].'&gt;</span>';
}
else
$out.=$this->esc($match[5]);
}
$str='<code>'.$out.'</code>';
break;
case 'ini':
preg_match_all(
'/(?<=^|\n)(?:'.
'(;[^\n]*)|(?:<\?php.+?\?>?)|'.
'(?:\[(.+?)\])|'.
'(.+?)(\h*=\h*)'.
'((?:\\\\\h*\r?\n|.+?)*)'.
')((?:\r?\n)+|$)/',
$str,$matches,PREG_SET_ORDER
);
$out='';
foreach ($matches as $match) {
if ($match[1])
$out.='<span class="comment">'.$match[1].
'</span>';
elseif ($match[2])
$out.='<span class="ini_section">['.$match[2].']'.
'</span>';
elseif ($match[3])
$out.='<span class="ini_key">'.$match[3].
'</span>'.$match[4].
($match[5]?
('<span class="ini_value">'.
$match[5].'</span>'):'');
else
$out.=$match[0];
if (isset($match[6]))
$out.=$match[6];
}
$str='<code>'.$out.'</code>';
break;
default:
$str='<code>'.$this->esc($str).'</code>';
break;
}
}
else
$str='<code>'.$this->esc($str).'</code>';
return '<pre>'.$str.'</pre>'."\n\n";
}
/**
* Process horizontal rule
* @return string
**/
protected function _hr() {
return '<hr />'."\n\n";
}
/**
* Process atx-style heading
* @return string
* @param $type string
* @param $str string
**/
protected function _atx($type,$str) {
$level=strlen($type);
return '<h'.$level.' id="'.Web::instance()->slug($str).'">'.
$this->scan($str).'</h'.$level.'>'."\n\n";
}
/**
* Process setext-style heading
* @return string
* @param $str string
* @param $type string
**/
protected function _setext($str,$type) {
$level=strpos('=-',$type)+1;
return '<h'.$level.' id="'.Web::instance()->slug($str).'">'.
$this->scan($str).'</h'.$level.'>'."\n\n";
}
/**
* Process ordered/unordered list
* @return string
* @param $str string
**/
protected function _li($str) {
// Initialize list parser
$len=strlen($str);
$ptr=0;
$dst='';
$first=TRUE;
$tight=TRUE;
$type='ul';
// Main loop
while ($ptr<$len) {
if (preg_match('/^\h*[*\-](?:\h?[*\-]){2,}(?:\n+|$)/',
substr($str,$ptr),$match)) {
$ptr+=strlen($match[0]);
// Embedded horizontal rule
return (strlen($dst)?
('<'.$type.'>'."\n".$dst.'</'.$type.'>'."\n\n"):'').
'<hr />'."\n\n".$this->build(substr($str,$ptr));
}
elseif (preg_match('/(?<=^|\n)([*+\-]|\d+\.)\h'.
'(.+?(?:\n+|$))((?:(?: {4}|\t)+.+?(?:\n+|$))*)/s',
substr($str,$ptr),$match)) {
$match[3]=preg_replace('/(?<=^|\n)(?: {4}|\t)/','',$match[3]);
$found=FALSE;
foreach (array_slice($this->blocks,0,-1) as $regex)
if (preg_match($regex,$match[3])) {
$found=TRUE;
break;
}
// List
if ($first) {
// First pass
if (is_numeric($match[1]))
$type='ol';
if (preg_match('/\n{2,}$/',$match[2].
($found?'':$match[3])))
// Loose structure; Use paragraphs
$tight=FALSE;
$first=FALSE;
}
// Strip leading whitespaces
$ptr+=strlen($match[0]);
$tmp=$this->snip($match[2].$match[3]);
if ($tight) {
if ($found)
$tmp=$match[2].$this->build($this->snip($match[3]));
}
else
$tmp=$this->build($tmp);
$dst.='<li>'.$this->scan(trim($tmp)).'</li>'."\n";
}
}
return strlen($dst)?
('<'.$type.'>'."\n".$dst.'</'.$type.'>'."\n\n"):'';
}
/**
* Ignore raw HTML
* @return string
* @param $str string
**/
protected function _raw($str) {
return $str;
}
/**
* Process paragraph
* @return string
* @param $str string
**/
protected function _p($str) {
$str=trim($str);
if (strlen($str)) {
if (preg_match('/^(.+?\n)([>#].+)$/s',$str,$parts))
return $this->_p($parts[1]).$this->build($parts[2]);
$str=preg_replace_callback(
'/([^<>\[]+)?(<[\?%].+?[\?%]>|<.+?>|\[.+?\]\s*\(.+?\))|'.
'(.+)/s',
function($expr) {
$tmp='';
if (isset($expr[4]))
$tmp.=$this->esc($expr[4]);
else {
if (isset($expr[1]))
$tmp.=$this->esc($expr[1]);
$tmp.=$expr[2];
if (isset($expr[3]))
$tmp.=$this->esc($expr[3]);
}
return $tmp;
},
$str
);
$str=preg_replace('/\s{2}\r?\n/','<br />',$str);
return '<p>'.$this->scan($str).'</p>'."\n\n";
}
return '';
}
/**
* Process strong/em/strikethrough spans
* @return string
* @param $str string
**/
protected function _text($str) {
$tmp='';
while ($str!=$tmp)
$str=preg_replace_callback(
'/(?<=\s|^)(?<!\\\\)([*_])([*_]?)([*_]?)(.*?)(?!\\\\)\3\2\1(?=[\s[:punct:]]|$)/',
function($expr) {
if ($expr[3])
return '<strong><em>'.$expr[4].'</em></strong>';
if ($expr[2])
return '<strong>'.$expr[4].'</strong>';
return '<em>'.$expr[4].'</em>';
},
preg_replace(
'/(?<!\\\\)~~(.*?)(?!\\\\)~~(?=[\s[:punct:]]|$)/',
'<del>\1</del>',
$tmp=$str
)
);
return $str;
}
/**
* Process image span
* @return string
* @param $str string
**/
protected function _img($str) {
return preg_replace_callback(
'/!(?:\[(.+?)\])?\h*\(<?(.*?)>?(?:\h*"(.*?)"\h*)?\)/',
function($expr) {
return '<img src="'.$expr[2].'"'.
(empty($expr[1])?
'':
(' alt="'.$this->esc($expr[1]).'"')).
(empty($expr[3])?
'':
(' title="'.$this->esc($expr[3]).'"')).' />';
},
$str
);
}
/**
* Process anchor span
* @return string
* @param $str string
**/
protected function _a($str) {
return preg_replace_callback(
'/(?<!\\\\)\[(.+?)(?!\\\\)\]\h*\(<?(.*?)>?(?:\h*"(.*?)"\h*)?\)/',
function($expr) {
return '<a href="'.$this->esc($expr[2]).'"'.
(empty($expr[3])?
'':
(' title="'.$this->esc($expr[3]).'"')).
'>'.$this->scan($expr[1]).'</a>';
},
$str
);
}
/**
* Auto-convert links
* @return string
* @param $str string
**/
protected function _auto($str) {
return preg_replace_callback(
'/`.*?<(.+?)>.*?`|<(.+?)>/',
function($expr) {
if (empty($expr[1]) && parse_url($expr[2],PHP_URL_SCHEME)) {
$expr[2]=$this->esc($expr[2]);
return '<a href="'.$expr[2].'">'.$expr[2].'</a>';
}
return $expr[0];
},
$str
);
}
/**
* Process code span
* @return string
* @param $str string
**/
protected function _code($str) {
return preg_replace_callback(
'/`` (.+?) ``|(?<!\\\\)`(.+?)(?!\\\\)`/',
function($expr) {
return '<code>'.
$this->esc(empty($expr[1])?$expr[2]:$expr[1]).'</code>';
},
$str
);
}
/**
* Convert characters to HTML entities
* @return string
* @param $str string
**/
function esc($str) {
if (!$this->special)
$this->special=[
'...'=>'&hellip;',
'(tm)'=>'&trade;',
'(r)'=>'&reg;',
'(c)'=>'&copy;'
];
foreach ($this->special as $key=>$val)
$str=preg_replace('/'.preg_quote($key,'/').'/i',$val,$str);
return htmlspecialchars($str,ENT_COMPAT,
Base::instance()->ENCODING,FALSE);
}
/**
* Reduce multiple line feeds
* @return string
* @param $str string
**/
protected function snip($str) {
return preg_replace('/(?:(?<=\n)\n+)|\n+$/',"\n",$str);
}
/**
* Scan line for convertible spans
* @return string
* @param $str string
**/
function scan($str) {
$inline=['img','a','text','auto','code'];
foreach ($inline as $func)
$str=$this->{'_'.$func}($str);
return $str;
}
/**
* Assemble blocks
* @return string
* @param $str string
**/
protected function build($str) {
if (!$this->blocks) {
// Regexes for capturing entire blocks
$this->blocks=[
'blockquote'=>'/^(?:\h?>\h?.*?(?:\n+|$))+/',
'pre'=>'/^(?:(?: {4}|\t).+?(?:\n+|$))+/',
'fence'=>'/^`{3}\h*(\w+)?.*?[^\n]*\n+(.+?)`{3}[^\n]*'.
'(?:\n+|$)/s',
'hr'=>'/^\h*[*_\-](?:\h?[\*_\-]){2,}\h*(?:\n+|$)/',
'atx'=>'/^\h*(#{1,6})\h?(.+?)\h*(?:#.*)?(?:\n+|$)/u',
'setext'=>'/^\h*(.+?)\h*\n([=\-])+\h*(?:\n+|$)/u',
'li'=>'/^(?:(?:[*+\-]|\d+\.)\h.+?(?:\n+|$)'.
'(?:(?: {4}|\t)+.+?(?:\n+|$))*)+/s',
'raw'=>'/^((?:<!--.+?-->|'.
'<(address|article|aside|audio|blockquote|canvas|dd|'.
'div|dl|fieldset|figcaption|figure|footer|form|h\d|'.
'header|hgroup|hr|noscript|object|ol|output|p|pre|'.
'section|table|tfoot|ul|video).*?'.
'(?:\/>|>(?:(?>[^><]+)|(?R))*<\/\2>))'.
'\h*(?:\n{2,}|\n*$)|<[\?%].+?[\?%]>\h*(?:\n?$|\n*))/s',
'p'=>'/^(.+?(?:\n{2,}|\n*$))/s'
];
}
// Treat lines with nothing but whitespaces as empty lines
$str=preg_replace('/\n\h+(?=\n)/',"\n",$str);
// Initialize block parser
$len=strlen($str);
$ptr=0;
$dst='';
// Main loop
while ($ptr<$len) {
if (preg_match('/^ {0,3}\[([^\[\]]+)\]:\s*<?(.*?)>?\s*'.
'(?:"([^\n]*)")?(?:\n+|$)/s',substr($str,$ptr),$match)) {
// Reference-style link; Backtrack
$ptr+=strlen($match[0]);
$tmp='';
// Catch line breaks in title attribute
$ref=preg_replace('/\h/','\s',preg_quote($match[1],'/'));
while ($dst!=$tmp) {
$dst=preg_replace_callback(
'/(?<!\\\\)\[('.$ref.')(?!\\\\)\]\s*\[\]|'.
'(!?)(?:\[([^\[\]]+)\]\s*)?'.
'(?<!\\\\)\[('.$ref.')(?!\\\\)\]/',
function($expr) use($match) {
return (empty($expr[2]))?
// Anchor
('<a href="'.$this->esc($match[2]).'"'.
(empty($match[3])?
'':
(' title="'.
$this->esc($match[3]).'"')).'>'.
// Link
$this->scan(
empty($expr[3])?
(empty($expr[1])?
$expr[4]:
$expr[1]):
$expr[3]
).'</a>'):
// Image
('<img src="'.$match[2].'"'.
(empty($expr[2])?
'':
(' alt="'.
$this->esc($expr[3]).'"')).
(empty($match[3])?
'':
(' title="'.
$this->esc($match[3]).'"')).
' />');
},
$tmp=$dst
);
}
}
else
foreach ($this->blocks as $func=>$regex)
if (preg_match($regex,substr($str,$ptr),$match)) {
$ptr+=strlen($match[0]);
$dst.=call_user_func_array(
[$this,'_'.$func],
count($match)>1?array_slice($match,1):$match
);
break;
}
}
return $dst;
}
/**
* Render HTML equivalent of markdown
* @return string
* @param $txt string
**/
function convert($txt) {
$txt=preg_replace_callback(
'/(<code.*?>.+?<\/code>|'.
'<[^>\n]+>|\([^\n\)]+\)|"[^"\n]+")|'.
'\\\\(.)/s',
function($expr) {
// Process escaped characters
return empty($expr[1])?$expr[2]:$expr[1];
},
$this->build(preg_replace('/\r\n|\r/',"\n",$txt))
);
return $this->snip($txt);
}
}

View File

@@ -0,0 +1,139 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Generic array utilities
class Matrix extends Prefab {
/**
* Retrieve values from a specified column of a multi-dimensional
* array variable
* @return array
* @param $var array
* @param $col mixed
**/
function pick(array $var,$col) {
return array_map(
function($row) use($col) {
return $row[$col];
},
$var
);
}
/**
* select a subset of fields from an input array
* @param string|array $fields splittable string or array
* @param string|array $data hive key or array
* @return array
*/
function select($fields, $data) {
return array_intersect_key(is_array($data) ? $data : \Base::instance()->get($data),
array_flip(is_array($fields) ? $fields : \Base::instance()->split($fields)));
}
/**
* walk with a callback function through a subset of fields from an input array
* the callback receives the value, index-key and the full input array as parameters
* set value parameter as reference and you're able to modify the data as well
* @param string|array $fields splittable string or array of fields
* @param string|array $data hive key or input array
* @param callable $callback (mixed &$value, string $key, array $data)
* @return array modified subset data
*/
function walk($fields, $data, $callback) {
$subset=$this->select($fields, $data);
array_walk($subset, $callback, $data);
return $subset;
}
/**
* Rotate a two-dimensional array variable
* @return NULL
* @param $var array
**/
function transpose(array &$var) {
$out=[];
foreach ($var as $keyx=>$cols)
foreach ($cols as $keyy=>$valy)
$out[$keyy][$keyx]=$valy;
$var=$out;
}
/**
* Sort a multi-dimensional array variable on a specified column
* @return bool
* @param $var array
* @param $col mixed
* @param $order int
**/
function sort(array &$var,$col,$order=SORT_ASC) {
uasort(
$var,
function($val1,$val2) use($col,$order) {
list($v1,$v2)=[$val1[$col],$val2[$col]];
$out=is_numeric($v1) && is_numeric($v2)?
Base::instance()->sign($v1-$v2):strcmp($v1,$v2);
if ($order==SORT_DESC)
$out=-$out;
return $out;
}
);
$var=array_values($var);
}
/**
* Change the key of a two-dimensional array element
* @return NULL
* @param $var array
* @param $old string
* @param $new string
**/
function changekey(array &$var,$old,$new) {
$keys=array_keys($var);
$vals=array_values($var);
$keys[array_search($old,$keys)]=$new;
$var=array_combine($keys,$vals);
}
/**
* Return month calendar of specified date, with optional setting for
* first day of week (0 for Sunday)
* @return array
* @param $date string|int
* @param $first int
**/
function calendar($date='now',$first=0) {
$out=FALSE;
if (extension_loaded('calendar')) {
if (is_string($date))
$date=strtotime($date);
$parts=getdate($date);
$days=cal_days_in_month(CAL_GREGORIAN,$parts['mon'],$parts['year']);
$ref=date('w',strtotime(date('Y-m',$parts[0]).'-01'))+(7-$first)%7;
$out=[];
for ($i=0;$i<$days;++$i)
$out[floor(($ref+$i)/7)][($ref+$i)%7]=$i+1;
}
return $out;
}
}

View File

@@ -0,0 +1,231 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Cache-based session handler
class Session extends Magic {
protected
//! Session ID
$sid,
//! Anti-CSRF token
$_csrf,
//! User agent
$_agent,
//! IP,
$_ip,
//! Suspect callback
$onsuspect,
//! Cache instance
$_cache,
//! Session meta data
$_data=[];
/**
* Open session
* @return TRUE
* @param $path string
* @param $name string
**/
function open(string $path, string $name): bool
{
return TRUE;
}
/**
* Close session
* @return TRUE
**/
function close(): bool
{
$this->sid=NULL;
$this->_data=[];
return TRUE;
}
/**
* Return session data in serialized format
* @return false|string
* @param $id string
**/
#[ReturnTypeWillChange]
function read(string $id)
{
$this->sid=$id;
if (!$data=$this->_cache->get($id.'.@'))
return '';
$this->_data = $data;
if ($data['ip']!=$this->_ip || $data['agent']!=$this->_agent) {
$fw=Base::instance();
if (!isset($this->onsuspect) ||
$fw->call($this->onsuspect,[$this,$id])===FALSE) {
//NB: `session_destroy` can't be called at that stage (`session_start` not completed)
$this->destroy($id);
$this->close();
unset($fw->{'COOKIE.'.session_name()});
$fw->error(403);
}
}
return $data['data'];
}
/**
* Write session data
*/
function write(string $id, string $data): bool
{
$fw=Base::instance();
$jar=$fw->JAR;
$this->_cache->set($id.'.@',
[
'data'=>$data,
'ip'=>$this->_ip,
'agent'=>$this->_agent,
'stamp'=>time()
],
$jar['expire']
);
return TRUE;
}
/**
* Destroy session
*/
function destroy(string $id): bool
{
$this->_cache->clear($id.'.@');
return TRUE;
}
/**
* Garbage collector
**/
#[ReturnTypeWillChange]
function gc(int $max_lifetime)
{
$this->_cache->reset('.@',$max_lifetime);
return TRUE;
}
/**
* Return session id (if session has started)
* @return string|NULL
**/
function sid() {
return $this->sid;
}
/**
* Return anti-CSRF token
* @return string
**/
function csrf() {
return $this->_csrf;
}
/**
* Return IP address
* @return string
**/
function ip() {
return $this->_ip;
}
/**
* Return Unix timestamp
* @return string|FALSE
**/
function stamp() {
if (!$this->sid)
session_start();
return $this->_cache->exists($this->sid.'.@',$data)?
$data['stamp']:FALSE;
}
/**
* Return HTTP user agent
* @return string
**/
function agent() {
return $this->_agent;
}
/**
* Instantiate class
* @param $onsuspect callback
* @param $key string
**/
function __construct($onsuspect=NULL,$key=NULL,$cache=null) {
$this->onsuspect=$onsuspect;
$this->_cache=$cache?:Cache::instance();
if (version_compare(PHP_VERSION, '8.4.0')>=0) {
// TODO: remove this when php7 support is dropped
session_set_save_handler(new SessionAdapter($this));
} else {
session_set_save_handler(
[$this,'open'],
[$this,'close'],
[$this,'read'],
[$this,'write'],
[$this,'destroy'],
[$this,'gc']
);
}
register_shutdown_function('session_commit');
$fw=\Base::instance();
$headers=$fw->HEADERS;
$this->_csrf=$fw->hash($fw->SEED.
extension_loaded('openssl')?
implode(unpack('L',openssl_random_pseudo_bytes(4))):
mt_rand()
);
if ($key)
$fw->$key=$this->_csrf;
$this->_agent=isset($headers['User-Agent'])?$headers['User-Agent']:'';
$this->_ip=$fw->IP;
}
/**
* check latest meta data existence
* @param string $key
* @return bool
*/
function exists($key) {
return isset($this->_data[$key]);
}
/**
* get meta data from latest session
* @param string $key
* @return mixed
*/
function &get($key) {
return $this->_data[$key];
}
function set($key,$val) {
trigger_error('Unable to set data on previous session');
}
function clear($key) {
trigger_error('Unable to clear data on previous session');
}
}

View File

@@ -0,0 +1,46 @@
<?php
/**
* To be removed once the legacy session handlers are reworked when php 7 support is dropped
*/
class SessionAdapter implements \SessionHandlerInterface
{
protected $_handler;
public function __construct($handler)
{
$this->_handler = $handler;
}
public function close(): bool
{
return $this->_handler->close();
}
public function destroy(string $id): bool
{
return $this->_handler->destroy($id);
}
#[ReturnTypeWillChange]
public function gc(int $max_lifetime): int
{
return $this->_handler->gc($max_lifetime);
}
public function open(string $path, string $name): bool
{
return $this->_handler->open($path, $name);
}
#[ReturnTypeWillChange]
public function read(string $id): string
{
return $this->_handler->read($id);
}
public function write(string $id, string $data): bool
{
return $this->_handler->write($id, $data);
}
}

View File

@@ -0,0 +1,363 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! SMTP plug-in
class SMTP extends Magic {
//@{ Locale-specific error/exception messages
const
E_Header='%s: header is required',
E_Blank='Message must not be blank',
E_Attach='Attachment %s not found',
E_DIALOG='SMTP dialog error: %s';
//@}
protected
//! Message properties
$headers,
//! E-mail attachments
$attachments,
//! SMTP host
$host,
//! SMTP port
$port,
//! TLS/SSL
$scheme,
//! User ID
$user,
//! Password
$pw,
//! TLS/SSL stream context
$context,
//! TCP/IP socket
$socket,
//! Server-client conversation
$log;
/**
* Fix header
* @return string
* @param $key string
**/
protected function fixheader($key) {
return str_replace(' ','-',
ucwords(preg_replace('/[_\-]/',' ',strtolower($key))));
}
/**
* Return TRUE if header exists
* @return bool
* @param $key
**/
function exists($key) {
$key=$this->fixheader($key);
return isset($this->headers[$key]);
}
/**
* Bind value to e-mail header
* @return string
* @param $key string
* @param $val string
**/
function set($key,$val) {
$key=$this->fixheader($key);
return $this->headers[$key]=$val;
}
/**
* Return value of e-mail header
* @return string|NULL
* @param $key string
**/
function &get($key) {
$key=$this->fixheader($key);
if (isset($this->headers[$key]))
$val=&$this->headers[$key];
else
$val=NULL;
return $val;
}
/**
* Remove header
* @return NULL
* @param $key string
**/
function clear($key) {
$key=$this->fixheader($key);
unset($this->headers[$key]);
}
/**
* Return client-server conversation history
* @return string
**/
function log() {
return str_replace("\n",PHP_EOL,$this->log);
}
/**
* Send SMTP command and record server response
* @return string
* @param $cmd string
* @param $log bool|string
* @param $mock bool
**/
protected function dialog($cmd=NULL,$log=TRUE,$mock=FALSE) {
$reply='';
if ($mock) {
$host=str_replace('ssl://','',$this->host);
switch ($cmd) {
case NULL:
$reply='220 '.$host.' ESMTP ready'."\n";
break;
case 'DATA':
$reply='354 Go ahead'."\n";
break;
case 'QUIT':
$reply='221 '.$host.' closing connection'."\n";
break;
default:
$reply='250 OK'."\n";
break;
}
}
else {
$socket=&$this->socket;
if ($cmd)
fputs($socket,$cmd."\r\n");
while (!feof($socket) && ($info=stream_get_meta_data($socket)) &&
!$info['timed_out'] && $str=fgets($socket,4096)) {
$reply.=$str;
if (preg_match('/(?:^|\n)\d{3} .+?\r\n/s',$reply))
break;
}
}
if ($log) {
if ($cmd)
$this->log.=$cmd."\n";
$this->log.=str_replace("\r",'',$reply);
}
if (preg_match('/^(4|5)\d{2}\s.*$/', $reply))
throw new \Exception(sprintf(self::E_DIALOG,$reply));
return $reply;
}
/**
* Add e-mail attachment
* @return NULL
* @param $file string
* @param $alias string
* @param $cid string
**/
function attach($file,$alias=NULL,$cid=NULL) {
if (!is_file($file))
throw new \Exception(sprintf(self::E_Attach,$file));
if ($alias)
$file=[$alias,$file];
$this->attachments[]=['filename'=>$file,'cid'=>$cid];
}
/**
* Transmit message
* @return bool
* @param $message string
* @param $log bool|string
* @param $mock bool
**/
function send($message,$log=TRUE,$mock=FALSE) {
if ($this->scheme=='ssl' && !extension_loaded('openssl'))
return FALSE;
// Message should not be blank
if (!$message)
throw new \Exception(self::E_Blank);
$fw=Base::instance();
// Retrieve headers
$headers=$this->headers;
// Connect to the server
if (!$mock) {
$socket=&$this->socket;
$socket=@stream_socket_client($this->host.':'.$this->port,
$errno,$errstr,ini_get('default_socket_timeout'),
STREAM_CLIENT_CONNECT,$this->context);
if (!$socket) {
$fw->error(500,$errstr);
return FALSE;
}
stream_set_blocking($socket,TRUE);
}
// Get server's initial response
$this->dialog(NULL,$log,$mock);
// Announce presence
$reply=$this->dialog('EHLO '.$fw->HOST,$log,$mock);
if (strtolower($this->scheme)=='tls') {
$this->dialog('STARTTLS',$log,$mock);
if (!$mock) {
$method=STREAM_CRYPTO_METHOD_TLS_CLIENT;
if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
$method|=STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
$method|=STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
}
stream_socket_enable_crypto($socket,TRUE,$method);
}
$reply=$this->dialog('EHLO '.$fw->HOST,$log,$mock);
}
$message=wordwrap($message,998);
if (preg_match('/8BITMIME/',$reply))
$headers['Content-Transfer-Encoding']='8bit';
else {
$headers['Content-Transfer-Encoding']='quoted-printable';
$message=preg_replace('/^\.(.+)/m',
'..$1',quoted_printable_encode($message));
}
if ($this->user && $this->pw && preg_match('/AUTH/',$reply)) {
// Authenticate
$this->dialog('AUTH LOGIN',$log,$mock);
$this->dialog(base64_encode($this->user),$log,$mock);
$reply=$this->dialog(base64_encode($this->pw),$log,$mock);
if (!preg_match('/^235\s.*/',$reply)) {
$this->dialog('QUIT',$log,$mock);
if (!$mock && $socket)
fclose($socket);
return FALSE;
}
}
if (empty($headers['Message-Id']))
$headers['Message-Id']='<'.uniqid('',TRUE).'@'.$this->host.'>';
if (empty($headers['Date']))
$headers['Date']=date('r');
// Required headers
$reqd=['From','To','Subject'];
foreach ($reqd as $id)
if (empty($headers[$id]))
throw new \Exception(sprintf(self::E_Header,$id));
$eol="\r\n";
// Stringify headers
foreach ($headers as $key=>&$val) {
if (in_array($key,['From','To','Cc','Bcc'])) {
$email='';
preg_match_all('/(?:".+?" |=\?.+?\?= )?(?:<.+?>|[^ ,]+)/',
$val,$matches,PREG_SET_ORDER);
foreach ($matches as $raw)
$email.=($email?', ':'').
(preg_match('/<.+?>/',$raw[0])?
$raw[0]:
('<'.$raw[0].'>'));
$val=$email;
}
unset($val);
}
$from=isset($headers['Sender'])?$headers['Sender']:strstr($headers['From'],'<');
unset($headers['Sender']);
// Start message dialog
$this->dialog('MAIL FROM: '.$from,$log,$mock);
foreach ($fw->split($headers['To'].
(isset($headers['Cc'])?(';'.$headers['Cc']):'').
(isset($headers['Bcc'])?(';'.$headers['Bcc']):'')) as $dst) {
$this->dialog('RCPT TO: '.strstr($dst,'<'),$log,$mock);
}
$this->dialog('DATA',$log,$mock);
if ($this->attachments) {
// Replace Content-Type
$type=$headers['Content-Type'];
unset($headers['Content-Type']);
$enc=$headers['Content-Transfer-Encoding'];
unset($headers['Content-Transfer-Encoding']);
$hash=uniqid('',TRUE);
// Send mail headers
$out='Content-Type: multipart/mixed; boundary="'.$hash.'"'.$eol;
foreach ($headers as $key=>$val)
if ($key!='Bcc')
$out.=$key.': '.$val.$eol;
$out.=$eol;
$out.='This is a multi-part message in MIME format'.$eol;
$out.=$eol;
$out.='--'.$hash.$eol;
$out.='Content-Type: '.$type.$eol;
$out.='Content-Transfer-Encoding: '.$enc.$eol;
$out.=$eol;
$out.=$message.$eol;
foreach ($this->attachments as $attachment) {
if (is_array($attachment['filename']))
list($alias,$file)=$attachment['filename'];
else
$alias=basename($file=$attachment['filename']);
$out.='--'.$hash.$eol;
$out.='Content-Type: application/octet-stream'.$eol;
$out.='Content-Transfer-Encoding: base64'.$eol;
if ($attachment['cid'])
$out.='Content-Id: '.$attachment['cid'].$eol;
$out.='Content-Disposition: attachment; '.
'filename="'.$alias.'"'.$eol;
$out.=$eol;
$out.=chunk_split(base64_encode(
file_get_contents($file))).$eol;
}
$out.=$eol;
$out.='--'.$hash.'--'.$eol;
$out.='.';
$this->dialog($out,preg_match('/verbose/i',$log),$mock);
}
else {
// Send mail headers
$out='';
foreach ($headers as $key=>$val)
if ($key!='Bcc')
$out.=$key.': '.$val.$eol;
$out.=$eol;
$out.=$message.$eol;
$out.='.';
// Send message
$this->dialog($out,preg_match('/verbose/i',$log),$mock);
}
$this->dialog('QUIT',$log,$mock);
if (!$mock && $socket)
fclose($socket);
return TRUE;
}
/**
* Instantiate class
* @param $host string
* @param $port int
* @param $scheme string
* @param $user string
* @param $pw string
* @param $ctx resource
**/
function __construct(
$host='localhost',$port=25,$scheme=NULL,$user=NULL,$pw=NULL,$ctx=NULL) {
$this->headers=[
'MIME-Version'=>'1.0',
'Content-Type'=>'text/plain; '.
'charset='.Base::instance()->ENCODING
];
$this->host=strtolower((($this->scheme=strtolower($scheme?:''))=='ssl'?
'ssl':'tcp').'://'.$host);
$this->port=$port;
$this->user=$user;
$this->pw=$pw;
$this->context=stream_context_create($ctx);
}
}

View File

@@ -0,0 +1,353 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! XML-style template engine
class Template extends Preview {
//@{ Error messages
const
E_Method='Call to undefined method %s()';
//@}
protected
//! Template tags
$tags,
//! Custom tag handlers
$custom=[];
/**
* Template -set- tag handler
* @return string
* @param $node array
**/
protected function _set(array $node) {
$out='';
foreach ($node['@attrib'] as $key=>$val)
$out.='$'.$key.'='.
(preg_match('/\{\{(.+?)\}\}/',$val?:'')?
$this->token($val):
Base::instance()->stringify($val)).'; ';
return '<?php '.$out.'?>';
}
/**
* Template -include- tag handler
* @return string
* @param $node array
**/
protected function _include(array $node) {
$attrib=$node['@attrib'];
$hive=isset($attrib['with']) &&
($attrib['with']=$this->token($attrib['with'])) &&
preg_match_all('/(\w+)\h*=\h*(.+?)(?=,|$)/',
$attrib['with'],$pairs,PREG_SET_ORDER)?
('['.implode(',',
array_map(function($pair) {
return '\''.$pair[1].'\'=>'.
(preg_match('/^\'.*\'$/',$pair[2]) ||
preg_match('/\$/',$pair[2])?
$pair[2]:Base::instance()->stringify(
Base::instance()->cast($pair[2])));
},$pairs)).']+get_defined_vars()'):
'get_defined_vars()';
$ttl=isset($attrib['ttl'])?(int)$attrib['ttl']:0;
return
'<?php '.(isset($attrib['if'])?
('if ('.$this->token($attrib['if']).') '):'').
('echo $this->render('.
(preg_match('/^\{\{(.+?)\}\}$/',$attrib['href'])?
$this->token($attrib['href']):
Base::instance()->stringify($attrib['href'])).','.
'NULL,'.$hive.','.$ttl.'); ?>');
}
/**
* Template -exclude- tag handler
* @return string
**/
protected function _exclude() {
return '';
}
/**
* Template -ignore- tag handler
* @return string
* @param $node array
**/
protected function _ignore(array $node) {
return $node[0];
}
/**
* Template -loop- tag handler
* @return string
* @param $node array
**/
protected function _loop(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
return
'<?php for ('.
$this->token($attrib['from']).';'.
$this->token($attrib['to']).';'.
$this->token($attrib['step']).'): ?>'.
$this->build($node).
'<?php endfor; ?>';
}
/**
* Template -repeat- tag handler
* @return string
* @param $node array
**/
protected function _repeat(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
return
'<?php '.
(isset($attrib['counter'])?
(($ctr=$this->token($attrib['counter'])).'=0; '):'').
'foreach (('.
$this->token($attrib['group']).'?:[]) as '.
(isset($attrib['key'])?
($this->token($attrib['key']).'=>'):'').
$this->token($attrib['value']).'):'.
(isset($ctr)?(' '.$ctr.'++;'):'').' ?>'.
$this->build($node).
'<?php endforeach; ?>';
}
/**
* Template -check- tag handler
* @return string
* @param $node array
**/
protected function _check(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
// Grab <true> and <false> blocks
foreach ($node as $pos=>$block)
if (isset($block['true']))
$true=[$pos,$block];
elseif (isset($block['false']))
$false=[$pos,$block];
if (isset($true,$false) && $true[0]>$false[0])
// Reverse <true> and <false> blocks
list($node[$true[0]],$node[$false[0]])=[$false[1],$true[1]];
return
'<?php if ('.$this->token($attrib['if']).'): ?>'.
$this->build($node).
'<?php endif; ?>';
}
/**
* Template -true- tag handler
* @return string
* @param $node array
**/
protected function _true(array $node) {
return $this->build($node);
}
/**
* Template -false- tag handler
* @return string
* @param $node array
**/
protected function _false(array $node) {
return '<?php else: ?>'.$this->build($node);
}
/**
* Template -switch- tag handler
* @return string
* @param $node array
**/
protected function _switch(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
foreach ($node as $pos=>$block)
if (is_string($block) && !preg_replace('/\s+/','',$block))
unset($node[$pos]);
return
'<?php switch ('.$this->token($attrib['expr']).'): ?>'.
$this->build($node).
'<?php endswitch; ?>';
}
/**
* Template -case- tag handler
* @return string
* @param $node array
**/
protected function _case(array $node) {
$attrib=$node['@attrib'];
unset($node['@attrib']);
return
'<?php case '.(preg_match('/\{\{(.+?)\}\}/',$attrib['value'])?
$this->token($attrib['value']):
Base::instance()->stringify($attrib['value'])).': ?>'.
$this->build($node).
'<?php '.(isset($attrib['break'])?
'if ('.$this->token($attrib['break']).') ':'').
'break; ?>';
}
/**
* Template -default- tag handler
* @return string
* @param $node array
**/
protected function _default(array $node) {
return
'<?php default: ?>'.
$this->build($node).
'<?php break; ?>';
}
/**
* Assemble markup
* @return string
* @param $node array|string
**/
function build($node) {
if (is_string($node))
return parent::build($node);
$out='';
foreach ($node as $key=>$val)
$out.=is_int($key)?$this->build($val):$this->{'_'.$key}($val);
return $out;
}
/**
* Extend template with custom tag
* @return NULL
* @param $tag string
* @param $func callback
**/
function extend($tag,$func) {
$this->tags.='|'.$tag;
$this->custom['_'.$tag]=$func;
}
/**
* Call custom tag handler
* @return string|FALSE
* @param $func string
* @param $args array
**/
function __call($func,array $args) {
if ($func[0]=='_')
return call_user_func_array($this->custom[$func],$args);
if (method_exists($this,$func))
return call_user_func_array([$this,$func],$args);
throw new \Exception(sprintf(self::E_Method,$func));
}
/**
* Parse string for template directives and tokens
* @return array
* @param $text string
**/
function parse($text) {
$text=parent::parse($text);
// Build tree structure
for ($ptr=0,$w=5,$len=strlen($text),$tree=[],$tmp='';$ptr<$len;)
if (preg_match('/^(.{0,'.$w.'}?)<(\/?)(?:F3:)?'.
'('.$this->tags.')\b((?:\s+[\w.:@!\-]+'.
'(?:\h*=\h*(?:"(?:.*?)"|\'(?:.*?)\'))?|'.
'\h*\{\{.+?\}\})*)\s*(\/?)>/is',
substr($text,$ptr),$match)) {
if (strlen($tmp) || isset($match[1]))
$tree[]=$tmp.$match[1];
// Element node
if ($match[2]) {
// Find matching start tag
$stack=[];
for($i=count($tree)-1;$i>=0;--$i) {
$item=$tree[$i];
if (is_array($item) &&
array_key_exists($k=strtolower($match[3]),$item) &&
!isset($item[$k][0])) {
// Start tag found
$tree[$i][$k]+=array_reverse($stack);
$tree=array_slice($tree,0,$i+1);
break;
}
else $stack[]=$item;
}
}
else {
// Start tag
$node=&$tree[][strtolower($match[3])];
$node=[];
if ($match[4]) {
// Process attributes
preg_match_all(
'/(?:(\{\{.+?\}\})|([^\s\/"\'=]+))'.
'\h*(?:=\h*(?:"(.*?)"|\'(.*?)\'))?/s',
$match[4],$attr,PREG_SET_ORDER);
foreach ($attr as $kv)
if (!empty($kv[1]) && !isset($kv[3]) && !isset($kv[4]))
$node['@attrib'][]=$kv[1];
else
$node['@attrib'][$kv[1]?:$kv[2]]=
(isset($kv[3]) && $kv[3]!==''?
$kv[3]:
(isset($kv[4]) && $kv[4]!==''?
$kv[4]:NULL));
}
}
$tmp='';
$ptr+=strlen($match[0]);
$w=5;
}
else {
// Text node
$tmp.=substr($text,$ptr,$w);
$ptr+=$w;
if ($w<50)
++$w;
}
if (strlen($tmp))
// Append trailing text
$tree[]=$tmp;
// Break references
unset($node);
return $tree;
}
/**
* Class constructor
* return object
**/
function __construct() {
$ref=new ReflectionClass(get_called_class());
$this->tags='';
foreach ($ref->getmethods() as $method)
if (preg_match('/^_(?=[[:alpha:]])/',$method->name))
$this->tags.=(strlen($this->tags)?'|':'').
substr($method->name,1);
parent::__construct();
}
}

View File

@@ -0,0 +1,98 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Unit test kit
class Test {
//@{ Reporting level
const
FLAG_False=0,
FLAG_True=1,
FLAG_Both=2;
//@}
protected
//! Test results
$data=[],
//! Success indicator
$passed=TRUE,
//! Reporting level
$level;
/**
* Return test results
* @return array
**/
function results() {
return $this->data;
}
/**
* Return FALSE if at least one test case fails
* @return bool
**/
function passed() {
return $this->passed;
}
/**
* Evaluate condition and save test result
* @return object
* @param $cond bool
* @param $text string
**/
function expect($cond,$text=NULL) {
$out=(bool)$cond;
if ($this->level==$out || $this->level==self::FLAG_Both) {
$data=['status'=>$out,'text'=>$text,'source'=>NULL];
foreach (debug_backtrace() as $frame)
if (isset($frame['file'])) {
$data['source']=Base::instance()->
fixslashes($frame['file']).':'.$frame['line'];
break;
}
$this->data[]=$data;
}
if (!$out && $this->passed)
$this->passed=FALSE;
return $this;
}
/**
* Append message to test results
* @return NULL
* @param $text string
**/
function message($text) {
$this->expect(TRUE,$text);
}
/**
* Class constructor
* @return NULL
* @param $level int
**/
function __construct($level=self::FLAG_Both) {
$this->level=$level;
}
}

View File

@@ -0,0 +1,199 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
//! Unicode string manager
class UTF extends Prefab {
/**
* Get string length
* @return int
* @param $str string
**/
function strlen($str) {
preg_match_all('/./us',$str,$parts);
return count($parts[0]);
}
/**
* Reverse a string
* @return string
* @param $str string
**/
function strrev($str) {
preg_match_all('/./us',$str,$parts);
return implode('',array_reverse($parts[0]));
}
/**
* Find position of first occurrence of a string (case-insensitive)
* @return int|FALSE
* @param $stack string
* @param $needle string
* @param $ofs int
**/
function stripos($stack,$needle,$ofs=0) {
return $this->strpos($stack,$needle,$ofs,TRUE);
}
/**
* Find position of first occurrence of a string
* @return int|FALSE
* @param $stack string
* @param $needle string
* @param $ofs int
* @param $case bool
**/
function strpos($stack,$needle,$ofs=0,$case=FALSE) {
return preg_match('/^(.{'.$ofs.'}.*?)'.
preg_quote($needle,'/').'/us'.($case?'i':''),$stack,$match)?
$this->strlen($match[1]):FALSE;
}
/**
* Returns part of haystack string from the first occurrence of
* needle to the end of haystack (case-insensitive)
* @return string|FALSE
* @param $stack string
* @param $needle string
* @param $before bool
**/
function stristr($stack,$needle,$before=FALSE) {
return $this->strstr($stack,$needle,$before,TRUE);
}
/**
* Returns part of haystack string from the first occurrence of
* needle to the end of haystack
* @return string|FALSE
* @param $stack string
* @param $needle string
* @param $before bool
* @param $case bool
**/
function strstr($stack,$needle,$before=FALSE,$case=FALSE) {
if (!$needle)
return FALSE;
preg_match('/^(.*?)'.preg_quote($needle,'/').'/us'.($case?'i':''),
$stack,$match);
return isset($match[1])?
($before?
$match[1]:
$this->substr($stack,$this->strlen($match[1]))):
FALSE;
}
/**
* Return part of a string
* @return string|FALSE
* @param $str string
* @param $start int
* @param $len int
**/
function substr($str,$start,$len=0) {
if ($start<0)
$start=$this->strlen($str)+$start;
if (!$len)
$len=$this->strlen($str)-$start;
return preg_match('/^.{'.$start.'}(.{0,'.$len.'})/us',$str,$match)?
$match[1]:FALSE;
}
/**
* Count the number of substring occurrences
* @return int
* @param $stack string
* @param $needle string
**/
function substr_count($stack,$needle) {
preg_match_all('/'.preg_quote($needle,'/').'/us',$stack,
$matches,PREG_SET_ORDER);
return count($matches);
}
/**
* Strip whitespaces from the beginning of a string
* @return string
* @param $str string
**/
function ltrim($str) {
return preg_replace('/^[\pZ\pC]+/u','',$str);
}
/**
* Strip whitespaces from the end of a string
* @return string
* @param $str string
**/
function rtrim($str) {
return preg_replace('/[\pZ\pC]+$/u','',$str);
}
/**
* Strip whitespaces from the beginning and end of a string
* @return string
* @param $str string
**/
function trim($str) {
return preg_replace('/^[\pZ\pC]+|[\pZ\pC]+$/u','',$str);
}
/**
* Return UTF-8 byte order mark
* @return string
**/
function bom() {
return chr(0xef).chr(0xbb).chr(0xbf);
}
/**
* Convert code points to Unicode symbols
* @return string
* @param $str string
**/
function translate($str) {
return html_entity_decode(
preg_replace('/\\\\u([[:xdigit:]]+)/i','&#x\1;',$str));
}
/**
* Translate emoji tokens to Unicode font-supported symbols
* @return string
* @param $str string
**/
function emojify($str) {
$map=[
':('=>'\u2639', // frown
':)'=>'\u263a', // smile
'<3'=>'\u2665', // heart
':D'=>'\u1f603', // grin
'XD'=>'\u1f606', // laugh
';)'=>'\u1f609', // wink
':P'=>'\u1f60b', // tongue
':,'=>'\u1f60f', // think
':/'=>'\u1f623', // skeptic
'8O'=>'\u1f632', // oops
]+Base::instance()->EMOJI;
return $this->translate(str_replace(array_keys($map),
array_values($map),$str));
}
}

View File

@@ -0,0 +1,111 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Web;
//! Geo plug-in
class Geo extends \Prefab {
/**
* Return information about specified Unix time zone
* @return array
* @param $zone string
**/
function tzinfo($zone) {
$ref=new \DateTimeZone($zone);
$loc=$ref->getLocation();
$trn=$ref->getTransitions($now=time(),$now);
$out=[
'offset'=>$ref->
getOffset(new \DateTime('now',new \DateTimeZone('UTC')))/3600,
'country'=>$loc['country_code'],
'latitude'=>$loc['latitude'],
'longitude'=>$loc['longitude'],
'dst'=>$trn[0]['isdst']
];
unset($ref);
return $out;
}
/**
* Return geolocation data based on specified/auto-detected IP address
* @return array|FALSE
* @param $ip string
**/
function location($ip=NULL) {
$fw=\Base::instance();
$web=\Web::instance();
if (!$ip)
$ip=$fw->IP;
$public=filter_var($ip,FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4|FILTER_FLAG_IPV6|
FILTER_FLAG_NO_RES_RANGE|FILTER_FLAG_NO_PRIV_RANGE);
if (function_exists('geoip_db_avail') &&
geoip_db_avail(GEOIP_CITY_EDITION_REV1) &&
$out=@geoip_record_by_name($ip)) {
$out['request']=$ip;
$out['region_code']=$out['region'];
$out['region_name']='';
if (!empty($out['country_code']) && !empty($out['region']))
$out['region_name']=geoip_region_name_by_code(
$out['country_code'],$out['region']
);
unset($out['country_code3'],$out['region'],$out['postal_code']);
return $out;
}
if (($req=$web->request('http://www.geoplugin.net/json.gp'.
($public?('?ip='.$ip):''))) &&
$data=json_decode($req['body'],TRUE)) {
$out=[];
foreach ($data as $key=>$val)
if (!strpos($key,'currency') && $key!=='geoplugin_status'
&& $key!=='geoplugin_region')
$out[$fw->snakecase(substr($key, 10))]=$val;
return $out;
}
return FALSE;
}
/**
* Return weather data based on specified latitude/longitude
* @return array|FALSE
* @param $latitude float
* @param $longitude float
* @param $key string
**/
function weather($latitude,$longitude,$key) {
$fw=\Base::instance();
$web=\Web::instance();
$query=[
'lat'=>$latitude,
'lon'=>$longitude,
'APPID'=>$key,
'units'=>'metric'
];
return ($req=$web->request(
'http://api.openweathermap.org/data/2.5/weather?'.
http_build_query($query)))?
json_decode($req['body'],TRUE):
FALSE;
}
}

View File

@@ -0,0 +1,58 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Web\Google;
//! Google ReCAPTCHA v2 plug-in
class Recaptcha {
const
//! API URL
URL_Recaptcha='https://www.google.com/recaptcha/api/siteverify';
/**
* Verify reCAPTCHA response
* @param string $secret
* @param string $response
* @return bool
**/
static function verify($secret,$response=NULL) {
$fw=\Base::instance();
if (!isset($response))
$response=$fw->{'POST.g-recaptcha-response'};
if (!$response)
return FALSE;
$web=\Web::instance();
$out=$web->request(self::URL_Recaptcha,[
'method'=>'POST',
'content'=>http_build_query([
'secret'=>$secret,
'response'=>$response,
'remoteip'=>$fw->IP
]),
]);
return isset($out['body']) &&
($json=json_decode($out['body'],TRUE)) &&
isset($json['success']) && $json['success'];
}
}

View File

@@ -0,0 +1,65 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Web\Google;
//! Google Static Maps API v2 plug-in
class StaticMap {
const
//! API URL
URL_Static='http://maps.googleapis.com/maps/api/staticmap';
protected
//! Query arguments
$query=array();
/**
* Specify API key-value pair via magic call
* @return object
* @param $func string
* @param $args array
**/
function __call($func,array $args) {
$this->query[]=array($func,$args[0]);
return $this;
}
/**
* Generate map
* @return string
**/
function dump() {
$fw=\Base::instance();
$web=\Web::instance();
$out='';
return ($req=$web->request(
self::URL_Static.'?'.array_reduce(
$this->query,
function($out,$item) {
return ($out.=($out?'&':'').
urlencode($item[0]).'='.urlencode($item[1]));
}
))) && $req['body']?$req['body']:FALSE;
}
}

View File

@@ -0,0 +1,163 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Web;
//! Lightweight OAuth2 client
class OAuth2 extends \Magic {
protected
//! Scopes and claims
$args=[],
//! Encoding
$enc_type = PHP_QUERY_RFC1738;
/**
* Return OAuth2 authentication URI
* @return string
* @param $endpoint string
* @param $query bool
**/
function uri($endpoint,$query=TRUE) {
return $endpoint.($query?('?'.
http_build_query($this->args,'','&',$this->enc_type)):'');
}
/**
* Send request to API/token endpoint
* @return string|array|FALSE
* @param $uri string
* @param $method string
* @param $token string
**/
function request($uri,$method,$token=NULL) {
$web=\Web::instance();
$options=[
'method'=>$method,
'content'=>http_build_query($this->args,'','&',$this->enc_type),
'header'=>['Accept: application/json']
];
if ($token)
array_push($options['header'],'Authorization: Bearer '.$token);
elseif ($method=='POST' && isset($this->args['client_id']))
array_push($options['header'],'Authorization: Basic '.
base64_encode(
$this->args['client_id'].':'.
$this->args['client_secret']
)
);
$response=$web->request($uri,$options);
if ($response['error'])
throw new \Exception($response['error']);
if (isset($response['body'])) {
if (preg_grep('/^Content-Type:.*application\/json/i',
$response['headers'])) {
$token=json_decode($response['body'],TRUE);
if (isset($token['error_description']))
throw new \Exception($token['error_description']);
if (isset($token['error']))
throw new \Exception($token['error']);
return $token;
}
else
return $response['body'];
}
return FALSE;
}
/**
* Parse JSON Web token
* @return array
* @param $token string
**/
function jwt($token) {
return json_decode(
base64_decode(
str_replace(['-','_'],['+','/'],explode('.',$token)[1])
),
TRUE
);
}
/**
* change default url encoding type, i.E. PHP_QUERY_RFC3986
* @param $type
*/
function setEncoding($type) {
$this->enc_type = $type;
}
/**
* URL-safe base64 encoding
* @return array
* @param $data string
**/
function b64url($data) {
return trim(strtr(base64_encode($data),'+/','-_'),'=');
}
/**
* Return TRUE if scope/claim exists
* @return bool
* @param $key string
**/
function exists($key) {
return isset($this->args[$key]);
}
/**
* Bind value to scope/claim
* @return string
* @param $key string
* @param $val string
**/
function set($key,$val) {
return $this->args[$key]=$val;
}
/**
* Return value of scope/claim
* @return mixed
* @param $key string
**/
function &get($key) {
if (isset($this->args[$key]))
$val=&$this->args[$key];
else
$val=NULL;
return $val;
}
/**
* Remove scope/claim
* @return NULL
* @param $key string
**/
function clear($key=NULL) {
if ($key)
unset($this->args[$key]);
else
$this->args=[];
}
}

View File

@@ -0,0 +1,248 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Web;
//! OpenID consumer
class OpenID extends \Magic {
protected
//! OpenID provider endpoint URL
$url,
//! HTTP request parameters
$args=[];
/**
* Determine OpenID provider
* @return string|FALSE
* @param $proxy string
**/
protected function discover($proxy) {
// Normalize
if (!preg_match('/https?:\/\//i',$this->args['endpoint']))
$this->args['endpoint']='http://'.$this->args['endpoint'];
$url=parse_url($this->args['endpoint']);
// Remove fragment; reconnect parts
$this->args['endpoint']=$url['scheme'].'://'.
(isset($url['user'])?
($url['user'].
(isset($url['pass'])?(':'.$url['pass']):'').'@'):'').
strtolower($url['host']).(isset($url['path'])?$url['path']:'/').
(isset($url['query'])?('?'.$url['query']):'');
// HTML-based discovery of OpenID provider
$req=\Web::instance()->
request($this->args['endpoint'],['proxy'=>$proxy]);
if (!$req)
return FALSE;
$type=array_values(preg_grep('/Content-Type:/',$req['headers']));
if ($type &&
preg_match('/application\/xrds\+xml|text\/xml/',$type[0]) &&
($sxml=simplexml_load_string($req['body'])) &&
($xrds=json_decode(json_encode($sxml),TRUE)) &&
isset($xrds['XRD'])) {
// XRDS document
$svc=$xrds['XRD']['Service'];
if (isset($svc[0]))
$svc=$svc[0];
$svc_type=is_array($svc['Type'])?$svc['Type']:array($svc['Type']);
if (preg_grep('/http:\/\/specs\.openid\.net\/auth\/2.0\/'.
'(?:server|signon)/',$svc_type)) {
$this->args['provider']=$svc['URI'];
if (isset($svc['LocalID']))
$this->args['localidentity']=$svc['LocalID'];
elseif (isset($svc['CanonicalID']))
$this->args['localidentity']=$svc['CanonicalID'];
}
$this->args['server']=$svc['URI'];
if (isset($svc['Delegate']))
$this->args['delegate']=$svc['Delegate'];
}
else {
$len=strlen($req['body']);
$ptr=0;
// Parse document
while ($ptr<$len)
if (preg_match(
'/^<link\b((?:\h+\w+\h*=\h*'.
'(?:"(?:.+?)"|\'(?:.+?)\'))*)\h*\/?>/is',
substr($req['body'],$ptr),$parts)) {
if ($parts[1] &&
// Process attributes
preg_match_all('/\b(rel|href)\h*=\h*'.
'(?:"(.+?)"|\'(.+?)\')/s',$parts[1],$attr,
PREG_SET_ORDER)) {
$node=[];
foreach ($attr as $kv)
$node[$kv[1]]=isset($kv[2])?$kv[2]:$kv[3];
if (isset($node['rel']) &&
preg_match('/openid2?\.(\w+)/',
$node['rel'],$var) &&
isset($node['href']))
$this->args[$var[1]]=$node['href'];
}
$ptr+=strlen($parts[0]);
}
else
++$ptr;
}
// Get OpenID provider's endpoint URL
if (isset($this->args['provider'])) {
// OpenID 2.0
$this->args['ns']='http://specs.openid.net/auth/2.0';
if (isset($this->args['localidentity']))
$this->args['identity']=$this->args['localidentity'];
if (isset($this->args['trust_root']))
$this->args['realm']=$this->args['trust_root'];
}
elseif (isset($this->args['server'])) {
// OpenID 1.1
$this->args['ns']='http://openid.net/signon/1.1';
if (isset($this->args['delegate']))
$this->args['identity']=$this->args['delegate'];
}
if (isset($this->args['provider'])) {
// OpenID 2.0
if (empty($this->args['claimed_id']))
$this->args['claimed_id']=$this->args['identity'];
return $this->args['provider'];
}
elseif (isset($this->args['server']))
// OpenID 1.1
return $this->args['server'];
else
return FALSE;
}
/**
* Initiate OpenID authentication sequence; Return FALSE on failure
* or redirect to OpenID provider URL
* @return bool
* @param $proxy string
* @param $attr array
* @param $reqd string|array
**/
function auth($proxy=NULL,$attr=[],?array $reqd=NULL) {
$fw=\Base::instance();
$root=$fw->SCHEME.'://'.$fw->HOST;
if (empty($this->args['trust_root']))
$this->args['trust_root']=$root.$fw->BASE.'/';
if (empty($this->args['return_to']))
$this->args['return_to']=$root.$_SERVER['REQUEST_URI'];
$this->args['mode']='checkid_setup';
if ($this->url=$this->discover($proxy)) {
if ($attr) {
$this->args['ns.ax']='http://openid.net/srv/ax/1.0';
$this->args['ax.mode']='fetch_request';
foreach ($attr as $key=>$val)
$this->args['ax.type.'.$key]=$val;
$this->args['ax.required']=is_string($reqd)?
$reqd:implode(',',$reqd);
}
$var=[];
foreach ($this->args as $key=>$val)
$var['openid.'.$key]=$val;
$fw->reroute($this->url.'?'.http_build_query($var));
}
return FALSE;
}
/**
* Return TRUE if OpenID verification was successful
* @return bool
* @param $proxy string
**/
function verified($proxy=NULL) {
preg_match_all('/(?<=^|&)openid\.([^=]+)=([^&]+)/',
$_SERVER['QUERY_STRING'],$matches,PREG_SET_ORDER);
foreach ($matches as $match)
$this->args[$match[1]]=urldecode($match[2]);
if (isset($this->args['mode']) &&
$this->args['mode']!='error' &&
$this->url=$this->discover($proxy)) {
$this->args['mode']='check_authentication';
$var=[];
foreach ($this->args as $key=>$val)
$var['openid.'.$key]=$val;
$req=\Web::instance()->request(
$this->url,
[
'method'=>'POST',
'content'=>http_build_query($var),
'proxy'=>$proxy
]
);
return (bool)preg_match('/is_valid:true/i',$req['body']);
}
return FALSE;
}
/**
* Return OpenID response fields
* @return array
**/
function response() {
return $this->args;
}
/**
* Return TRUE if OpenID request parameter exists
* @return bool
* @param $key string
**/
function exists($key) {
return isset($this->args[$key]);
}
/**
* Bind value to OpenID request parameter
* @return string
* @param $key string
* @param $val string
**/
function set($key,$val) {
return $this->args[$key]=$val;
}
/**
* Return value of OpenID request parameter
* @return mixed
* @param $key string
**/
function &get($key) {
if (isset($this->args[$key]))
$val=&$this->args[$key];
else
$val=NULL;
return $val;
}
/**
* Remove OpenID request parameter
* @return NULL
* @param $key
**/
function clear($key) {
unset($this->args[$key]);
}
}

View File

@@ -0,0 +1,176 @@
<?php
/*
Copyright (c) 2009-2019 F3::Factory/Bong Cosca, All rights reserved.
This file is part of the Fat-Free Framework (http://fatfreeframework.com).
This 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 later.
Fat-Free Framework 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 Fat-Free Framework. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Web;
//! Pingback 1.0 protocol (client and server) implementation
class Pingback extends \Prefab {
protected
//! Transaction history
$log;
/**
* Return TRUE if URL points to a pingback-enabled resource
* @return bool
* @param $url
**/
protected function enabled($url) {
$web=\Web::instance();
$req=$web->request($url);
$found=FALSE;
if ($req['body']) {
// Look for pingback header
foreach ($req['headers'] as $header)
if (preg_match('/^X-Pingback:\h*(.+)/',$header,$href)) {
$found=$href[1];
break;
}
if (!$found &&
// Scan page for pingback link tag
preg_match('/<link\h+(.+?)\h*\/?>/i',$req['body'],$parts) &&
preg_match('/rel\h*=\h*"pingback"/i',$parts[1]) &&
preg_match('/href\h*=\h*"\h*(.+?)\h*"/i',$parts[1],$href))
$found=$href[1];
}
return $found;
}
/**
* Load local page contents, parse HTML anchor tags, find permalinks,
* and send XML-RPC calls to corresponding pingback servers
* @return NULL
* @param $source string
**/
function inspect($source) {
$fw=\Base::instance();
$web=\Web::instance();
$parts=parse_url($source);
if (empty($parts['scheme']) || empty($parts['host']) ||
$parts['host']==$fw->HOST) {
$req=$web->request($source);
$doc=new \DOMDocument('1.0',$fw->ENCODING);
$doc->strictErrorChecking=FALSE;
$doc->recover=TRUE;
if (@$doc->loadhtml($req['body'])) {
// Parse anchor tags
$links=$doc->getelementsbytagname('a');
foreach ($links as $link) {
$permalink=$link->getattribute('href');
// Find pingback-enabled resources
if ($permalink && $found=$this->enabled($permalink)) {
$req=$web->request($found,
[
'method'=>'POST',
'header'=>'Content-Type: application/xml',
'content'=>xmlrpc_encode_request(
'pingback.ping',
[$source,$permalink],
['encoding'=>$fw->ENCODING]
)
]
);
if ($req['body'])
$this->log.=date('r').' '.
$permalink.' [permalink:'.$found.']'.PHP_EOL.
$req['body'].PHP_EOL;
}
}
}
unset($doc);
}
}
/**
* Receive ping, check if local page is pingback-enabled, verify
* source contents, and return XML-RPC response
* @return string
* @param $func callback
* @param $path string
**/
function listen($func,$path=NULL) {
$fw=\Base::instance();
if (PHP_SAPI!='cli') {
header('X-Powered-By: '.$fw->PACKAGE);
header('Content-Type: application/xml; '.
'charset='.$charset=$fw->ENCODING);
}
if (!$path)
$path=$fw->BASE;
$web=\Web::instance();
$args=xmlrpc_decode_request($fw->BODY,$method,$charset);
$options=['encoding'=>$charset];
if ($method=='pingback.ping' && isset($args[0],$args[1])) {
list($source,$permalink)=$args;
$doc=new \DOMDocument('1.0',$fw->ENCODING);
// Check local page if pingback-enabled
$parts=parse_url($permalink);
if ((empty($parts['scheme']) ||
$parts['host']==$fw->HOST) &&
preg_match('/^'.preg_quote($path,'/').'/'.
($fw->CASELESS?'i':''),$parts['path']) &&
$this->enabled($permalink)) {
// Check source
$parts=parse_url($source);
if ((empty($parts['scheme']) ||
$parts['host']==$fw->HOST) &&
($req=$web->request($source)) &&
$doc->loadhtml($req['body'])) {
$links=$doc->getelementsbytagname('a');
foreach ($links as $link) {
if ($link->getattribute('href')==$permalink) {
call_user_func_array($func,[$source,$req['body']]);
// Success
die(xmlrpc_encode_request(NULL,$source,$options));
}
}
// No link to local page
die(xmlrpc_encode_request(NULL,0x11,$options));
}
// Source failure
die(xmlrpc_encode_request(NULL,0x10,$options));
}
// Doesn't exist (or not pingback-enabled)
die(xmlrpc_encode_request(NULL,0x21,$options));
}
// Access denied
die(xmlrpc_encode_request(NULL,0x31,$options));
}
/**
* Return transaction history
* @return string
**/
function log() {
return $this->log;
}
/**
* Instantiate class
* @return object
**/
function __construct() {
// Suppress errors caused by invalid HTML structures
libxml_use_internal_errors(TRUE);
}
}

View File

@@ -0,0 +1,3 @@
<?php
//

View File

@@ -0,0 +1,51 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Cache;
interface CacheInterface
{
/**
* @param string $id
*
* @return mixed
*/
public function fetch(string $id);
/**
* @param string $id
*
* @return bool
*/
public function contains(string $id): bool;
/**
* @param string $id
* @param mixed $data
* @param int $lifeTime
*
* @return bool
*/
public function save(string $id, $data, int $lifeTime = 0): bool;
/**
* @param string $id
*
* @return bool
*/
public function delete(string $id): bool;
/**
* @return bool
*/
public function flushAll(): bool;
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Cache;
use Doctrine\Common\Cache\CacheProvider;
class DoctrineBridge implements CacheInterface
{
/**
* @var CacheProvider
*/
private $cache;
/**
* @param CacheProvider $cache
*/
public function __construct(CacheProvider $cache)
{
$this->cache = $cache;
}
/**
* @inheritDoc
*/
public function fetch(string $id)
{
return $this->cache->fetch($id);
}
/**
* @inheritDoc
*/
public function contains(string $id): bool
{
return $this->cache->contains($id);
}
/**
* @inheritDoc
*/
public function save(string $id, $data, int $lifeTime = 0): bool
{
return $this->cache->save($id, $data, $lifeTime);
}
/**
* @inheritDoc
*/
public function delete(string $id): bool
{
return $this->cache->delete($id);
}
/**
* @inheritDoc
*/
public function flushAll(): bool
{
return $this->cache->flushAll();
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Cache;
use Illuminate\Support\Facades\Cache;
class LaravelCache implements CacheInterface
{
/**
* @inheritDoc
*/
public function fetch(string $id)
{
return Cache::get($id);
}
/**
* @inheritDoc
*/
public function contains(string $id): bool
{
return Cache::has($id);
}
/**
* @inheritDoc
*/
public function save(string $id, $data, int $lifeTime = 0): bool
{
return Cache::put($id, $data, \func_num_args() < 3 ? null : $lifeTime);
}
/**
* @inheritDoc
*/
public function delete(string $id): bool
{
return Cache::forget($id);
}
/**
* @inheritDoc
*/
public function flushAll(): bool
{
return Cache::flush();
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Cache;
use Psr\SimpleCache\CacheInterface as PsrCacheInterface;
class PSR16Bridge implements CacheInterface
{
/**
* @var PsrCacheInterface
*/
private $cache;
/**
* PSR16Bridge constructor.
* @param PsrCacheInterface $cache
*/
public function __construct(PsrCacheInterface $cache)
{
$this->cache = $cache;
}
/**
* @inheritDoc
*/
public function fetch(string $id)
{
return $this->cache->get($id, false);
}
/**
* @inheritDoc
*/
public function contains(string $id): bool
{
return $this->cache->has($id);
}
/**
* @inheritDoc
*/
public function save(string $id, $data, int $lifeTime = 0): bool
{
return $this->cache->set($id, $data, \func_num_args() < 3 ? null : $lifeTime);
}
/**
* @inheritDoc
*/
public function delete(string $id): bool
{
return $this->cache->delete($id);
}
/**
* @inheritDoc
*/
public function flushAll(): bool
{
return $this->cache->clear();
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Cache;
use Psr\Cache\CacheItemPoolInterface;
class PSR6Bridge implements CacheInterface
{
/**
* @var CacheItemPoolInterface
*/
private $pool;
/**
* PSR6Bridge constructor.
* @param CacheItemPoolInterface $pool
*/
public function __construct(CacheItemPoolInterface $pool)
{
$this->pool = $pool;
}
/**
* @inheritDoc
*/
public function fetch(string $id)
{
$item = $this->pool->getItem($id);
return $item->isHit() ? $item->get() : false;
}
/**
* @inheritDoc
*/
public function contains(string $id): bool
{
return $this->pool->hasItem($id);
}
/**
* @inheritDoc
*/
public function save(string $id, $data, int $lifeTime = 0): bool
{
$item = $this->pool->getItem($id);
$item->set($data);
if (\func_num_args() > 2) {
$item->expiresAfter($lifeTime);
}
return $this->pool->save($item);
}
/**
* @inheritDoc
*/
public function delete(string $id): bool
{
return $this->pool->deleteItem($id);
}
/**
* @inheritDoc
*/
public function flushAll(): bool
{
return $this->pool->clear();
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Cache;
/**
* Class StaticCache
*
* Simple Cache that caches in a static property
* (Speeds up multiple detections in one request)
*/
class StaticCache implements CacheInterface
{
/**
* Holds the static cache data
* @var array
*/
protected static $staticCache = [];
/**
* @inheritdoc
*/
public function fetch(string $id)
{
return $this->contains($id) ? self::$staticCache[$id] : false;
}
/**
* @inheritdoc
*/
public function contains(string $id): bool
{
return isset(self::$staticCache[$id]) || \array_key_exists($id, self::$staticCache);
}
/**
* @inheritdoc
*/
public function save(string $id, $data, int $lifeTime = 0): bool
{
self::$staticCache[$id] = $data;
return true;
}
/**
* @inheritdoc
*/
public function delete(string $id): bool
{
unset(self::$staticCache[$id]);
return true;
}
/**
* @inheritdoc
*/
public function flushAll(): bool
{
self::$staticCache = [];
return true;
}
}

View File

@@ -0,0 +1,373 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector;
class ClientHints
{
/**
* Represents `Sec-CH-UA-Arch` header field: The underlying architecture's instruction set
*
* @var string
*/
protected $architecture = '';
/**
* Represents `Sec-CH-UA-Bitness` header field: The underlying architecture's bitness
*
* @var string
*/
protected $bitness = '';
/**
* Represents `Sec-CH-UA-Mobile` header field: whether the user agent should receive a specifically "mobile" UX
*
* @var bool
*/
protected $mobile = false;
/**
* Represents `Sec-CH-UA-Model` header field: the user agent's underlying device model
*
* @var string
*/
protected $model = '';
/**
* Represents `Sec-CH-UA-Platform` header field: the platform's brand
*
* @var string
*/
protected $platform = '';
/**
* Represents `Sec-CH-UA-Platform-Version` header field: the platform's major version
*
* @var string
*/
protected $platformVersion = '';
/**
* Represents `Sec-CH-UA-Full-Version` header field: the platform's major version
*
* @var string
*/
protected $uaFullVersion = '';
/**
* Represents `Sec-CH-UA-Full-Version-List` header field: the full version for each brand in its brand list
*
* @var array
*/
protected $fullVersionList = [];
/**
* Represents `x-requested-with` header field: Android app id
* @var string
*/
protected $app = '';
/**
* Represents `Sec-CH-UA-Form-Factors` header field: form factor device type name
*
* @var array
*/
protected $formFactors = [];
/**
* Constructor
*
* @param string $model `Sec-CH-UA-Model` header field
* @param string $platform `Sec-CH-UA-Platform` header field
* @param string $platformVersion `Sec-CH-UA-Platform-Version` header field
* @param string $uaFullVersion `Sec-CH-UA-Full-Version` header field
* @param array $fullVersionList `Sec-CH-UA-Full-Version-List` header field
* @param bool $mobile `Sec-CH-UA-Mobile` header field
* @param string $architecture `Sec-CH-UA-Arch` header field
* @param string $bitness `Sec-CH-UA-Bitness`
* @param string $app `HTTP_X-REQUESTED-WITH`
* @param array $formFactors `Sec-CH-UA-Form-Factors` header field
*/
public function __construct(string $model = '', string $platform = '', string $platformVersion = '', string $uaFullVersion = '', array $fullVersionList = [], bool $mobile = false, string $architecture = '', string $bitness = '', string $app = '', array $formFactors = []) // phpcs:ignore Generic.Files.LineLength
{
$this->model = $model;
$this->platform = $platform;
$this->platformVersion = $platformVersion;
$this->uaFullVersion = $uaFullVersion;
$this->fullVersionList = $fullVersionList;
$this->mobile = $mobile;
$this->architecture = $architecture;
$this->bitness = $bitness;
$this->app = $app;
$this->formFactors = $formFactors;
}
/**
* Magic method to directly allow accessing the protected properties
*
* @param string $variable
*
* @return mixed
*
* @throws \Exception
*/
public function __get(string $variable)
{
if (\property_exists($this, $variable)) {
return $this->$variable;
}
throw new \Exception('Invalid ClientHint property requested.');
}
/**
* Returns if the client hints
*
* @return bool
*/
public function isMobile(): bool
{
return $this->mobile;
}
/**
* Returns the Architecture
*
* @return string
*/
public function getArchitecture(): string
{
return $this->architecture;
}
/**
* Returns the Bitness
*
* @return string
*/
public function getBitness(): string
{
return $this->bitness;
}
/**
* Returns the device model
*
* @return string
*/
public function getModel(): string
{
return $this->model;
}
/**
* Returns the Operating System
*
* @return string
*/
public function getOperatingSystem(): string
{
return $this->platform;
}
/**
* Returns the Operating System version
*
* @return string
*/
public function getOperatingSystemVersion(): string
{
return $this->platformVersion;
}
/**
* Returns the Browser name
*
* @return array<string, string>
*/
public function getBrandList(): array
{
if (\is_array($this->fullVersionList) && \count($this->fullVersionList)) {
$brands = \array_column($this->fullVersionList, 'brand');
$versions = \array_column($this->fullVersionList, 'version');
if (\count($brands) === \count($versions)) {
// @phpstan-ignore-next-line
return \array_combine($brands, $versions);
}
}
return [];
}
/**
* Returns the Browser version
*
* @return string
*/
public function getBrandVersion(): string
{
if (!empty($this->uaFullVersion)) {
return $this->uaFullVersion;
}
return '';
}
/**
* Returns the Android app id
*
* @return string
*/
public function getApp(): string
{
return $this->app;
}
/**
* Returns the formFactor device type name
*
* @return array
*/
public function getFormFactors(): array
{
return $this->formFactors;
}
/**
* Factory method to easily instantiate this class using an array containing all available (client hint) headers
*
* @param array $headers
*
* @return ClientHints
*/
public static function factory(array $headers): ClientHints
{
$model = $platform = $platformVersion = $uaFullVersion = $architecture = $bitness = '';
$app = '';
$mobile = false;
$fullVersionList = [];
$formFactors = [];
foreach ($headers as $name => $value) {
if (empty($value)) {
continue;
}
switch (\str_replace('_', '-', \strtolower((string) $name))) {
case 'http-sec-ch-ua-arch':
case 'sec-ch-ua-arch':
case 'arch':
case 'architecture':
$architecture = \trim($value, '"');
break;
case 'http-sec-ch-ua-bitness':
case 'sec-ch-ua-bitness':
case 'bitness':
$bitness = \trim($value, '"');
break;
case 'http-sec-ch-ua-mobile':
case 'sec-ch-ua-mobile':
case 'mobile':
$mobile = true === $value || '1' === $value || '?1' === $value;
break;
case 'http-sec-ch-ua-model':
case 'sec-ch-ua-model':
case 'model':
$model = \trim($value, '"');
break;
case 'http-sec-ch-ua-full-version':
case 'sec-ch-ua-full-version':
case 'uafullversion':
$uaFullVersion = \trim($value, '"');
break;
case 'http-sec-ch-ua-platform':
case 'sec-ch-ua-platform':
case 'platform':
$platform = \trim($value, '"');
break;
case 'http-sec-ch-ua-platform-version':
case 'sec-ch-ua-platform-version':
case 'platformversion':
$platformVersion = \trim($value, '"');
break;
case 'brands':
if (!empty($fullVersionList)) {
break;
}
// use this only if no other header already set the list
case 'fullversionlist':
$fullVersionList = \is_array($value) ? $value : $fullVersionList;
break;
case 'http-sec-ch-ua':
case 'sec-ch-ua':
if (!empty($fullVersionList)) {
break;
}
// use this only if no other header already set the list
case 'http-sec-ch-ua-full-version-list':
case 'sec-ch-ua-full-version-list':
$reg = '/^"([^"]+)"; ?v="([^"]+)"(?:, )?/';
$list = [];
while (\preg_match($reg, $value, $matches)) {
$list[] = ['brand' => $matches[1], 'version' => $matches[2]];
$value = \substr($value, \strlen($matches[0]));
}
if (\count($list)) {
$fullVersionList = $list;
}
break;
case 'http-x-requested-with':
case 'x-requested-with':
if ('xmlhttprequest' !== \strtolower($value)) {
$app = $value;
}
break;
case 'formfactors':
case 'http-sec-ch-ua-form-factors':
case 'sec-ch-ua-form-factors':
if (\is_array($value)) {
$formFactors = \array_map('\strtolower', $value);
} elseif (\preg_match_all('~"([a-z]+)"~i', \strtolower($value), $matches)) {
$formFactors = $matches[1];
}
break;
}
}
return new self(
$model,
$platform,
$platformVersion,
$uaFullVersion,
$fullVersionList,
$mobile,
$architecture,
$bitness,
$app,
$formFactors
);
}
}

View File

@@ -0,0 +1,165 @@
GNU LESSER 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.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser 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
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

View File

@@ -0,0 +1,26 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser;
/**
* Class AbstractBotParser
*
* Abstract class for all bot parsers
*/
abstract class AbstractBotParser extends AbstractParser
{
/**
* Enables information discarding
*/
abstract public function discardDetails(): void;
}

View File

@@ -0,0 +1,494 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser;
use DeviceDetector\Cache\CacheInterface;
use DeviceDetector\Cache\StaticCache;
use DeviceDetector\ClientHints;
use DeviceDetector\DeviceDetector;
use DeviceDetector\Yaml\ParserInterface as YamlParser;
use DeviceDetector\Yaml\Spyc;
/**
* Class AbstractParser
*/
abstract class AbstractParser
{
/**
* Holds the path to the yml file containing regexes
* @var string
*/
protected $fixtureFile;
/**
* Holds the internal name of the parser
* Used for caching
* @var string
*/
protected $parserName;
/**
* Holds the user agent to be parsed
* @var string
*/
protected $userAgent;
/**
* Holds the client hints to be parsed
* @var ?ClientHints
*/
protected $clientHints = null;
/**
* Contains a list of mappings from names we use to known client hint values
* @var array<string, array<string>>
*/
protected static $clientHintMapping = [];
/**
* Holds an array with method that should be available global
* @var array
*/
protected $globalMethods;
/**
* Holds an array with regexes to parse, if already loaded
* @var array
*/
protected $regexList;
/**
* Holds the concatenated regex for all items in regex list
* @var string
*/
protected $overAllMatch;
/**
* Indicates how deep versioning will be detected
* if $maxMinorParts is 0 only the major version will be returned
* @var int
*/
protected static $maxMinorParts = 1;
/**
* Versioning constant used to set max versioning to major version only
* Version examples are: 3, 5, 6, 200, 123, ...
*/
public const VERSION_TRUNCATION_MAJOR = 0;
/**
* Versioning constant used to set max versioning to minor version
* Version examples are: 3.4, 5.6, 6.234, 0.200, 1.23, ...
*/
public const VERSION_TRUNCATION_MINOR = 1;
/**
* Versioning constant used to set max versioning to path level
* Version examples are: 3.4.0, 5.6.344, 6.234.2, 0.200.3, 1.2.3, ...
*/
public const VERSION_TRUNCATION_PATCH = 2;
/**
* Versioning constant used to set versioning to build number
* Version examples are: 3.4.0.12, 5.6.334.0, 6.234.2.3, 0.200.3.1, 1.2.3.0, ...
*/
public const VERSION_TRUNCATION_BUILD = 3;
/**
* Versioning constant used to set versioning to unlimited (no truncation)
*/
public const VERSION_TRUNCATION_NONE = -1;
/**
* @var CacheInterface|null
*/
protected $cache = null;
/**
* @var YamlParser|null
*/
protected $yamlParser = null;
/**
* parses the currently set useragents and returns possible results
*
* @return array|null
*/
abstract public function parse(): ?array;
/**
* AbstractParser constructor.
*
* @param string $ua
* @param ?ClientHints $clientHints
*/
public function __construct(string $ua = '', ?ClientHints $clientHints = null)
{
$this->setUserAgent($ua);
$this->setClientHints($clientHints);
}
/**
* @inheritdoc
*/
public function restoreUserAgentFromClientHints(): void
{
if (null === $this->clientHints) {
return;
}
$deviceModel = $this->clientHints->getModel();
if ('' === $deviceModel) {
return;
}
// Restore Android User Agent
if ($this->hasUserAgentClientHintsFragment()) {
$osVersion = $this->clientHints->getOperatingSystemVersion();
$this->setUserAgent((string) \preg_replace(
'(Android (?:10[.\d]*; K|1[1-5]))',
\sprintf('Android %s; %s', '' !== $osVersion ? $osVersion : '10', $deviceModel),
$this->userAgent
));
}
// Restore Desktop User Agent
if (!$this->hasDesktopFragment()) {
return;
}
$this->setUserAgent((string) \preg_replace(
'(X11; Linux x86_64)',
\sprintf('X11; Linux x86_64; %s', $deviceModel),
$this->userAgent
));
}
/**
* Set how DeviceDetector should return versions
* @param int $type Any of the VERSION_TRUNCATION_* constants
*/
public static function setVersionTruncation(int $type): void
{
if (!\in_array($type, [
self::VERSION_TRUNCATION_BUILD,
self::VERSION_TRUNCATION_NONE,
self::VERSION_TRUNCATION_MAJOR,
self::VERSION_TRUNCATION_MINOR,
self::VERSION_TRUNCATION_PATCH,
])
) {
return;
}
static::$maxMinorParts = $type;
}
/**
* Sets the user agent to parse
*
* @param string $ua user agent
*/
public function setUserAgent(string $ua): void
{
$this->userAgent = $ua;
}
/**
* Sets the client hints to parse
*
* @param ?ClientHints $clientHints client hints
*/
public function setClientHints(?ClientHints $clientHints): void
{
$this->clientHints = $clientHints;
}
/**
* Returns the internal name of the parser
*
* @return string
*/
public function getName(): string
{
return $this->parserName;
}
/**
* Sets the Cache class
*
* @param CacheInterface $cache
*/
public function setCache(CacheInterface $cache): void
{
$this->cache = $cache;
}
/**
* Returns Cache object
*
* @return CacheInterface
*/
public function getCache(): CacheInterface
{
if (!empty($this->cache)) {
return $this->cache;
}
return new StaticCache();
}
/**
* Sets the YamlParser class
*
* @param YamlParser $yamlParser
*/
public function setYamlParser(YamlParser $yamlParser): void
{
$this->yamlParser = $yamlParser;
}
/**
* Returns YamlParser object
*
* @return YamlParser
*/
public function getYamlParser(): YamlParser
{
if (!empty($this->yamlParser)) {
return $this->yamlParser;
}
return new Spyc();
}
/**
* Returns the result of the parsed yml file defined in $fixtureFile
*
* @return array
*/
protected function getRegexes(): array
{
if (empty($this->regexList)) {
$cacheKey = 'DeviceDetector-' . DeviceDetector::VERSION . 'regexes-' . $this->getName();
$cacheKey = (string) \preg_replace('/([^a-z0-9_-]+)/i', '', $cacheKey);
$cacheContent = $this->getCache()->fetch($cacheKey);
if (\is_array($cacheContent)) {
$this->regexList = $cacheContent;
}
if (empty($this->regexList)) {
$parsedContent = $this->getYamlParser()->parseFile(
$this->getRegexesDirectory() . DIRECTORY_SEPARATOR . $this->fixtureFile
);
if (!\is_array($parsedContent)) {
$parsedContent = [];
}
$this->regexList = $parsedContent;
$this->getCache()->save($cacheKey, $this->regexList);
}
}
return $this->regexList;
}
/**
* Returns the provided name after applying client hint mappings.
* This is used to map names provided in client hints to the names we use.
*
* @param string $name
*
* @return string
*/
protected function applyClientHintMapping(string $name): string
{
foreach (static::$clientHintMapping as $mappedName => $clientHints) {
foreach ($clientHints as $clientHint) {
if (\strtolower($name) === \strtolower($clientHint)) {
return $mappedName;
}
}
}
return $name;
}
/**
* @return string
*/
protected function getRegexesDirectory(): string
{
return \dirname(__DIR__);
}
/**
* Returns if the parsed UA contains the 'Windows NT;' or 'X11; Linux x86_64' fragments
*
* @return bool
*/
protected function hasDesktopFragment(): bool
{
$regexExcludeDesktopFragment = \implode('|', [
'CE-HTML',
' Mozilla/|Andr[o0]id|Tablet|Mobile|iPhone|Windows Phone|ricoh|OculusBrowser',
'PicoBrowser|Lenovo|compatible; MSIE|Trident/|Tesla/|XBOX|FBMD/|ARM; ?([^)]+)',
]);
return
$this->matchUserAgent('(?:Windows (?:NT|IoT)|X11; Linux x86_64)') &&
!$this->matchUserAgent($regexExcludeDesktopFragment);
}
/**
* Returns if the parsed UA contains the 'Android 10 K;' or Android 10 K Build/` fragment
*
* @return bool
*/
protected function hasUserAgentClientHintsFragment(): bool
{
return (bool) \preg_match('~Android (?:10[.\d]*; K(?: Build/|[;)])|1[1-5]\)) AppleWebKit~i', $this->userAgent);
}
/**
* Matches the useragent against the given regex
*
* @param string $regex
*
* @return ?array
*
* @throws \Exception
*/
protected function matchUserAgent(string $regex): ?array
{
$matches = [];
// only match if useragent begins with given regex or there is no letter before it
$regex = '/(?:^|[^A-Z0-9_-]|[^A-Z0-9-]_|sprd-|MZ-)(?:' . \str_replace('/', '\/', $regex) . ')/i';
try {
if (\preg_match($regex, $this->userAgent, $matches)) {
return $matches;
}
} catch (\Exception $exception) {
throw new \Exception(
\sprintf("%s\nRegex: %s", $exception->getMessage(), $regex),
$exception->getCode(),
$exception
);
}
return null;
}
/**
* @param string $item
* @param array $matches
*
* @return string
*/
protected function buildByMatch(string $item, array $matches): string
{
$search = [];
$replace = [];
for ($nb = 1; $nb <= \count($matches); $nb++) {
$search[] = '$' . $nb;
$replace[] = $matches[$nb] ?? '';
}
return \trim(\str_replace($search, $replace, $item));
}
/**
* Builds the version with the given $versionString and $matches
*
* Example:
* $versionString = 'v$2'
* $matches = ['version_1_0_1', '1_0_1']
* return value would be v1.0.1
*
* @param string $versionString
* @param array $matches
*
* @return string
*/
protected function buildVersion(string $versionString, array $matches): string
{
$versionString = $this->buildByMatch($versionString, $matches);
$versionString = \str_replace('_', '.', $versionString);
if (self::VERSION_TRUNCATION_NONE !== static::$maxMinorParts
&& \substr_count($versionString, '.') > static::$maxMinorParts
) {
$versionParts = \explode('.', $versionString);
$versionParts = \array_slice($versionParts, 0, 1 + static::$maxMinorParts);
$versionString = \implode('.', $versionParts);
}
return \trim($versionString, ' .');
}
/**
* Tests the useragent against a combination of all regexes
*
* All regexes returned by getRegexes() will be reversed and concatenated with '|'
* Afterwards the big regex will be tested against the user agent
*
* Method can be used to speed up detections by making a big check before doing checks for every single regex
*
* @return ?array
*/
protected function preMatchOverall(): ?array
{
$regexes = $this->getRegexes();
$cacheKey = $this->parserName . DeviceDetector::VERSION . '-all';
$cacheKey = (string) \preg_replace('/([^a-z0-9_-]+)/i', '', $cacheKey);
if (empty($this->overAllMatch)) {
$overAllMatch = $this->getCache()->fetch($cacheKey);
if (\is_string($overAllMatch)) {
$this->overAllMatch = $overAllMatch;
}
}
if (empty($this->overAllMatch)) {
// reverse all regexes, so we have the generic one first, which already matches most patterns
$this->overAllMatch = \array_reduce(\array_reverse($regexes), static function ($val1, $val2) {
return !empty($val1) ? $val1 . '|' . $val2['regex'] : $val2['regex'];
});
$this->getCache()->save($cacheKey, $this->overAllMatch);
}
return $this->matchUserAgent($this->overAllMatch);
}
/**
* Compares if two strings equals after lowering their case and removing spaces
*
* @param string $value1
* @param string $value2
*
* @return bool
*/
protected function fuzzyCompare(string $value1, string $value2): bool
{
return \str_replace(' ', '', \strtolower($value1)) ===
\str_replace(' ', '', \strtolower($value2));
}
}

View File

@@ -0,0 +1,88 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser;
/**
* Class Bot
*
* Parses a user agent for bot information
*
* Detected bots are defined in regexes/bots.yml
*/
class Bot extends AbstractBotParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/bots.yml';
/**
* @var string
*/
protected $parserName = 'bot';
/**
* @var bool
*/
protected $discardDetails = false;
/**
* Enables information discarding
*/
public function discardDetails(): void
{
$this->discardDetails = true;
}
/**
* Parses the current UA and checks whether it contains bot information
*
* @see bots.yml for list of detected bots
*
* Step 1: Build a big regex containing all regexes and match UA against it
* -> If no matches found: return
* -> Otherwise:
* Step 2: Walk through the list of regexes in bots.yml and try to match every one
* -> Return the matched data
*
* If $discardDetails is set to TRUE, the Step 2 will be skipped
* $bot will be set to TRUE instead
*
* NOTE: Doing the big match before matching every single regex speeds up the detection
*
* @return array|null
*/
public function parse(): ?array
{
$result = null;
if ($this->preMatchOverall()) {
if ($this->discardDetails) {
return [true];
}
foreach ($this->getRegexes() as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if ($matches) {
unset($regex['regex']);
$result = $regex;
break;
}
}
}
return $result;
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client;
use DeviceDetector\Parser\AbstractParser;
abstract class AbstractClientParser extends AbstractParser
{
/**
* @var string
*/
protected $fixtureFile = '';
/**
* @var string
*/
protected $parserName = '';
/**
* Parses the current UA and checks whether it contains any client information
*
* @see $fixtureFile for file with list of detected clients
*
* Step 1: Build a big regex containing all regexes and match UA against it
* -> If no matches found: return
* -> Otherwise:
* Step 2: Walk through the list of regexes in feed_readers.yml and try to match every one
* -> Return the matched feed reader
*
* NOTE: Doing the big match before matching every single regex speeds up the detection
*
* @return array|null
*/
public function parse(): ?array
{
$result = null;
if ($this->preMatchOverall()) {
foreach ($this->getRegexes() as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if ($matches) {
$result = [
'type' => $this->parserName,
'name' => $this->buildByMatch($regex['name'], $matches),
'version' => $this->buildVersion((string) $regex['version'], $matches),
];
break;
}
}
}
return $result;
}
/**
* Returns all names defined in the regexes
*
* Attention: This method might not return all names of detected clients
*
* @return array
*/
public static function getAvailableClients(): array
{
$instance = new static(); // @phpstan-ignore-line
$regexes = $instance->getRegexes();
$names = [];
foreach ($regexes as $regex) {
if (false !== \strpos($regex['name'], '$1')) {
continue;
}
$names[] = $regex['name'];
}
if (static::class === MobileApp::class) {
$names = \array_merge($names, [
// Microsoft Office $1
'Microsoft Office Access', 'Microsoft Office Excel', 'Microsoft Office OneDrive for Business',
'Microsoft Office OneNote', 'Microsoft Office PowerPoint', 'Microsoft Office Project',
'Microsoft Office Publisher', 'Microsoft Office Visio', 'Microsoft Office Word',
// Podkicker$1
'Podkicker', 'Podkicker Pro', 'Podkicker Classic',
// radio.$1
'radio.at', 'radio.de', 'radio.dk', 'radio.es', 'radio.fr',
'radio.it', 'radio.pl', 'radio.pt', 'radio.se', 'radio.net',
]);
}
\natcasesort($names);
return \array_unique($names);
}
}

View File

@@ -0,0 +1,104 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client\Browser;
use DeviceDetector\Parser\Client\AbstractClientParser;
/**
* Class Engine
*
* Client parser for browser engine detection
*/
class Engine extends AbstractClientParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/browser_engine.yml';
/**
* @var string
*/
protected $parserName = 'browserengine';
/**
* Known browser engines mapped to their internal short codes
*
* @var array
*/
protected static $availableEngines = [
'WebKit',
'Blink',
'Trident',
'Text-based',
'Dillo',
'iCab',
'Elektra',
'Presto',
'Clecko',
'Gecko',
'KHTML',
'NetFront',
'Edge',
'NetSurf',
'Servo',
'Goanna',
'EkiohFlow',
'Arachne',
'LibWeb',
'Maple',
];
/**
* Returns list of all available browser engines
* @return array
*/
public static function getAvailableEngines(): array
{
return self::$availableEngines;
}
/**
* @inheritdoc
*/
public function parse(): ?array
{
$matches = false;
foreach ($this->getRegexes() as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if ($matches) {
break;
}
}
if (empty($matches) || empty($regex)) {
return null;
}
$name = $this->buildByMatch($regex['name'], $matches);
foreach (self::getAvailableEngines() as $engineName) {
if (\strtolower($name) === \strtolower($engineName)) {
return ['engine' => $engineName];
}
}
// This Exception should never be thrown. If so a defined browser name is missing in $availableEngines
throw new \Exception(\sprintf(
'Detected browser engine was not found in $availableEngines. Tried to parse user agent: %s',
$this->userAgent
)); // @codeCoverageIgnore
}
}

View File

@@ -0,0 +1,85 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client\Browser\Engine;
use DeviceDetector\Parser\Client\AbstractClientParser;
/**
* Class Version
*
* Client parser for browser engine version detection
*/
class Version extends AbstractClientParser
{
/**
* @var string
*/
private $engine;
/**
* Version constructor.
*
* @param string $ua
* @param string $engine
*/
public function __construct(string $ua, string $engine)
{
parent::__construct($ua);
$this->engine = $engine;
}
/**
* @inheritdoc
*/
public function parse(): ?array
{
if (empty($this->engine)) {
return null;
}
if ('Gecko' === $this->engine || 'Clecko' === $this->engine) {
$pattern = '~[ ](?:rv[: ]([0-9.]+)).*(?:g|cl)ecko/[0-9]{8,10}~i';
if (\preg_match($pattern, $this->userAgent, $matches)) {
return ['version' => \array_pop($matches)];
}
}
$engineToken = $this->engine;
if ('Blink' === $this->engine) {
$engineToken = 'Chr[o0]me|Chromium|Cronet';
}
if ('Arachne' === $this->engine) {
$engineToken = 'Arachne\/5\.';
}
if ('LibWeb' === $this->engine) {
$engineToken = 'LibWeb\+LibJs';
}
\preg_match(
"~(?:{$engineToken})\s*[/_]?\s*((?(?=\d+\.\d)\d+[.\d]*|\d{1,7}(?=(?:\D|$))))~i",
$this->userAgent,
$matches
);
if (!$matches) {
return null;
}
return ['version' => \array_pop($matches)];
}
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client;
/**
* Class FeedReader
*
* Client parser for feed reader detection
*/
class FeedReader extends AbstractClientParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/feed_readers.yml';
/**
* @var string
*/
protected $parserName = 'feed reader';
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client\Hints;
use DeviceDetector\Parser\AbstractParser;
class AppHints extends AbstractParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/hints/apps.yml';
/**
* @var string
*/
protected $parserName = 'AppHints';
/**
* Get application name if is in collection
*
* @return array|null
*/
public function parse(): ?array
{
if (null === $this->clientHints) {
return null;
}
$appId = $this->clientHints->getApp();
$name = $this->getRegexes()[$appId] ?? null;
if ('' === (string) $name) {
return null;
}
return [
'name' => $name,
];
}
}

View File

@@ -0,0 +1,51 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client\Hints;
use DeviceDetector\Parser\AbstractParser;
class BrowserHints extends AbstractParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/hints/browsers.yml';
/**
* @var string
*/
protected $parserName = 'BrowserHints';
/**
* Get browser name if is in collection
*
* @return array|null
*/
public function parse(): ?array
{
if (null === $this->clientHints) {
return null;
}
$appId = $this->clientHints->getApp();
$name = $this->getRegexes()[$appId] ?? null;
if ('' === (string) $name) {
return null;
}
return [
'name' => $name,
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client;
/**
* Class Library
*
* Client parser for tool & software detection
*/
class Library extends AbstractClientParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/libraries.yml';
/**
* @var string
*/
protected $parserName = 'library';
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client;
/**
* Class MediaPlayer
*
* Client parser for mediaplayer detection
*/
class MediaPlayer extends AbstractClientParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/mediaplayers.yml';
/**
* @var string
*/
protected $parserName = 'mediaplayer';
}

View File

@@ -0,0 +1,126 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client;
use DeviceDetector\Cache\CacheInterface;
use DeviceDetector\ClientHints;
use DeviceDetector\Parser\Client\Hints\AppHints;
use DeviceDetector\Yaml\ParserInterface as YamlParser;
/**
* Class MobileApp
*
* Client parser for mobile app detection
*/
class MobileApp extends AbstractClientParser
{
/**
* @var AppHints
*/
private $appHints;
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/mobile_apps.yml';
/**
* @var string
*/
protected $parserName = 'mobile app';
/**
* MobileApp constructor.
*
* @param string $ua
* @param ClientHints|null $clientHints
*/
public function __construct(string $ua = '', ?ClientHints $clientHints = null)
{
$this->appHints = new AppHints($ua, $clientHints);
parent::__construct($ua, $clientHints);
}
/**
* Sets the client hints to parse
*
* @param ?ClientHints $clientHints client hints
*/
public function setClientHints(?ClientHints $clientHints): void
{
parent::setClientHints($clientHints);
$this->appHints->setClientHints($clientHints);
}
/**
* Sets the user agent to parse
*
* @param string $ua user agent
*/
public function setUserAgent(string $ua): void
{
parent::setUserAgent($ua);
$this->appHints->setUserAgent($ua);
}
/**
* Sets the Cache class
*
* @param CacheInterface $cache
*/
public function setCache(CacheInterface $cache): void
{
parent::setCache($cache);
$this->appHints->setCache($cache);
}
/**
* Sets the YamlParser class
*
* @param YamlParser $yamlParser
*/
public function setYamlParser(YamlParser $yamlParser): void
{
parent::setYamlParser($yamlParser);
$this->appHints->setYamlParser($this->getYamlParser());
}
/**
* Parses the current UA and checks whether it contains any client information
* See parent::parse() for more details.
*
* @return array|null
*/
public function parse(): ?array
{
$result = parent::parse();
$name = $result['name'] ?? '';
$version = $result['version'] ?? '';
$appHash = $this->appHints->parse();
if (null !== $appHash && $appHash['name'] !== $name) {
$name = $appHash['name'];
$version = '';
}
if (empty($name)) {
return null;
}
return [
'type' => $this->parserName,
'name' => $name,
'version' => $version,
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Client;
/**
* Class PIM
*
* Client parser for pim (personal information manager) detection
*/
class PIM extends AbstractClientParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/client/pim.yml';
/**
* @var string
*/
protected $parserName = 'pim';
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class Camera
*
* Device parser for camera detection
*/
class Camera extends AbstractDeviceParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/device/cameras.yml';
/**
* @var string
*/
protected $parserName = 'camera';
/**
* @inheritdoc
*/
public function parse(): ?array
{
if (!$this->preMatchOverall()) {
return null;
}
return parent::parse();
}
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class CarBrowser
*
* Device parser for car browser detection
*/
class CarBrowser extends AbstractDeviceParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/device/car_browsers.yml';
/**
* @var string
*/
protected $parserName = 'car browser';
/**
* @inheritdoc
*/
public function parse(): ?array
{
if (!$this->preMatchOverall()) {
return null;
}
return parent::parse();
}
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class Console
*
* Device parser for console detection
*/
class Console extends AbstractDeviceParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/device/consoles.yml';
/**
* @var string
*/
protected $parserName = 'console';
/**
* @inheritdoc
*/
public function parse(): ?array
{
if (!$this->preMatchOverall()) {
return null;
}
return parent::parse();
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class HbbTv
*
* Device parser for hbbtv detection
*/
class HbbTv extends AbstractDeviceParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/device/televisions.yml';
/**
* @var string
*/
protected $parserName = 'tv';
/**
* Parses the current UA and checks whether it contains HbbTv or SmartTvA information
*
* @see televisions.yml for list of detected televisions
*
* @return array|null
*/
public function parse(): ?array
{
// only parse user agents containing fragments: hbbtv or SmartTvA
if (null === $this->isHbbTv()) {
return null;
}
parent::parse();
// always set device type to tv, even if no model/brand could be found
if (null === $this->deviceType) {
$this->deviceType = self::DEVICE_TYPE_TV;
}
return $this->getResult();
}
/**
* Returns if the parsed UA was identified as a HbbTV device
*
* @return string|null
*/
public function isHbbTv(): ?string
{
$regex = '(?:HbbTV|SmartTvA)/([1-9]{1}(?:\.[0-9]{1}){1,2})';
$match = $this->matchUserAgent($regex);
return $match[1] ?? null;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class Mobile
*
* Device parser for mobile detection
*/
class Mobile extends AbstractDeviceParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/device/mobiles.yml';
/**
* @var string
*/
protected $parserName = 'mobile';
}

View File

@@ -0,0 +1,37 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class Notebook
*
* Device parser for notebook detection in Facebook useragents
*/
class Notebook extends AbstractDeviceParser
{
protected $fixtureFile = 'regexes/device/notebooks.yml';
protected $parserName = 'notebook';
/**
* @inheritdoc
*/
public function parse(): ?array
{
if (!$this->matchUserAgent('FBMD/')) {
return null;
}
return parent::parse();
}
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class PortableMediaPlayer
*
* Device parser for portable media player detection
*/
class PortableMediaPlayer extends AbstractDeviceParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/device/portable_media_player.yml';
/**
* @var string
*/
protected $parserName = 'portablemediaplayer';
/**
* @inheritdoc
*/
public function parse(): ?array
{
if (!$this->preMatchOverall()) {
return null;
}
return parent::parse();
}
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser\Device;
/**
* Class ShellTv
*/
class ShellTv extends AbstractDeviceParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/device/shell_tv.yml';
/**
* @var string
*/
protected $parserName = 'shelltv';
/**
* Returns if the parsed UA was identified as ShellTv device
*
* @return bool
*
* @throws \Exception
*/
public function isShellTv(): bool
{
$regex = '[a-z]+[ _]Shell[ _]\w{6}|tclwebkit(\d+[.\d]*)';
$match = $this->matchUserAgent($regex);
return null !== $match;
}
/**
* Parses the current UA and checks whether it contains ShellTv information
*
* @see shell_tv.yml for list of detected televisions
*
* @return array|null
*/
public function parse(): ?array
{
// only parse user agents containing fragments: {brand} shell
if (false === $this->isShellTv()) {
return null;
}
parent::parse();
// always set device type to tv, even if no model/brand could be found
$this->deviceType = self::DEVICE_TYPE_TV;
return $this->getResult();
}
}

View File

@@ -0,0 +1,756 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser;
use DeviceDetector\ClientHints;
/**
* Class OperatingSystem
*
* Parses the useragent for operating system information
*
* Detected operating systems can be found in self::$operatingSystems and /regexes/oss.yml
* This class also defined some operating system families and methods to get the family for a specific os
*/
class OperatingSystem extends AbstractParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/oss.yml';
/**
* @var string
*/
protected $parserName = 'os';
/**
* Known operating systems mapped to their internal short codes
*
* @var array
*/
protected static $operatingSystems = [
'AIX' => 'AIX',
'AND' => 'Android',
'ADR' => 'Android TV',
'ALP' => 'Alpine Linux',
'AMZ' => 'Amazon Linux',
'AMG' => 'AmigaOS',
'ARM' => 'Armadillo OS',
'ARO' => 'AROS',
'ATV' => 'tvOS',
'ARL' => 'Arch Linux',
'AOS' => 'AOSC OS',
'ASP' => 'ASPLinux',
'AZU' => 'Azure Linux',
'BTR' => 'BackTrack',
'SBA' => 'Bada',
'BYI' => 'Baidu Yi',
'BEO' => 'BeOS',
'BLB' => 'BlackBerry OS',
'QNX' => 'BlackBerry Tablet OS',
'PAN' => 'blackPanther OS',
'BOS' => 'Bliss OS',
'BMP' => 'Brew',
'BSN' => 'BrightSignOS',
'CAI' => 'Caixa Mágica',
'CES' => 'CentOS',
'CST' => 'CentOS Stream',
'CLO' => 'Clear Linux OS',
'CLR' => 'ClearOS Mobile',
'COS' => 'Chrome OS',
'CRS' => 'Chromium OS',
'CHN' => 'China OS',
'COL' => 'Coolita OS',
'CYN' => 'CyanogenMod',
'DEB' => 'Debian',
'DEE' => 'Deepin',
'DFB' => 'DragonFly',
'DVK' => 'DVKBuntu',
'ELE' => 'ElectroBSD',
'EUL' => 'EulerOS',
'FED' => 'Fedora',
'FEN' => 'Fenix',
'FOS' => 'Firefox OS',
'FIR' => 'Fire OS',
'FOR' => 'Foresight Linux',
'FRE' => 'Freebox',
'BSD' => 'FreeBSD',
'FRI' => 'FRITZ!OS',
'FYD' => 'FydeOS',
'FUC' => 'Fuchsia',
'GNT' => 'Gentoo',
'GNX' => 'GENIX',
'GEO' => 'GEOS',
'GNS' => 'gNewSense',
'GRI' => 'GridOS',
'GTV' => 'Google TV',
'HPX' => 'HP-UX',
'HAI' => 'Haiku OS',
'IPA' => 'iPadOS',
'HAR' => 'HarmonyOS',
'HAS' => 'HasCodingOS',
'HEL' => 'HELIX OS',
'IRI' => 'IRIX',
'INF' => 'Inferno',
'JME' => 'Java ME',
'JOL' => 'Joli OS',
'KOS' => 'KaiOS',
'KAL' => 'Kali',
'KAN' => 'Kanotix',
'KIN' => 'KIN OS',
'KOL' => 'KolibriOS',
'KNO' => 'Knoppix',
'KTV' => 'KreaTV',
'KBT' => 'Kubuntu',
'LIN' => 'GNU/Linux',
'LEA' => 'LeafOS',
'LND' => 'LindowsOS',
'LNS' => 'Linspire',
'LEN' => 'Lineage OS',
'LIR' => 'Liri OS',
'LOO' => 'Loongnix',
'LBT' => 'Lubuntu',
'LOS' => 'Lumin OS',
'LUN' => 'LuneOS',
'VLN' => 'VectorLinux',
'MAC' => 'Mac',
'MAE' => 'Maemo',
'MAG' => 'Mageia',
'MDR' => 'Mandriva',
'SMG' => 'MeeGo',
'MET' => 'Meta Horizon',
'MCD' => 'MocorDroid',
'MON' => 'moonOS',
'EZX' => 'Motorola EZX',
'MIN' => 'Mint',
'MLD' => 'MildWild',
'MOR' => 'MorphOS',
'NBS' => 'NetBSD',
'MTK' => 'MTK / Nucleus',
'MRE' => 'MRE',
'NXT' => 'NeXTSTEP',
'NWS' => 'NEWS-OS',
'WII' => 'Nintendo',
'NDS' => 'Nintendo Mobile',
'NOV' => 'Nova',
'OS2' => 'OS/2',
'T64' => 'OSF1',
'OBS' => 'OpenBSD',
'OVS' => 'OpenVMS',
'OVZ' => 'OpenVZ',
'OWR' => 'OpenWrt',
'OTV' => 'Opera TV',
'ORA' => 'Oracle Linux',
'ORD' => 'Ordissimo',
'PAR' => 'Pardus',
'PCL' => 'PCLinuxOS',
'PIC' => 'PICO OS',
'PLA' => 'Plasma Mobile',
'PSP' => 'PlayStation Portable',
'PS3' => 'PlayStation',
'PVE' => 'Proxmox VE',
'PUF' => 'Puffin OS',
'PUR' => 'PureOS',
'QTP' => 'Qtopia',
'PIO' => 'Raspberry Pi OS',
'RAS' => 'Raspbian',
'RHT' => 'Red Hat',
'RST' => 'Red Star',
'RED' => 'RedOS',
'REV' => 'Revenge OS',
'RIS' => 'risingOS',
'ROS' => 'RISC OS',
'ROC' => 'Rocky Linux',
'ROK' => 'Roku OS',
'RSO' => 'Rosa',
'ROU' => 'RouterOS',
'REM' => 'Remix OS',
'RRS' => 'Resurrection Remix OS',
'REX' => 'REX',
'RZD' => 'RazoDroiD',
'RXT' => 'RTOS & Next',
'SAB' => 'Sabayon',
'SSE' => 'SUSE',
'SAF' => 'Sailfish OS',
'SCI' => 'Scientific Linux',
'SEE' => 'SeewoOS',
'SER' => 'SerenityOS',
'SIR' => 'Sirin OS',
'SLW' => 'Slackware',
'SOS' => 'Solaris',
'SBL' => 'Star-Blade OS',
'SYL' => 'Syllable',
'SYM' => 'Symbian',
'SYS' => 'Symbian OS',
'S40' => 'Symbian OS Series 40',
'S60' => 'Symbian OS Series 60',
'SY3' => 'Symbian^3',
'TEN' => 'TencentOS',
'TDX' => 'ThreadX',
'TIZ' => 'Tizen',
'TIV' => 'TiVo OS',
'TOS' => 'TmaxOS',
'TUR' => 'Turbolinux',
'UBT' => 'Ubuntu',
'ULT' => 'ULTRIX',
'UOS' => 'UOS',
'VID' => 'VIDAA',
'VIZ' => 'ViziOS',
'WAS' => 'watchOS',
'WER' => 'Wear OS',
'WTV' => 'WebTV',
'WHS' => 'Whale OS',
'WIN' => 'Windows',
'WCE' => 'Windows CE',
'WIO' => 'Windows IoT',
'WMO' => 'Windows Mobile',
'WPH' => 'Windows Phone',
'WRT' => 'Windows RT',
'WPO' => 'WoPhone',
'XBX' => 'Xbox',
'XBT' => 'Xubuntu',
'YNS' => 'YunOS',
'ZEN' => 'Zenwalk',
'ZOR' => 'ZorinOS',
'IOS' => 'iOS',
'POS' => 'palmOS',
'WEB' => 'Webian',
'WOS' => 'webOS',
];
/**
* Operating system families mapped to the short codes of the associated operating systems
*
* @var array
*/
protected static $osFamilies = [
'Android' => [
'AND', 'CYN', 'FIR', 'REM', 'RZD', 'MLD', 'MCD', 'YNS', 'GRI', 'HAR',
'ADR', 'CLR', 'BOS', 'REV', 'LEN', 'SIR', 'RRS', 'WER', 'PIC', 'ARM',
'HEL', 'BYI', 'RIS', 'PUF', 'LEA', 'MET',
],
'AmigaOS' => ['AMG', 'MOR', 'ARO'],
'BlackBerry' => ['BLB', 'QNX'],
'Brew' => ['BMP'],
'BeOS' => ['BEO', 'HAI'],
'Chrome OS' => ['COS', 'CRS', 'FYD', 'SEE'],
'Firefox OS' => ['FOS', 'KOS'],
'Gaming Console' => ['WII', 'PS3'],
'Google TV' => ['GTV'],
'IBM' => ['OS2'],
'iOS' => ['IOS', 'ATV', 'WAS', 'IPA'],
'RISC OS' => ['ROS'],
'GNU/Linux' => [
'LIN', 'ARL', 'DEB', 'KNO', 'MIN', 'UBT', 'KBT', 'XBT', 'LBT', 'FED',
'RHT', 'VLN', 'MDR', 'GNT', 'SAB', 'SLW', 'SSE', 'CES', 'BTR', 'SAF',
'ORD', 'TOS', 'RSO', 'DEE', 'FRE', 'MAG', 'FEN', 'CAI', 'PCL', 'HAS',
'LOS', 'DVK', 'ROK', 'OWR', 'OTV', 'KTV', 'PUR', 'PLA', 'FUC', 'PAR',
'FOR', 'MON', 'KAN', 'ZEN', 'LND', 'LNS', 'CHN', 'AMZ', 'TEN', 'CST',
'NOV', 'ROU', 'ZOR', 'RED', 'KAL', 'ORA', 'VID', 'TIV', 'BSN', 'RAS',
'UOS', 'PIO', 'FRI', 'LIR', 'WEB', 'SER', 'ASP', 'AOS', 'LOO', 'EUL',
'SCI', 'ALP', 'CLO', 'ROC', 'OVZ', 'PVE', 'RST', 'EZX', 'GNS', 'JOL',
'TUR', 'QTP', 'WPO', 'PAN', 'VIZ', 'AZU', 'COL',
],
'Mac' => ['MAC'],
'Mobile Gaming Console' => ['PSP', 'NDS', 'XBX'],
'OpenVMS' => ['OVS'],
'Real-time OS' => ['MTK', 'TDX', 'MRE', 'JME', 'REX', 'RXT', 'KOL'],
'Other Mobile' => ['WOS', 'POS', 'SBA', 'TIZ', 'SMG', 'MAE', 'LUN', 'GEO'],
'Symbian' => ['SYM', 'SYS', 'SY3', 'S60', 'S40'],
'Unix' => [
'SOS', 'AIX', 'HPX', 'BSD', 'NBS', 'OBS', 'DFB', 'SYL', 'IRI', 'T64',
'INF', 'ELE', 'GNX', 'ULT', 'NWS', 'NXT', 'SBL',
],
'WebTV' => ['WTV'],
'Windows' => ['WIN'],
'Windows Mobile' => ['WPH', 'WMO', 'WCE', 'WRT', 'WIO', 'KIN'],
'Other Smart TV' => ['WHS'],
];
/**
* Contains a list of mappings from OS names we use to known client hint values
*
* @var array<string, array<string>>
*/
protected static $clientHintMapping = [
'GNU/Linux' => ['Linux'],
'Mac' => ['MacOS'],
];
/**
* Operating system families that are known as desktop only
*
* @var array
*/
protected static $desktopOsArray = [
'AmigaOS', 'IBM', 'GNU/Linux', 'Mac', 'Unix', 'Windows', 'BeOS', 'Chrome OS',
];
/**
* Fire OS version mapping
*
* @var array
*/
private $fireOsVersionMapping = [
'11' => '8',
'10' => '8',
'9' => '7',
'7' => '6',
'5' => '5',
'4.4.3' => '4.5.1',
'4.4.2' => '4',
'4.2.2' => '3',
'4.0.3' => '3',
'4.0.2' => '3',
'4' => '2',
'2' => '1',
];
/**
* Lineage OS version mapping
*
* @var array
*/
private $lineageOsVersionMapping = [
'16' => '23',
'15' => '22',
'14' => '21',
'13' => '20.0',
'12.1' => '19.1',
'12' => '19.0',
'11' => '18.0',
'10' => '17.0',
'9' => '16.0',
'8.1.0' => '15.1',
'8.0.0' => '15.0',
'7.1.2' => '14.1',
'7.1.1' => '14.1',
'7.0' => '14.0',
'6.0.1' => '13.0',
'6.0' => '13.0',
'5.1.1' => '12.1',
'5.0.2' => '12.0',
'5.0' => '12.0',
'4.4.4' => '11.0',
'4.3' => '10.2',
'4.2.2' => '10.1',
'4.0.4' => '9.1.0',
];
/**
* Returns all available operating systems
*
* @return array
*/
public static function getAvailableOperatingSystems(): array
{
return self::$operatingSystems;
}
/**
* Returns all available operating system families
*
* @return array
*/
public static function getAvailableOperatingSystemFamilies(): array
{
return self::$osFamilies;
}
/**
* Returns the os name and shot name
*
* @param string $name
*
* @return array
*/
public static function getShortOsData(string $name): array
{
$short = 'UNK';
foreach (self::$operatingSystems as $osShort => $osName) {
if (\strtolower($name) !== \strtolower($osName)) {
continue;
}
$name = $osName;
$short = $osShort;
break;
}
return \compact('short', 'name');
}
/**
* @inheritdoc
*/
public function parse(): ?array
{
$this->restoreUserAgentFromClientHints();
$osFromClientHints = $this->parseOsFromClientHints();
$osFromUserAgent = $this->parseOsFromUserAgent();
if (!empty($osFromClientHints['name'])) {
$name = $osFromClientHints['name'];
$version = $osFromClientHints['version'];
// use version from user agent if non was provided in client hints, but os family from useragent matches
if (empty($version)
&& self::getOsFamily($name) === self::getOsFamily($osFromUserAgent['name'])
) {
$version = $osFromUserAgent['version'];
}
// On Windows, version 0.0.0 can be either 7, 8 or 8.1
if ('Windows' === $name && '0.0.0' === $version) {
$version = ('10' === $osFromUserAgent['version']) ? '' : $osFromUserAgent['version'];
}
// If the OS name detected from client hints matches the OS family from user agent
// but the os name is another, we use the one from user agent, as it might be more detailed
if (self::getOsFamily($osFromUserAgent['name']) === $name && $osFromUserAgent['name'] !== $name) {
$name = $osFromUserAgent['name'];
if ('LeafOS' === $name || 'HarmonyOS' === $name) {
$version = '';
}
if ('PICO OS' === $name) {
$version = $osFromUserAgent['version'];
}
if ('Fire OS' === $name && !empty($osFromClientHints['version'])) {
$majorVersion = (int) (\explode('.', $version, 1)[0] ?? '0');
$version = $this->fireOsVersionMapping[$version]
?? $this->fireOsVersionMapping[$majorVersion] ?? '';
}
}
$short = $osFromClientHints['short_name'];
// Chrome OS is in some cases reported as Linux in client hints, we fix this only if the version matches
if ('GNU/Linux' === $name
&& 'Chrome OS' === $osFromUserAgent['name']
&& $osFromClientHints['version'] === $osFromUserAgent['version']
) {
$name = $osFromUserAgent['name'];
$short = $osFromUserAgent['short_name'];
}
// Chrome OS is in some cases reported as Android in client hints
if ('Android' === $name && 'Chrome OS' === $osFromUserAgent['name']) {
$name = $osFromUserAgent['name'];
$version = '';
$short = $osFromUserAgent['short_name'];
}
// Meta Horizon is reported as Linux in client hints
if ('GNU/Linux' === $name && 'Meta Horizon' === $osFromUserAgent['name']) {
$name = $osFromUserAgent['name'];
$short = $osFromUserAgent['short_name'];
}
} elseif (!empty($osFromUserAgent['name'])) {
$name = $osFromUserAgent['name'];
$version = $osFromUserAgent['version'];
$short = $osFromUserAgent['short_name'];
} else {
return [];
}
$platform = $this->parsePlatform();
$family = self::getOsFamily($short);
$androidApps = [
'com.hisense.odinbrowser', 'com.seraphic.openinet.pre', 'com.appssppa.idesktoppcbrowser',
'every.browser.inc',
];
if (null !== $this->clientHints) {
if (\in_array($this->clientHints->getApp(), $androidApps) && 'Android' !== $name) {
$name = 'Android';
$family = 'Android';
$short = 'ADR';
$version = '';
}
if ('org.lineageos.jelly' === $this->clientHints->getApp() && 'Lineage OS' !== $name) {
$majorVersion = (int) (\explode('.', $version, 1)[0] ?? '0');
$name = 'Lineage OS';
$family = 'Android';
$short = 'LEN';
$version = $this->lineageOsVersionMapping[$version]
?? $this->lineageOsVersionMapping[$majorVersion] ?? '';
}
if ('org.mozilla.tv.firefox' === $this->clientHints->getApp() && 'Fire OS' !== $name) {
$majorVersion = (int) (\explode('.', $version, 1)[0] ?? '0');
$name = 'Fire OS';
$family = 'Android';
$short = 'FIR';
$version = $this->fireOsVersionMapping[$version] ?? $this->fireOsVersionMapping[$majorVersion] ?? '';
}
}
$return = [
'name' => $name,
'short_name' => $short,
'version' => $version,
'platform' => $platform,
'family' => $family,
];
if (\in_array($return['name'], self::$operatingSystems)) {
$return['short_name'] = \array_search($return['name'], self::$operatingSystems);
}
return $return;
}
/**
* Returns the operating system family for the given operating system
*
* @param string $osLabel name or short name
*
* @return string|null If null, "Unknown"
*/
public static function getOsFamily(string $osLabel): ?string
{
if (\in_array($osLabel, self::$operatingSystems)) {
$osLabel = \array_search($osLabel, self::$operatingSystems);
}
foreach (self::$osFamilies as $family => $labels) {
if (\in_array($osLabel, $labels)) {
return (string) $family;
}
}
return null;
}
/**
* Returns true if OS is desktop
*
* @param string $osName OS short name
*
* @return bool
*/
public static function isDesktopOs(string $osName): bool
{
$osFamily = self::getOsFamily($osName);
return \in_array($osFamily, self::$desktopOsArray);
}
/**
* Returns the full name for the given short name
*
* @param string $os
* @param string|null $ver
*
* @return ?string
*/
public static function getNameFromId(string $os, ?string $ver = null): ?string
{
if (\array_key_exists($os, self::$operatingSystems)) {
$osFullName = self::$operatingSystems[$os];
return \trim($osFullName . ' ' . $ver);
}
return null;
}
/**
* Returns the OS that can be safely detected from client hints
*
* @return array
*/
protected function parseOsFromClientHints(): array
{
$name = $version = $short = '';
if ($this->clientHints instanceof ClientHints && $this->clientHints->getOperatingSystem()) {
$hintName = $this->applyClientHintMapping($this->clientHints->getOperatingSystem());
foreach (self::$operatingSystems as $osShort => $osName) {
if ($this->fuzzyCompare($hintName, $osName)) {
$name = $osName;
$short = $osShort;
break;
}
}
$version = $this->clientHints->getOperatingSystemVersion();
if ('Windows' === $name) {
$majorVersion = (int) (\explode('.', $version, 1)[0] ?? '0');
$minorVersion = (int) (\explode('.', $version, 2)[1] ?? '0');
if (0 === $majorVersion) {
$minorVersionMapping = [1 => '7', 2 => '8', 3 => '8.1'];
$version = $minorVersionMapping[$minorVersion] ?? $version;
} elseif ($majorVersion > 0 && $majorVersion < 11) {
$version = '10';
} elseif ($majorVersion > 10) {
$version = '11';
}
}
// On Windows, version 0.0.0 can be either 7, 8 or 8.1, so we return 0.0.0
if ('Windows' !== $name && '0.0.0' !== $version && 0 === (int) $version) {
$version = '';
}
}
return [
'name' => $name,
'short_name' => $short,
'version' => $this->buildVersion($version, []),
];
}
/**
* Returns the OS that can be detected from useragent
*
* @return array
*
* @throws \Exception
*/
protected function parseOsFromUserAgent(): array
{
$osRegex = $matches = [];
$name = $version = $short = '';
foreach ($this->getRegexes() as $osRegex) {
$matches = $this->matchUserAgent($osRegex['regex']);
if ($matches) {
break;
}
}
if (!empty($matches)) {
$name = $this->buildByMatch($osRegex['name'], $matches);
['name' => $name, 'short' => $short] = self::getShortOsData($name);
$version = \array_key_exists('version', $osRegex)
? $this->buildVersion((string) $osRegex['version'], $matches)
: '';
foreach ($osRegex['versions'] ?? [] as $regex) {
$matches = $this->matchUserAgent($regex['regex']);
if (!$matches) {
continue;
}
if (\array_key_exists('name', $regex)) {
$name = $this->buildByMatch($regex['name'], $matches);
['name' => $name, 'short' => $short] = self::getShortOsData($name);
}
if (\array_key_exists('version', $regex)) {
$version = $this->buildVersion((string) $regex['version'], $matches);
}
break;
}
}
return [
'name' => $name,
'short_name' => $short,
'version' => $version,
];
}
/**
* Parse current UserAgent string for the operating system platform
*
* @return string
*/
protected function parsePlatform(): string
{
// Use architecture from client hints if available
if ($this->clientHints instanceof ClientHints && $this->clientHints->getArchitecture()) {
$arch = \strtolower($this->clientHints->getArchitecture());
if (false !== \strpos($arch, 'arm')) {
return 'ARM';
}
if (false !== \strpos($arch, 'loongarch64')) {
return 'LoongArch64';
}
if (false !== \strpos($arch, 'mips')) {
return 'MIPS';
}
if (false !== \strpos($arch, 'sh4')) {
return 'SuperH';
}
if (false !== \strpos($arch, 'sparc64')) {
return 'SPARC64';
}
if (false !== \strpos($arch, 'x64')
|| (false !== \strpos($arch, 'x86') && '64' === $this->clientHints->getBitness())
) {
return 'x64';
}
if (false !== \strpos($arch, 'x86')) {
return 'x86';
}
}
if ($this->matchUserAgent('arm[ _;)ev]|.*arm$|.*arm64|aarch64|Apple ?TV|Watch ?OS|Watch1,[12]')) {
return 'ARM';
}
if ($this->matchUserAgent('loongarch64')) {
return 'LoongArch64';
}
if ($this->matchUserAgent('mips')) {
return 'MIPS';
}
if ($this->matchUserAgent('sh4')) {
return 'SuperH';
}
if ($this->matchUserAgent('sparc64')) {
return 'SPARC64';
}
if ($this->matchUserAgent('64-?bit|WOW64|(?:Intel)?x64|WINDOWS_64|win64|.*amd64|.*x86_?64')) {
return 'x64';
}
if ($this->matchUserAgent('.*32bit|.*win32|(?:i[0-9]|x)86|i86pc')) {
return 'x86';
}
return '';
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Parser;
/**
* Class VendorFragments
*
* Device parser for vendor fragment detection
*/
class VendorFragment extends AbstractParser
{
/**
* @var string
*/
protected $fixtureFile = 'regexes/vendorfragments.yml';
/**
* @var string
*/
protected $parserName = 'vendorfragments';
/**
* @var string
*/
protected $matchedRegex = null;
/**
* @inheritdoc
*/
public function parse(): ?array
{
foreach ($this->getRegexes() as $brand => $regexes) {
foreach ($regexes as $regex) {
if ($this->matchUserAgent($regex . '[^a-z0-9]+')) {
$this->matchedRegex = $regex;
return ['brand' => $brand];
}
}
}
return null;
}
/**
* @return string|null
*/
public function getMatchedRegex(): ?string
{
return $this->matchedRegex;
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,25 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Yaml;
interface ParserInterface
{
/**
* Parses the file with the given filename and returns the converted content
*
* @param string $file
*
* @return mixed
*/
public function parseFile(string $file);
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Yaml;
use Exception;
/**
* Class Pecl
*
* Parses a YAML file with LibYAML library
* @see http://php.net/manual/en/function.yaml-parse-file.php
*/
class Pecl implements ParserInterface
{
/**
* Parses the file with the given filename using PECL and returns the converted content
* @param string $file The path to the YAML file to be parsed
*
* @return mixed The YAML converted to a PHP value or FALSE on failure
*
* @throws Exception If the YAML extension is not installed
*/
public function parseFile(string $file)
{
if (false === \function_exists('yaml_parse_file')) {
throw new Exception('Pecl YAML extension is not installed');
}
return \yaml_parse_file($file);
}
}

View File

@@ -0,0 +1,30 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Yaml;
use Spyc as SpycParser;
class Spyc implements ParserInterface
{
/**
* Parses the file with the given filename using Spyc and returns the converted content
*
* @param string $file
*
* @return mixed
*/
public function parseFile(string $file)
{
return SpycParser::YAMLLoad($file);
}
}

View File

@@ -0,0 +1,30 @@
<?php
/**
* Device Detector - The Universal Device Detection library for parsing User Agents
*
* @link https://matomo.org
*
* @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
*/
declare(strict_types=1);
namespace DeviceDetector\Yaml;
use Symfony\Component\Yaml\Yaml;
class Symfony implements ParserInterface
{
/**
* Parses the file with the given filename using Symfony Yaml parser and returns the converted content
*
* @param string $file
*
* @return mixed
*/
public function parseFile(string $file)
{
return Yaml::parseFile($file);
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* PSR-4 autoloader implementation for the DeviceDetector namespace.
* First we define the 'dd_autoload' function, and then we register
* it with 'spl_autoload_register' so that PHP knows to use it.
*/
/**
* Automatically include the file that defines <code>class</code>.
*
* @param string $class
* the name of the class to load
*
* @return void
*/
function dd_autoload(string $class): void
{
if (false === strpos($class, 'DeviceDetector\\')) {
return;
}
$namespaceMap = ['DeviceDetector\\' => __DIR__ . '/'];
foreach ($namespaceMap as $prefix => $dir) {
/* First swap out the namespace prefix with a directory... */
$path = str_replace($prefix, $dir, $class);
/* replace the namespace separator with a directory separator... */
$path = str_replace('\\', '/', $path);
/* and finally, add the PHP file extension to the result. */
$path .= '.php';
/* $path should now contain the path to a PHP file defining $class */
require $path;
}
}
spl_autoload_register('dd_autoload');

View File

@@ -0,0 +1,57 @@
{
"name": "matomo/device-detector",
"type": "library",
"description": "The Universal Device Detection library, that parses User Agents and detects devices (desktop, tablet, mobile, tv, cars, console, etc.), clients (browsers, media players, mobile apps, feed readers, libraries, etc), operating systems, devices, brands and models.",
"keywords": ["useragent","parser","devicedetection"],
"homepage": "https://matomo.org",
"license": "LGPL-3.0-or-later",
"authors": [
{
"name": "The Matomo Team",
"email": "hello@matomo.org",
"homepage": "https://matomo.org/team/"
}
],
"support": {
"forum": "https://forum.matomo.org/",
"issues": "https://github.com/matomo-org/device-detector/issues",
"wiki": "https://dev.matomo.org/",
"source": "https://github.com/matomo-org/matomo"
},
"autoload": {
"psr-4": { "DeviceDetector\\": "" },
"exclude-from-classmap": ["Tests/"]
},
"require": {
"php": "^7.2|^8.0",
"mustangostang/spyc": "*"
},
"require-dev": {
"phpunit/phpunit": "^8.5.8",
"psr/cache": "^1.0.1",
"psr/simple-cache": "^1.0.1",
"matthiasmullie/scrapbook": "^1.4.7",
"phpstan/phpstan": "^1.10.44",
"mayflower/mo4-coding-standard": "^v9.0.0",
"slevomat/coding-standard": "<8.16.0",
"symfony/yaml": "^5.1.7"
},
"suggest": {
"doctrine/cache": "Can directly be used for caching purpose",
"ext-yaml": "Necessary for using the Pecl YAML parser"
},
"scripts": {
"php-cs-fixed": "php vendor/bin/phpcbf"
},
"archive": {
"exclude": ["/autoload.php"]
},
"replace": {
"piwik/device-detector":"self.version"
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true
}
}
}

View File

@@ -0,0 +1,111 @@
<?xml version="1.0"?>
<ruleset name="device-detector">
<description>Device Detector Coding Standard</description>
<file>.</file>
<exclude-pattern>vendor/</exclude-pattern>
<!-- use MO4 coding standard as base -->
<rule ref="MO4">
<exclude name="SlevomatCodingStandard.Classes.ForbiddenPublicProperty.ForbiddenPublicProperty"/>
<exclude name="SlevomatCodingStandard.Commenting.UselessInheritDocComment"/>
<exclude name="SlevomatCodingStandard.Functions.UnusedParameter.UnusedParameter"/>
<exclude name="Squiz.PHP.DisallowMultipleAssignments.Found"/>
<exclude name="SlevomatCodingStandard.ControlStructures.RequireTernaryOperator"/>
</rule>
<rule ref="SlevomatCodingStandard.ControlStructures.RequireTernaryOperator">
<properties>
<property name="ignoreMultiLine" value="true"/>
</properties>
</rule>
<rule ref="Symfony.Commenting">
<exclude-pattern>misc/</exclude-pattern>
<exclude-pattern>Tests/</exclude-pattern>
</rule>
<rule ref="Squiz.Functions.GlobalFunction.Found">
<exclude-pattern>misc/</exclude-pattern>
<exclude-pattern>autoload.php</exclude-pattern>
</rule>
<rule ref="PSR1.Files.SideEffects.FoundWithSymbols">
<exclude-pattern>misc/</exclude-pattern>
<exclude-pattern>autoload.php</exclude-pattern>
</rule>
<!-- Disallow more than 120 chars per line -->
<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="120" />
<property name="absoluteLineLimit" value="120" />
</properties>
<exclude-pattern>misc/</exclude-pattern>
<exclude-pattern>Tests/</exclude-pattern>
</rule>
<!-- Require spaces around string concatenating -->
<rule ref="Squiz.Strings.ConcatenationSpacing">
<properties>
<property name="spacing" value="1" />
</properties>
</rule>
<!-- Disallow is_null function -->
<rule ref="Generic.PHP.ForbiddenFunctions">
<properties>
<property name="forbiddenFunctions" type="array" value="is_null=>null"/>
</properties>
</rule>
<!-- Require empty lines around control structures -->
<rule ref="SlevomatCodingStandard.ControlStructures.BlockControlStructureSpacing"/>
<!-- Require strict types -->
<rule ref="SlevomatCodingStandard.TypeHints.DeclareStrictTypes">
<properties>
<property name="linesCountBeforeDeclare" value="1" />
<property name="spacesCountAroundEqualsSign" value="0" />
<property name="linesCountAfterDeclare" value="1" />
</properties>
</rule>
<!-- Require Yoda-Conditions -->
<rule ref="SlevomatCodingStandard.ControlStructures.RequireYodaComparison"/>
<!-- Disallow useless semicolons -->
<rule ref="SlevomatCodingStandard.PHP.UselessSemicolon" />
<!-- Disallow old type hints in comments (e.g. "int[]" should be "array<int>") -->
<rule ref="SlevomatCodingStandard.TypeHints.DisallowArrayTypeHintSyntax"/>
<!-- Disallow spaces after splat operator -->
<rule ref="SlevomatCodingStandard.Operators.SpreadOperatorSpacing"/>
<!-- Disallow empty lines around class braces -->
<rule ref="SlevomatCodingStandard.Classes.EmptyLinesAroundClassBraces">
<properties>
<property name="linesCountAfterOpeningBrace" value="0" />
<property name="linesCountBeforeClosingBrace" value="0" />
</properties>
</rule>
<!-- Require empty lines around namespace definition -->
<rule ref="SlevomatCodingStandard.Namespaces.NamespaceSpacing">
<properties>
<property name="linesCountBeforeNamespace" value="1" />
<property name="linesCountAfterNamespace" value="1" />
</properties>
</rule>
<!-- Require empty lines around use statements -->
<rule ref="SlevomatCodingStandard.Namespaces.UseSpacing">
<properties>
<property name="linesCountBeforeFirstUse" value="1" />
<property name="linesCountBetweenUseTypes" value="0" />
<property name="linesCountAfterLastUse" value="1" />
</properties>
</rule>
</ruleset>

View File

@@ -0,0 +1,54 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
- regex: 'NetFront'
name: 'NetFront'
- regex: 'Edge/'
name: 'Edge'
- regex: 'Trident'
name: 'Trident'
- regex: 'Chr[o0]me/(?!1?\d\.|2[0-7]\.)'
name: 'Blink'
- regex: '(?:Apple)?WebKit'
name: 'WebKit'
- regex: 'Presto'
name: 'Presto'
- regex: 'Goanna'
name: 'Goanna'
- regex: '(?<!like )Clecko' # fork of Gecko
name: 'Clecko'
- regex: '(?<!like )Gecko'
name: 'Gecko'
- regex: 'KHTML'
name: 'KHTML'
- regex: 'NetSurf'
name: 'NetSurf'
- regex: 'Servo'
name: 'Servo'
- regex: 'Ekioh(?:Flow)?'
name: 'EkiohFlow'
- regex: 'xChaos_Arachne'
name: 'Arachne'
- regex: 'LibWeb\+LibJs'
name: 'LibWeb'
- regex: 'Maple (?!III)(\d+[.\d]+)|Maple\d{4}'
name: 'Maple'

View File

@@ -0,0 +1,146 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
- regex: 'Akregator(?:/(\d+[.\d]+))?'
name: 'Akregator'
version: '$1'
url: 'http://userbase.kde.org/Akregator'
- regex: 'Apple-PubSub(?:/(\d+[.\d]+))?'
name: 'Apple PubSub'
version: '$1'
url: 'https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/pubsub.1.html'
- regex: 'BashPodder'
name: 'BashPodder'
version: ''
url: 'http://lincgeek.org/bashpodder/'
- regex: 'Breaker/v?([\d.]+)'
name: 'Breaker'
version: '$1'
url: 'https://www.breaker.audio/'
- regex: 'FeedDemon(?:/(\d+[.\d]+))?'
name: 'FeedDemon'
version: '$1'
url: 'http://www.feeddemon.com/'
- regex: 'Feeddler(?:RSS|PRO)(?:[/ ](\d+[.\d]+))?'
name: 'Feeddler RSS Reader'
version: '$1'
url: 'http://www.chebinliu.com/projects/iphone/feeddler-rss-reader/'
- regex: 'QuiteRSS(?:[/ ](\d+[.\d]+))?'
name: 'QuiteRSS'
version: '$1'
url: 'https://quiterss.org'
- regex: 'gPodder/([\d.]+)'
name: 'gPodder'
version: '$1'
url: 'http://gpodder.org/'
- regex: 'JetBrains Omea Reader(?:[/ ](\d+[.\d]+))?'
name: 'JetBrains Omea Reader'
version: '$1'
url: 'http://www.jetbrains.com/omea/reader/'
- regex: 'Liferea(?:[/ ](\d+[.\d]+))?'
name: 'Liferea'
version: '$1'
url: 'http://liferea.sf.net/'
- regex: '(?:NetNewsWire|Evergreen.+MacOS)(?:[/ ](\d+[.\d]+))?'
name: 'NetNewsWire'
version: '$1'
url: 'http://netnewswireapp.com/'
- regex: 'NewsBlur (?:iPhone|iPad) App(?: v(\d+[.\d]+))?'
name: 'NewsBlur Mobile App'
version: '$1'
url: 'http://www.newsblur.com'
- regex: 'NewsBlur(?:/(\d+[.\d]+))'
name: 'NewsBlur'
version: '$1'
url: 'http://www.newsblur.com'
- regex: 'newsbeuter(?:[/ ](\d+[.\d]+))?'
name: 'Newsbeuter'
version: '$1'
url: 'http://www.newsbeuter.org/'
- regex: 'PritTorrent/([\d.]+)'
name: 'PritTorrent'
version: '$1'
url: 'http://bitlove.org'
- regex: 'Pulp[/ ](\d+[.\d]+)'
name: 'Pulp'
version: '$1'
url: 'http://www.acrylicapps.com/pulp/'
- regex: 'ReadKit(?:[/ ](\d+[.\d]+))?'
name: 'ReadKit'
version: '$1'
url: 'http://readkitapp.com/'
- regex: 'Reeder[/ ](\d+[.\d]+)'
name: 'Reeder'
version: '$1'
url: 'http://reederapp.com/'
- regex: 'RSSBandit(?:[/ ](\d+[.\d]+))?'
name: 'RSS Bandit'
version: '$1'
url: 'http://www.rssbandit.org)'
- regex: 'RSS Junkie(?:[/ ](\d+[.\d]+))?'
name: 'RSS Junkie'
version: '$1'
url: 'https://play.google.com/store/apps/details?id=com.bitpowder.rssjunkie'
- regex: 'RSSOwl(?:[/ ](\d+[.\d]+))?'
name: 'RSSOwl'
version: '$1'
url: 'https://www.rssowl.org/'
- regex: 'Stringer'
name: 'Stringer'
version: ''
url: 'https://github.com/swanson/stringer'
- regex: '^castero (\d+\.[.\d]+)'
name: 'castero'
version: '$1'
url: 'https://github.com/xgi/castero'
- regex: '^castget (\d+\.[.\d]+)'
name: 'castget'
version: '$1'
url: 'https://castget.johndal.com/'
- regex: '^Newsboat/([a-z\d\.]+)'
name: 'Newsboat'
version: '$1'
url: 'https://newsboat.org/index.html'
- regex: '^Playapod(?: Lite)?/(\d+\.[.\d]+)'
name: 'Playapod'
version: '$1'
url: 'https://playapod.com/'
- regex: 'PodPuppy (\d+\.[.\d]+)'
name: 'PodPuppy'
version: '$1'
url: 'https://github.com/felixwatts/PodPuppy'
- regex: '^Reeder/([\d.]+)'
name: 'Reeder'
version: '$1'
url: 'https://reederapp.com/'

View File

@@ -0,0 +1,166 @@
# Apps
'org.telegram.messenger': 'Telegram'
'org.telegram.messenger.web': 'Telegram'
'com.snapchat.android': 'Snapchat'
'info.sunista.app': 'Sanista Persian Instagram'
'com.instapro.app': 'InstaPro'
'com.tencent.mm': 'WeChat'
'com.kakao.talk': 'KakaoTalk'
'com.ayoba.ayoba': 'Ayoba'
'snapu2b.com': 'SnapU2B'
'com.facebook.katana': 'Facebook'
'com.facebook.orca': 'Facebook Messenger'
'com.yahoo.onesearch': 'Yahoo OneSearch'
'jp.co.yahoo.android.yjtop': 'Yahoo! Japan'
'it.ideasolutions.kyms': 'KYMS - Keep Your Media Safe'
'it.tolelab.fvd': 'FVD - Free Video Downloader'
'kik.android': 'Kik'
'com.tinder': 'Tinder'
'com.videochat.livu': 'LivU'
'io.metamask': 'MetaMask'
'com.totalav.android': 'TotalAV'
'com.fsecure.ms.saunalahti_m': 'Elisa Turvapaketti'
'com.fsecure.ms.ziggo': 'Ziggo Safe Online'
'com.aol.mobile.aolapp': 'AOL'
'com.fancyclean.security.antivirus': 'Fancy Security'
'com.google.android.gms': 'Google Play'
'com.appsinnova.android.keepclean': 'KeepClean'
'com.turtc': 'TurTc'
'com.sony.nfx.app.sfrc': 'News Suite by Sony'
'com.rcplatform.livechat': 'Tumile'
'jp.gocro.smartnews.android': 'SmartNews'
'com.lenovo.anyshare.gps': 'SHAREit'
'com.espn.score_center': 'ESPN'
'com.active.cleaner': 'Active Cleaner'
'com.hld.anzenbokusucal': 'Calculator Photo Vault'
'com.hld.anzenbokusufake': 'Calculator Hide Photos'
'com.hld.anzenbokusu': 'Sgallery'
'com.huawei.appmarket': 'AppGallery'
'com.michatapp.im': 'MiChat'
'com.michatapp.im.lite': 'MiChat Lite'
'com.noxgroup.app.security': 'Nox Security'
'phone.cleaner.antivirus.speed.booster': 'Super Cleaner'
'com.yy.hiyo': 'Hago'
'com.instagram.android': 'Instagram'
'com.instagram.barcelona': 'Threads'
'com.microsoft.office.outlook': 'Microsoft Outlook'
'com.microsoft.bing': 'Microsoft Bing'
'com.microsoft.bingintl': 'Microsoft Bing'
'com.nhn.android.search': 'Naver'
'com.jb.security': 'GO Security'
'com.fsecure.ms.safe': 'F-Secure SAFE'
'com.jaumo': 'Jaumo'
'com.jaumo.prime': 'Jaumo Prime'
'com.skout.android': 'SKOUT'
'com.hornet.android': 'Hornet'
'com.fsecure.ms.darty': 'Darty Sécurité'
'com.fsecure.ms.dc': 'F-Secure Mobile Security'
'com.fsecure.ms.swisscom.sa': 'Swisscom Internet Security'
'com.andrewshu.android.reddit': 'Reddit is fun'
'com.andrewshu.android.redditdonation': 'Reddit is fun'
'org.quantumbadger.redreader': 'RedReader'
'com.sina.weibo': 'Sina Weibo'
'com.wiseplay': 'Wiseplay'
'com.fsecure.ms.nifty': 'Always Safe Security 24'
'com.zeebusiness.news': 'Zee Business'
'com.awesapp.isp': 'iSafePlay'
'com.baidu.searchbox': 'Baidu Box App'
'hesoft.T2S': 'T2S'
'hippeis.com.photochecker': 'Photo Sherlock'
'com.thinkfree.searchbyimage': 'Reverse Image Search'
'com.tct.launcher': 'Joy Launcher'
'com.tcl.live': 'TCL Live'
'com.harshad.someto': 'Social Media Explorer'
'com.reddit.frontpage': 'Reddit'
'com.opera.app.news': 'Opera News'
'com.palmteam.imagesearch': 'Search By Image'
'com.sharekaro.app': 'ShareKaro'
'com.til.timesnews': 'NewsPoint'
'com.transsion.XOSLauncher': 'XOS Launcher'
'com.transsion.hilauncher': 'HiOS Launcher'
'com.transsion.itel.launcher': 'itel Launcher'
'com.twitter.android': 'Twitter'
'com.waze': 'Waze'
'com.tuya.smartlife': 'Tuya Smart Life'
'com.cleanmaster.mguard': 'Clean Master'
'com.cleanmaster.mguard.huawei': 'Clean Master'
'de.twokit.castbrowsernexusplayer': 'TV Cast'
'de.twokit.video.tv.cast.browser.firetv': 'TV Cast'
'de.twokit.video.tv.cast.browser.lg': 'TV Cast'
'de.twokit.video.tv.cast.browser.samsung': 'TV Cast'
'com.cleanmaster.security': 'CM Security'
'com.antivirus.master.cmsecurity': 'CM Security'
'idm.video.free': 'IDM Video Download Manager'
'mobi.deallauncher.coupons.shopping': 'Coupons & Deals'
'com.wukongtv.wkcast.intl': 'Quick Cast'
'com.tt.android.dm.view': 'Download Manager'
'com.fsecure.ms.kpn.veilig': 'KPN Veilig'
'com.fsecure.ms.actshield': 'ACT Shield'
'com.fsecure.ms.talktalksa': 'TalkTalk SuperSafe'
'com.fsecure.ms.dnafi': 'DNA Digiturva'
'com.fsecure.ms.teliasweden': 'Telia Trygg'
'com.fsecure.ms.upc.ch': 'UPC Internet Security'
'com.fsecure.ms.sfr': 'SFR Sécurité'
'com.fsecure.ms.sonera': 'Telia Turvapaketti'
'com.bifrostwallet.app': 'Bifrost Wallet'
'com.anydesk.anydeskandroid': 'AnyDesk Remote Desktop'
'com.google.android.youtube': 'YouTube'
'io.bluewallet.bluewallet': 'BlueWallet'
'com.google.android.apps.searchlite': 'Google Go'
'com.snaptube.premium': 'SnapTube'
'com.myhomescreen.sms': 'Messenger Home'
'com.myhomescreen.email': 'Email Home'
'com.myhomescreen.weather': 'Weather Home'
'com.myhomescreen.access': 'Big Keyboard'
'com.myhomescreen.messenger.home.emoji.lite': 'Messenger Lite'
'com.myhomescreen.fitness': 'Fit Home'
'com.myhomescreen.news': 'News Home'
'com.amazon.webapps.gms.search': 'Google Search App'
'com.huawei.fastapp': 'Huawei Quick App Center'
'com.flatfish.cal.privacy': 'HideX'
'com.sweep.cleaner.trash.junk': 'Sweep'
'com.google.android.apps.maps': 'Google Maps'
'com.box.video.downloader': 'BOX Video Downloader'
'com.oxoo.kinogo': 'Kinogo.ge'
'com.tradron.hdvideodownloader': 'Download Hub'
'net.daum.android.daum': 'Daum'
'com.massimple.nacion.gcba.es': '+Simple'
'com.massimple.nacion.parana.es': '+Simple'
'com.microsoft.math': 'Microsoft Math Solver'
'com.instabridge.android': 'Instabridge'
'com.repotools.whatplay': 'Whatplay'
'com.saf.seca': 'SearchCraft'
'com.huawei.hwsearch': 'Petal Search'
'com.playit.videoplayer': 'PLAYit'
'com.droidlogic.xlauncher': 'X Launcher'
'nu.bi.moya': 'Moya'
'com.microsoft.copilot': 'Microsoft Copilot'
'com.nate.android.portalmini': 'nate'
'za.co.tracker.consumer': 'Tracker Connect'
'com.larus.wolf': 'Cici'
'com.qihoo.security': '360 Security'
'com.infinix.xshare': 'XShare'
'com.transsion.magicshow': 'Visha'
'com.bigqsys.photosearch.searchbyimage2020': 'Photo Search'
'com.stickypassword.android': 'Sticky Password'
'com.nytimes.crossword': 'The Crossword'
'castify.roku': 'Castify'
'com.castify': 'Castify'
'mojeek.app': 'Mojeek'
'org.aka.messenger': 'Aka Messenger'
'org.aka.lite': 'Aka Messenger Lite'
'the.best.gram': 'Bestgram'
'ir.ilmili.telegraph': 'Graph Messenger'
# Vpns
'org.torproject.android': 'Orbot'
'free.vpn.unblock.proxy.vpnmonster': 'VPN Monster'
'com.udicorn.proxy': 'Blue Proxy'
'com.v2.vpn.security.free': 'V2Free'
'com.surfshark.vpnclient.android': 'Surfshark'
'com.omshyapps.vpn': 'Omshy VPN'
'com.kuto.vpn': 'KUTO VPN'
'com.ezt.vpn': 'EZVPN'
'com.nocardteam.nocardvpn': 'NoCard VPN'
'com.nocardteam.nocardvpn.lite': 'NoCard VPN Lite'

View File

@@ -0,0 +1,326 @@
# Browsers
'mark.via.gg': 'Via'
'mark.via.gp': 'Via'
'mark.via.gq': 'Via'
'mark.via.pm': 'Via'
'mark.viah': 'Via'
'com.pure.mini.browser': 'Pure Mini Browser'
'pure.lite.browser': 'Pure Lite Browser'
'acr.browser.Hexa': 'Hexa Web Browser'
'acr.browser.raisebrowserfull': 'Raise Fast Browser'
'acr.tez.browse': 'Browspeed Browser'
'com.Fast.BrowserUc.lite': 'Fast Browser UC Lite'
'acr.browser.barebones': 'Lightning Browser'
'anar.app.darkweb': 'Dark Web Browser'
'com.darkbrowser': 'Dark Browser'
'com.kiwibrowser.browser': 'Kiwi'
'com.cloudmosa.puffinFree': 'Puffin Web Browser'
'com.cloudmosa.puffin': 'Puffin Web Browser' # or Puffin Web Browser Pro
'com.cloudmosa.puffinIncognito': 'Puffin Incognito Browser'
'com.cloudmosa.puffinCloudBrowser': 'Puffin Cloud Browser'
'com.aloha.browser': 'Aloha Browser'
'com.cake.browser': 'Cake Browser'
'com.UCMobile.intl': 'UC Browser'
'com.iebrowser.fast': 'IE Browser Fast'
'com.internet.browser.secure': 'Internet Browser Secure'
'acr.browser.linxy': 'Vegas Browser'
'com.oh.bro': 'OH Browser'
'com.oh.brop': 'OH Private Browser'
'com.duckduckgo.mobile.android': 'DuckDuckGo Privacy Browser'
'net.onecook.browser': 'Stargon'
'com.mi.globalbrowser.mini': 'Mint Browser'
'com.hisense.odinbrowser': 'Odin Browser'
'com.brave.browser': 'Brave'
'com.brave.browser_beta': 'Brave'
'org.mozilla.klar': 'Firefox Klar'
'phx.hot.browser': 'Anka Browser'
'com.anka.browser': 'Anka Browser'
'org.mozilla.focus': 'Firefox Focus'
'org.mozilla.tv.firefox': 'Firefox Focus'
'com.vivaldi.browser': 'Vivaldi'
'web.browser.dragon': 'Dragon Browser'
'org.easyweb.browser': 'Easy Browser'
'com.xbrowser.play': 'XBrowser Mini'
'com.sharkeeapp.browser': 'Sharkee Browser'
'com.mobiu.browser': 'Lark Browser'
'com.qflair.browserq': 'Pluma'
'com.noxgroup.app.browser': 'Nox Browser'
'com.jio.web': 'JioSphere'
'com.ume.browser.cust': 'Ume Browser'
'com.ume.browser.international': 'Ume Browser'
'com.ume.browser.bose': 'Ume Browser'
'com.ume.browser.euas': 'Ume Browser'
'com.ume.browser.latinamerican': 'Ume Browser'
'com.ume.browser.mexicotelcel': 'Ume Browser'
'com.ume.browser.venezuelavtelca': 'Ume Browser'
'com.ume.browser.northamerica': 'Ume Browser'
'com.ume.browser.newage': 'Ume Browser'
'com.kuto.browser': 'KUTO Mini Browser'
'com.dolphin.browser.zero': 'Dolphin Zero'
'mobi.mgeek.TunnyBrowser': 'Dolphin' # Dolphin + AdBlock
'nextapp.atlas': 'Atlas'
'org.mozilla.rocket': 'Firefox Rocket' # Firefox Lite
'com.mx.browser': 'Maxthon'
'com.ecosia.android': 'Ecosia'
'org.lineageos.jelly': 'Jelly'
'com.opera.gx': 'Opera GX'
'br.marcelo.monumentbrowser': 'Monument Browser'
'com.airfind.deltabrowser': 'Delta Browser'
'com.apusapps.browser': 'APUS Browser'
'com.ask.browser': 'Ask.com'
'com.browser.tssomas': 'Super Fast Browser'
'iron.web.jalepano.browser': 'SuperFast Browser'
'yuce.browser.mini': 'Ui Browser Mini'
'SavySoda.PrivateBrowsing': 'SavySoda'
'savannah.internet.web.browser': 'Savannah Browser'
'com.gl9.cloudBrowser': 'Surf Browser'
'com.ucold.browser.secure.browse': 'UC Browser Mini'
'com.mycompany.app.soulbrowser': 'Soul Browser'
'com.quickbig.browser': 'Indian UC Mini Browser' # (alternative name Splash UC Mini Browser)
'com.opera.browser': 'Opera'
'com.opera.mini.native': 'Opera Mini'
'com.wSilverMobBrowser': 'SilverMob US'
'com.ksmobile.cb': 'CM Browser'
'com.cmcm.armorfly': 'Armorfly Browser'
'org.mini.freebrowser': 'CM Mini'
'com.anc.web.browser': 'Comfort Browser'
'fast.explorer.web.browser': 'Fast Explorer'
'net.soti.surf': 'SOTI Surf'
'com.lexi.browser': 'Lexi Browser'
'com.browser.pintar': 'Smart Browser'
'com.belva.browser': 'Belva Browser'
'com.belva.safe.browser': 'Belva Browser'
'com.youcare.browser': 'YouCare'
'org.lilo.mobile.android2020': 'Lilo'
'com.opera.cryptobrowser': 'Opera Crypto'
'AlohaBrowser': 'Aloha Browser'
'mark.via': 'Via'
'com.xpp.floatbrowser': 'Float Browser'
'com.kiddoware.kidsafebrowser': 'Kids Safe Browser'
'com.hideitpro.vbrowser': 'vBrowser'
'com.cgbrowser.rn': 'CG Browser'
'com.azka.browser.anti.blokir': 'Azka Browser'
'com.azka.browser': 'Azka Browser'
'com.micromaxinfo.browser': 'Mmx Browser'
'com.zeesitech.bitchutebrowser': 'Bitchute Browser'
'nova.all.video.downloader': 'Nova Video Downloader Pro'
'tukidev.pronhubbrowser.tanpavpn': 'PronHub Browser'
'com.crowbar.beaverlite': 'Frost'
'com.crowbar.beaverbrowser': 'Frost+'
'com.lenovo.browser': 'Lenovo Browser'
'com.transsion.phoenix': 'Phoenix Browser'
'quick.browser.secure': 'Quick Browser'
'com.asus.browser': 'Asus Browser'
'com.opera.touch': 'Opera Touch'
'com.ghostery.android.ghostery': 'Ghostery Privacy Browser'
'com.oceanhero.search': 'OceanHero'
'com.mebrowser.webapp': 'Me Browser'
'info.plateaukao.einkbro': 'EinkBro'
'com.fevdev.nakedbrowser': 'Naked Browser'
'com.fevdev.nakedbrowserlts': 'Naked Browser'
'com.fevdev.nakedbrowserpro': 'Naked Browser Pro'
'com.yasirshakoor.ducbrowser': 'DUC Browser'
'com.wDesiBrowser_13255326': 'Desi Browser'
'com.huawei.browser': 'Huawei Browser Mobile'
'com.phantom.me': 'Phantom.me'
'com.opera.mini.android': 'Opera Mini'
'jp.ejimax.berrybrowser': 'Berry Browser'
'com.fulldive.mobile': 'Fulldive'
'com.talpa.hibrowser': 'Hi Browser'
'org.midorinext.android': 'Midori Lite'
'reactivephone.msearch': 'Smart Search & Web Browser'
'com.sibimobilelab.amazebrowser': 'Amaze Browser'
'com.alohamobile.browser.lite': 'Aloha Browser Lite'
'com.tcl.browser': 'BrowseHere'
'com.seraphic.openinet.pre': 'Open Browser'
'com.seraphic.openinet.cvte': 'Open Browser'
'privatebrowser.securebrowser.com.klar': 'Secure Private Browser'
'in.pokebbrowser.bukablokirsitus': 'HUB Browser'
'com.wOpenBrowser_12576500': 'Open Browser fast 5G'
'com.wOpenbrowser_13506467': 'Open Browser 4U'
'com.MaxTube.browser': 'MaxTube Browser'
'com.ninexgen.chowbo': 'Chowbo'
'net.pertiller.debuggablebrowser': 'Debuggable Browser'
'com.appssppa.idesktoppcbrowser': 'iDesktop PC Browser'
'pi.browser': 'Pi Browser'
'com.xooloo.internet': 'Xooloo Internet'
'com.u_browser': 'U Browser'
'ai.blokee.browser.android': 'Bloket'
'com.vast.vpn.proxy.unblock': 'Vast Browser'
'com.security.xvpn.z35kb': 'X-VPN'
'com.security.xvpn.z35kb.amazon': 'X-VPN'
'com.security.xvpn.z35kb.huawei': 'X-VPN'
'com.yandex.browser.lite': 'Yandex Browser Lite'
'com.yandex.browser.beta': 'Yandex Browser'
'com.yandex.browser.alpha': 'Yandex Browser'
'cz.seznam.sbrowser': 'Seznam Browser'
'com.morrisxar.nav88': 'Office Browser'
'com.rabbit.incognito.browser': 'Rabbit Private Browser'
'arun.com.chromer': 'Lynket Browser'
'jp.hazuki.yuzubrowser': 'Yuzu Browser'
'com.swiftariel.browser.cherry': 'Cherry Browser'
'id.browser.vivid3': 'Vivid Browser Mini'
'com.browser.yo.indian': 'Yo Browser'
'com.mercandalli.android.browser': 'G Browser'
'com.bf.browser': 'BXE Browser'
'com.qihoo.browser': '360 Secure Browser'
'com.qihoo.contents': '360 Secure Browser'
'com.qihoo.haosou': '360 Secure Browser'
'com.qihoo.padbrowser': '360 Secure Browser'
'com.qihoo.sonybrowser': '360 Secure Browser'
'org.zirco': 'Zirco Browser'
'org.tint': 'Tint Browser'
'com.skyfire.browser': 'Skyfire'
'com.sonymobile.smallbrowser': 'Sony Small Browser'
'org.hola': 'hola! Browser'
'it.ideasolutions.amerigo': 'Amerigo'
'org.xbrowser.prosuperfast': 'xBrowser Pro Super Fast'
'org.plus18.android': '18+ Privacy Browser'
'com.beyond.privatebrowser': 'Beyond Private Browser'
'com.blacklion.browser': 'Black Lion Browser'
'com.opera.mini.native.ShonizME': 'Opera Mini'
'com.tuc.mini.st': 'TUC Mini Browser'
'com.roidtechnologies.appbrowzer': 'AppBrowzer'
'com.futuristic.sx': 'SX Browser'
'hot.fiery.browser': 'Fiery Browser'
'in.nismah.yagi': 'YAGI'
'com.apn.mobile.browser.cherry': 'APN Browser'
'com.apn.mobile.browser.umeatt': 'APN Browser'
'com.apn.mobile.browser.zte': 'APN Browser'
'com.tencent.mtt': 'QQ Browser'
'com.wordly.translate.browser': 'NextWord Browser'
'idm.internet.download.manager': '1DM Browser'
'idm.internet.download.manager.plus': '1DM+ Browser'
'com.veeraapps.newadult': 'Adult Browser'
'com.xnxbrowser.rampage': 'XNX Browser'
'com.xtremecast': 'XtremeCast'
'com.xvideobrowserlite.xvideoDownloaderbrowserlite': 'X Browser Lite'
'com.xxnxx.browser.proxy.vpn': 'xBrowser'
'com.sweetbrowser.ice': 'Sweet Browser'
'com.mcent.browser': 'mCent'
'com.htc.sense.browser': 'HTC Browser'
'com.browlser': 'Browlser'
'app.browserhub.download': 'Browser Hup Pro'
'com.flyperinc.flyperlink': 'Flyperlink'
'com.w3engineers.banglabrowser': 'Bangla Browser'
'com.coccoc.trinhduyet': 'Coc Coc'
'com.browser.explore': 'Explore Browser'
'com.microsoft.emmx': 'Microsoft Edge'
'com.explore.web.browser': 'Web Browser & Explorer'
'privacy.explorer.fast.safe.browser': 'Privacy Explorer Fast Safe'
'app.soundy.browser': 'Soundy Browser'
'com.ivvi.browser': 'IVVI Browser'
'com.nomone.vrbrowser': 'NOMone VR Browser'
'com.opus.browser': 'Opus Browser'
'com.arvin.browser': 'Arvin'
'com.pawxy.browser': 'Pawxy'
'com.internet.tvbrowser': 'LUJO TV Browser'
'com.logicui.tvbrowser2': 'LogicUI TV Browser'
'com.opera.browser.afin': 'Opera'
'com.opera.browser.beta': 'Opera'
'com.quark.browser': 'Quark'
'jp.co.yahoo.android.ybrowser': 'Yahoo! Japan Browser'
'com.tv.browser.open': 'Open TV Browser'
'com.ornet.torbrowser': 'OrNET Browser'
'com.browsbit': 'BrowsBit'
'org.mozilla.firefox': 'Firefox Mobile'
'com.yandex.browser': 'Yandex Browser'
'com.opera.mini.native.beta': 'Opera Mini'
'com.sec.android.app.sbrowser': 'Samsung Browser'
'com.sec.android.app.sbrowser.lite': 'Samsung Browser Lite'
'com.browser.elmurzaev': 'World Browser'
'every.browser.inc': 'Every Browser'
'com.mi.globalbrowser': 'Mi Browser'
'nu.tommie.inbrowser': 'InBrowser'
'com.insta.browser': 'Insta Browser'
'com.alohamobile.vertexsurf': 'Vertex Surf'
'com.hollabrowser.meforce': 'Holla Web Browser'
'org.torbrowser.torproject': 'Tor Browser'
'org.torproject.torbrowser': 'Tor Browser'
'com.marslab.browserz': 'MarsLab Web Browser'
'com.mini.web.browser': 'Sunflower Browser'
'com.cavebrowser': 'Cave Browser'
'com.zordo.browser': 'Zordo Browser'
'freedom.theanarch.org.freedom': 'Freedom Browser'
'com.lechneralexander.privatebrowser': 'Private Internet Browser'
'com.airfind.browser': 'Airfind Secure Browser'
'com.securex.browser': 'SecureX'
'com.sec.android.app.sbrowser.beta': 'Samsung Browser'
'threads.thor': 'Thor'
'com.androidbull.incognito.browser': 'Incognito Browser'
'com.mosoft.godzilla': 'Godzilla Browser'
'com.oceanbrowser.mobile.android': 'Ocean Browser'
'com.qmamu.browser': 'Qmamu'
'com.techlastudio.bfbrowser': 'BF Browser'
'com.befaster.bfbrowser': 'BF Browser'
'app.nextinnovations.brokeep': 'BroKeep Browser'
'org.lilo.app': 'Lilo'
'proxy.browser.unblock.sites.proxybrowser.unblocksites': 'Proxy Browser'
'com.hotsurf.browser': 'HotBrowser'
'vpn.video.downloader': 'VD Browser'
'com.aospstudio.tvsearch': 'Quick Search TV'
'com.go.browser': 'GO Browser'
'com.apgsolutionsllc.APGSOLUTIONSLLC0007': 'Basic Web Browser'
'com.phlox.tvwebbrowser': 'TV Bro'
'com.lovense.vibemate': 'VibeMate'
'dev.sect.lotus.browser.videoapp': 'Lotus'
'com.qjy.browser': 'QJY TV Browser' # http://www.qianjiayue.com/new/?c=index&a=show&id=100
'com.airwatch.browser': 'VMware AirWatch'
'com.microsoft.intune.mam.managedbrowser': 'Intune Managed Browser'
'com.tencent.bang': 'Bang'
'com.outcoder.browser': 'Surfy Browser'
'ginxdroid.gdm': 'GinxDroid Browser'
'on.browser': 'OnBrowser Lite'
'com.pico.browser.overseas': 'PICO Browser'
'com.cliqz.browser': 'Cliqz'
'org.hola.prem': 'hola! Browser'
'com.baidu.browser.inter': 'Baidu Browser'
'org.torproject.torbrowser_alpha': 'Tor Browser'
'com.ilegendsoft.mercury': 'Mercury'
'com.apn.mobile.browser.coolpad': 'APN Browser'
'com.apn.mobile.browser.infosonics': 'APN Browser'
'net.dezor.browser': 'Dezor'
'com.involta.involtago': 'Involta Go'
'jp.ddo.pigsty.HabitBrowser': 'Habit Browser'
'org.browser.owl': 'Owl Browser'
'com.orbitum.browser': 'Orbitum'
'com.appsverse.photon': 'Photon'
'fr.agrange.bbbrowser': 'Keyboard Browser'
'com.stealthmobile.browser': 'Stealth Browser'
'com.wcd.talkto': 'TalkTo'
'com.foxylab.airfox': 'Proxynet'
'io.github.mthli.goodbrowser': 'Good Browser'
'app.proxyiumbrowser.android': 'Proxyium'
'com.vuhuv': 'Vuhuv'
'com.fast.fireBrowser': 'Fire Browser'
'acr.browser.lightning': 'Lightning Browser Plus'
'birapp.dark.web': 'Dark Web'
'birapp.dark.web.private': 'Dark Web Private'
'com.hihonor.baidu.browser': 'HONOR Browser'
'com.browser.pintar.vpn': 'Pintar Browser'
'com.ucimini.internetbrowser': 'Browser Mini'
'de.baumann.browser': 'FOSS Browser'
'com.oversea.mybrowser': 'Peach Browser'
'com.apptec360.android.browser': 'AppTec Secure Browser'
'com.ojr.browser.anti.blokir': 'OJR Browser'
'com.vworldc.tusk': 'TUSK'
'com.stoutner.privacybrowser.standard': 'Privacy Browser'
'com.techlastudio.proxyfoxbrowser': 'ProxyFox'
'com.vielianztlabs.browser': 'ProxyMax'
'com.keepsolid.privatebrowser': 'KeepSolid Browser'
'com.onionsearchengine.focus': 'ONIONBrowser'
'com.best.quick.browser': 'Ai Browser'
'miada.tv.webbrowser': 'Internet Webbrowser'
'com.kaweapp.webexplorer': 'Web Explorer'
'com.halo.browser': 'Halo Browser'
'com.mmbox.xbrowser': 'MMBOX XBrowser'
'com.tvwebbrowser.v22': 'TV-Browser Internet'
'com.tvwebbrowserpaid.v22': 'TV-Browser Internet'
'xnx.browser.browse.Xnxnewx': 'XnBrowse'
'com.metax.browser': 'Open Browser Lite'
'com.getkeepsafe.browser': 'Keepsafe Browser'
'com.hawk.android.browser': 'Hawk Turbo Browser'
'com.zte.nubrowser': 'ZTE Browser'
'com.cloaktp.browser': 'Privacy Pioneer Browser'
'company.thebrowser.arc': 'Arc Search'
'com.android.webview': 'Chrome Webview'

View File

@@ -0,0 +1,701 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
- regex: 'PhantomJS(?:/(\d+[.\d]+))?'
name: 'PhantomJS'
version: '$1'
url: 'https://phantomjs.org/'
- regex: 'IPinfoClient/.*/(\d+[.\d]+)'
name: 'IPinfo'
version: '$1'
url: 'https://github.com/ipinfo'
- regex: 'kiwi-tcms/(\d+[.\d]+)'
name: 'Kiwi TCMS'
version: '$1'
url: 'https://kiwitcms.org'
- regex: 'tcms-api/(\d+[.\d]+)'
name: 'Kiwi TCMS API'
version: '$1'
url: 'https://kiwitcms.org'
- regex: 'Fuzz Faster U Fool v(\d+[.\d]+)'
name: 'FFUF'
version: '$1'
url: 'https://github.com/ffuf/ffuf'
- regex: 'Slim Framework'
name: 'Slim Framework'
version: ''
url: 'https://www.slimframework.com/'
- regex: 'msray-plus'
name: 'Msray-Plus'
version: ''
url: 'https://github.com/super-l/msray'
- regex: 'HTMLParser(?:/(\d+[.\d]+))?'
name: 'HTML Parser'
version: '$1'
url: 'https://htmlparser.sourceforge.net/'
# got - a nodejs library
- regex: '^got(?:/(\d+\.[.\d]+))? \('
name: 'got'
version: '$1'
url: 'https://github.com/sindresorhus/got'
# Typhoeus
- regex: 'Typhoeus'
name: 'Typhoeus'
version: ''
url: 'https://github.com/typhoeus/typhoeus'
# req
- regex: 'req/v([.\d]+)'
name: 'req'
version: '$1'
url: 'https://github.com/imroc/req'
# quic-go
- regex: 'quic-go[ -]HTTP/3'
name: 'quic-go'
version: ''
url: 'https://github.com/lucas-clemente/quic-go'
# Azure Data Factory
- regex: 'azure-data-factory(?:/(\d+[.\d]+))?'
name: 'Azure Data Factory'
version: '$1'
url: 'https://azure.microsoft.com/en-us/products/data-factory/'
# Dart
- regex: 'Dart/(\d+[.\d]+)'
name: 'Dart'
version: '$1'
url: 'https://dart.dev/'
# r-curl
- regex: 'r-curl(?:/(\d+[.\d]+))?'
name: 'r-curl'
version: '$1'
url: 'https://github.com/jeroen/curl'
# HTTPX
- regex: 'python-httpx(?:/(\d+[.\d]+))?'
name: 'HTTPX'
version: '$1'
url: 'https://www.python-httpx.org/'
# fasthttp
- regex: 'fasthttp(?:/(\d+[.\d]+))?'
name: 'fasthttp'
version: '$1'
url: 'https://github.com/valyala/fasthttp'
# GeoIP Update
- regex: 'geoipupdate(?:/(\d+[.\d]+))?'
name: 'GeoIP Update'
version: '$1'
url: 'https://github.com/maxmind/geoipupdate'
# PHP cURL Class
- regex: 'PHP-Curl-Class(?:/(\d+[.\d]+))?'
name: 'PHP cURL Class'
version: '$1'
url: 'https://github.com/php-curl-class/php-curl-class'
# cPanel HTTP Client
- regex: 'Cpanel-HTTP-Client(?:/(\d+[.\d]+))?'
name: 'cPanel HTTP Client'
version: '$1'
url: 'https://www.cpanel.net/'
# AnyEvent HTTP
- regex: 'AnyEvent-HTTP(?:/(\d+[.\d]+))?'
name: 'AnyEvent HTTP'
version: '$1'
url: 'http://software.schmorp.de/pkg/AnyEvent'
# SlimerJS
- regex: 'SlimerJS/(\d+[.\d]+)'
name: 'SlimerJS'
version: '$1'
url: 'https://www.slimerjs.org/'
# Jaunt
- regex: 'Jaunt/(\d+[.\d]+)'
name: 'Jaunt'
version: '$1'
url: 'https://jaunt-api.com/'
# Cypress
- regex: 'Cypress/(\d+[.\d]+)'
name: 'Cypress'
version: '$1'
url: 'https://github.com/cypress-io/cypress'
- regex: 'Wget(?:/(\d+[.\d]+))?'
name: 'Wget'
version: '$1'
- regex: 'Guzzle(?:Http)?(?:/(\d+[.\d]+))?'
name: 'Guzzle (PHP HTTP Client)'
version: '$1'
# symphony php http client
- regex: '^Symfony HttpClient/'
name: 'Symfony'
version: '$1'
- regex: '(?:lib)?curl(?:/(\d+[.\d]+))?'
name: 'curl'
version: '$1'
- regex: 'python-requests(?:/(\d+[.\d]+))?'
name: 'Python Requests'
version: '$1'
- regex: 'Python-httplib2(?:/(\d+[.\d]+))?'
name: 'httplib2'
version: '$1'
url: 'https://pypi.org/project/httplib2/'
- regex: 'Python-urllib3?(?:/?(\d+[.\d]+))?'
name: 'Python urllib'
version: '$1'
- regex: 'Apache-HttpClient(?:/?(\d+[.\d]+))?'
name: 'Apache HTTP Client'
version: '$1'
- regex: 'Java-http-client(?:/?(\d+[.\d]+))?'
name: 'Java HTTP Client'
version: '$1'
- regex: 'Java/?(\d+[.\d]+)'
name: 'Java'
version: '$1'
- regex: '(?:perlclient|libwww-perl)(?:/?(\d+[.\d]+))?'
name: 'Perl'
version: '$1'
- regex: 'grpc-java-okhttp/([\d.]+)'
name: 'gRPC-Java'
version: '$1'
url: 'https://github.com/grpc/grpc-java'
# java library
- regex: '(?:okhttp|network-okhttp3)/([\d.]+)'
name: 'OkHttp'
version: '$1'
- regex: 'okhttp3-([\d.]+)'
name: 'OkHttp'
version: '$1'
- regex: 'HTTP_Request2(?:/(\d+[.\d]+))?'
name: 'HTTP_Request2'
version: '$1'
url: 'https://pear.php.net/package/http_request2'
- regex: 'Mechanize(?:/(\d+[.\d]+))?'
name: 'Mechanize'
version: '$1'
url: 'https://github.com/sparklemotion/mechanize'
- regex: 'aiohttp(?:/(\d+[.\d]+))?'
name: 'aiohttp'
version: '$1'
- regex: 'Google-HTTP-Java-Client(?:/(\d+[\.\w-]+))?'
name: 'Google HTTP Java Client'
version: '$1'
- regex: 'WWW-Mechanize(?:/(\d+[.\d]+))?'
name: 'WWW-Mechanize'
version: '$1'
- regex: 'Faraday(?: v(\d+[.\d]+))?'
name: 'Faraday'
version: '$1'
url: 'https://github.com/lostisland/faraday'
- regex: '(?:Go-http-client|^Go )/?(?:(\d+[.\d]+))?(?: package http)?'
name: 'Go-http-client'
version: '$1'
- regex: 'urlgrabber(?:/(\d+[.\d]+))?'
name: 'urlgrabber (yum)'
version: '$1'
- regex: 'libdnf(?:/(\d+[.\d]+))?'
name: 'libdnf'
version: '$1'
- regex: 'HTTPie(?:/(\d+[.\d]+))?'
name: 'HTTPie'
version: '$1'
- regex: 'rest-client/(\d+\.[.\d]+) .*ruby'
name: 'REST Client for Ruby'
version: '$1'
- regex: 'RestSharp/(\d+[.\d]+)'
name: 'RestSharp'
version: '$1'
url: 'https://github.com/restsharp/RestSharp'
- regex: 'scalaj-http/(\d+[.\d]+)'
name: 'ScalaJ HTTP'
version: '$1'
url: 'https://github.com/scalaj/scalaj-http'
- regex: 'REST::Client/(\d+)'
name: 'Perl REST::Client'
version: '$1'
url: 'https://metacpan.org/pod/REST::Client'
- regex: 'node-fetch/?(\d+[.\d]+)?'
name: 'Node Fetch'
version: '$1'
url: 'https://github.com/node-fetch/node-fetch'
- regex: 'electron-fetch/?(\d+[.\d]+)?'
name: 'Electron Fetch'
version: '$1'
url: 'https://github.com/arantes555/electron-fetch'
- regex: 'ReactorNetty/(\d+[.\d]+)'
name: 'ReactorNetty'
version: '$1'
url: 'https://github.com/reactor/reactor-netty'
- regex: 'PostmanRuntime(?:/(\d+[.\d]+))?'
name: 'Postman Desktop'
version: '$1'
url: 'https://github.com/postmanlabs/postman-runtime'
- regex: 'insomnia(?:/(\d+[.\d]+))?'
name: 'Insomnia REST Client'
version: '$1'
url: 'https://insomnia.rest'
- regex: 'Jakarta Commons-HttpClient/([.\d]+)'
name: 'Jakarta Commons HttpClient'
version: '$1'
url: 'https://hc.apache.org/httpclient-3.x'
- regex: 'WinHttp\.WinHttpRequest.+([.\d]+)'
name: 'WinHttp WinHttpRequest'
version: '$1'
- regex: 'WinHTTP'
name: 'Windows HTTP'
version: ''
# THTTPClient in delphi 10+ default useragent
- regex: 'Embarcadero URI Client/([.\d]+)'
name: 'Embarcadero URI Client'
version: '$1'
- regex: 'Mikrotik/([.\d]+)'
name: 'Mikrotik Fetch'
version: '$1'
- regex: 'GRequests(?:/(\d+[.\d]+))?'
name: 'GRequests'
version: '$1'
# https://doc.akka.io/
- regex: 'akka-http/([.\d]+)'
name: 'Akka HTTP'
version: '$1'
# this added need added tests
- regex: 'aria2(?:/(\d+[.\d]+))?'
name: 'Aria2'
version: '$1'
- regex: '(?:BTWebClient/|^uTorrent/)'
name: 'uTorrent'
version: ''
- regex: 'gvfs/(?:(\d+[.\d]+))?'
name: 'gvfs'
version: '$1'
# https://openwrt.org/packages/pkgdata/uclient-fetch
- regex: 'uclient-fetch'
name: 'uclient-fetch'
version: ''
# https://github.com/microsoft/cpprestsdk
- regex: 'cpprestsdk/([.\d]+)'
name: 'C++ REST SDK'
version: '$1'
- regex: 'lua-resty-http/([.\d]+).+ngx_'
name: 'LUA OpenResty NGINX'
version: '$1'
# https://github.com/Kong/unirest-java
- regex: 'unirest-java/([.\d]+)'
name: 'Unirest for Java'
version: '$1'
# jsdom (https://github.com/jsdom/jsdom)
- regex: 'jsdom/([.\d]+)'
name: 'jsdom'
version: '$1'
# hackney (https://github.com/benoitc/hackney) (elixir)
- regex: 'hackney/([.\d]+)'
name: 'hackney'
version: '$1'
# Resty (https://github.com/go-resty/resty)
- regex: 'go-resty/([.\d]+)'
name: 'Resty'
version: '$1'
# Pa11y (https://pa11y.org/)
- regex: 'pa11y/([.\d]+)'
name: 'Pa11y'
version: '$1'
# Ultimate Sitemap Parser (https://github.com/mediacloud/ultimate-sitemap-parser)
- regex: 'ultimate_sitemap_parser/([.\d]+)'
name: 'Ultimate Sitemap Parser'
version: '$1'
# Container-related useragents
# Artifactory (https://jfrog.com/de/artifactory/)
- regex: 'Artifactory/([.\d]+)'
name: 'Artifactory'
version: '$1'
# Open build service (https://build.opensuse.org/)
- regex: 'BSRPC ([.\d]+)'
name: 'Open Build Service'
version: '$1'
# Buildah (https://github.com/containers/buildah)
- regex: 'Buildah/([.\d]+)'
name: 'Buildah'
version: '$1'
# Buildkit (https://github.com/moby/buildkit)
- regex: 'buildkit/v?([.\d]+)'
name: 'BuildKit'
version: '$1'
# containerd (https://github.com/containerd/containerd)
- regex: 'containerd/v?([.\d]+)'
name: 'Containerd'
version: '$1'
# containers (https://github.com/containers/image)
- regex: 'containers/([.\d]+)'
name: 'containers'
version: '$1'
# cri-o (https://github.com/cri-o/cri-)o
- regex: 'cri-o/([.\d]+)'
name: 'cri-o'
version: '$1'
# docker (https://github.com/moby/moby)
- regex: 'docker/([.\d]+)'
name: 'docker'
version: '$1'
# gcr (https://github.com/google/go-containerregistry)
- regex: 'go-containerregistry/v([.\d]+)'
name: 'go-container registry'
version: '$1'
# libpod (https://github.com/dankohn/libpod)
- regex: 'libpod/([.\d]+)'
name: 'libpod'
version: '$1'
# skopeo (https://github.com/containers/skopeo)
- regex: 'skopeo/([.\d]+)'
name: 'Skopeo'
version: '$1'
# helm (https://github.com/helm/helm)
- regex: 'Helm/([.\d]+)'
name: 'Helm'
version: '$1'
# harbor client (https://goharbor.io/)
- regex: 'harbor-registry-client'
name: 'Harbor registry client'
version: ''
# axios http (https://axios-http.com/)
- regex: 'axios(?:/?(\d+[.\d]+))?'
name: Axios
version: '$1'
# Classier solution for file uploads for Rails, Sinatra and other Ruby web frameworks
- regex: '^CarrierWave/(\d+\.[.\d]+)'
name: 'CarrierWave'
version: '$1'
- regex: '^Deno/(\d+\.[.\d]+)'
name: 'Deno'
version: '$1'
# Streaming downloads using net/http, http.rb, HTTPX or wget (ruby)
- regex: '^Down/(\d+\.[.\d]+)'
name: 'Down'
version: '$1'
# various programs can use this, like vlc, but the underlying lib is ffmpeg
- regex: '^Lavf/'
name: 'ffmpeg'
version: '$1'
- regex: '^FileDownloader/(\d+\.[.\d]+)'
name: 'FileDownloader'
version: '$1'
# Allows managing large files with git, without storing the file contents in git
- regex: '^git-annex/(\d+\.[.\d]+)'
name: 'git-annex'
version: '$1'
- regex: '^GStreamer(?: souphttpsrc)[ /](\d+\.[.\d]+)?'
name: 'GStreamer'
version: '$1'
# A small, simple, correct HTTP/1.1 client (Perl)
- regex: '^HTTP-Tiny/(\d+\.[.\d]+)'
name: 'HTTP:Tiny'
version: '$1'
- regex: 'KaiOS Downloader'
name: 'KaiOS Downloader'
version: ''
# HTTP client/server library for GNOME
- regex: '^libsoup/(\d+\.[.\d]+)'
name: 'libsoup'
version: '$1'
- regex: '^Android\.LVLDM$'
name: 'Android License Verification Library'
version: '$1'
# A file downloader library for Android with pause and resume support
- regex: '^PRDownloader$'
name: 'PRDownloader'
version: ''
# a rust http library
- regex: '^reqwest/(\d+\.[.\d]+)'
name: 'reqwest'
version: '$1'
# lua http library
- regex: '^resty-requests'
name: 'resty-requests'
version: ''
# ruby core lib http download
- regex: '^Ruby'
name: 'ruby'
version: ''
# SFSafariViewController, some safari service
- regex: '^SafariViewService/(\d+\.[.\d]+)'
name: 'Safari View Service'
version: '$1'
# a nodejs lib
- regex: '^undici$'
name: 'undici'
version: ''
# URL, an emacs plugin
- regex: '^URL/Emacs Emacs/(\d+\.[.\d]+)'
name: 'Emacs'
version: '$1'
- regex: '^FDM[ /]([\d.]+)'
name: 'Free Download Manager'
version: '$1'
# 'https://github.com/lingochamp/okdownload'
- regex: 'OkDownload/([\d.]+)'
name: 'OKDownload Library'
version: '$1'
# podcast host https://libsyn.com (probably an importer)
- regex: '^Libsyn4-?(?:peek|download)$'
name: 'Libsyn'
version: ''
# any ios application that uses apple core media but doesn't set its user
# agent will default to this, always with 1.0.0 version.
# there was a time when (not even that long ago) apple didn't let you set
# a user agent so a ton of random applications still identify themselves this way.
- regex: 'AppleCoreMedia/1\.0\.0'
name: 'iOS Application'
version: ''
- regex: 'cpp-httplib(?:/(\d+[.\d]+))?'
name: 'cpp-httplib'
version: '$1'
url: 'https://github.com/yhirose/cpp-httplib'
- regex: 'Definitely-Not-Requests'
name: 'Requests'
version: ''
url: 'https://github.com/psf/requests'
- regex: 'Stealer ([\d.]+)'
name: 'Stealer'
version: '$1'
url: 'https://github.com/hotrush/stealer/'
- regex: 'Mandrill-PHP(?:/(\d+[.\d]+))?'
name: 'Mandrill PHP'
version: '$1'
url: 'https://bitbucket.org/mailchimp/mandrill-api-php/src/master/'
- regex: '^Podgrab'
name: 'Podgrab'
version: ''
url: 'https://github.com/akhilrex/podgrab'
- regex: '^Podcast Provider.*?Radio Downloader ([\d.]+)'
name: 'Radio Downloader'
version: '$1'
url: 'https://nerdoftheherd.com/tools/radiodld/'
- regex: '^ESP32 HTTP Client/([\d.]+)'
name: 'ESP32 HTTP Client'
version: '$1'
url: 'https://github.com/espressif/arduino-esp32'
- regex: 'babashka\.http-client(?:/(\d+[.\d]+))?'
name: 'Babashka HTTP Client'
version: '$1'
url: 'https://github.com/babashka/http-client'
- regex: 'http\.rb(?:/(\d+[.\d]+))?'
name: 'http.rb'
version: '$1'
url: 'https://github.com/httprb/http'
- regex: 'node-superagent(?:/(\d+[.\d]+))?'
name: 'superagent'
version: '$1'
url: 'https://github.com/ladjs/superagent'
- regex: 'CakePHP'
name: 'CakePHP'
version: ''
url: 'https://www.cakephp.org/'
- regex: 'request\.js'
name: 'request'
version: ''
url: 'https://github.com/request/request'
- regex: 'qbhttp(?:/(\d+[.\d]+))?'
name: 'QbHttp'
version: '$1'
url: 'https://github.com/OpenQb/QbHttp'
- regex: 'httprs(?:/(\d+[.\d]+))?'
name: 'httprs'
version: '$1'
url: 'https://github.com/http-server-rs/http-server'
- regex: 'Boto3(?:/(\d+[.\d]+))?'
name: 'Boto3'
version: '$1'
url: 'https://github.com/boto/boto3'
- regex: 'Python-xmlrpc(?:/(\d+[.\d]+))?'
name: 'XML-RPC'
version: '$1'
url: 'https://docs.python.org/3/library/xmlrpc.html'
- regex: 'ICAP-Client-Library(?:/(\d+[.\d]+))?'
name: 'ICAP Client'
version: '$1'
url: 'https://github.com/Peoplecantfly/icapserver'
- regex: 'Cygwin-Setup(?:/(\d+[.\d]+))?'
name: 'Cygwin'
version: '$1'
url: 'https://www.cygwin.com/'
- regex: 'azsdk-python-storage-blob(?:/(\d+[.\d]+))?'
name: 'Azure Blob Storage'
version: '$1'
url: 'https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-python'
- regex: 'trafilatura(?:/(\d+[.\d]+))?'
name: 'trafilatura'
version: '$1'
url: 'https://github.com/adbar/trafilatura'
- regex: 'sqlmap(?:/(\d+[.\d]+))?'
name: 'sqlmap'
version: '$1'
url: 'https://sqlmap.org/'
- regex: 'vimeo\.php(?: (\d+[.\d]+))?'
name: 'vimeo.php'
version: '$1'
url: 'https://github.com/vimeo/vimeo.php'
- regex: '^PHP/?(\d+[.\d]+)'
name: 'PHP'
version: '$1'
url: ''
- regex: 'go-network-v(\d+[.\d]+)'
name: 'go-network'
version: '$1'
url: ''
- regex: 'Bun/(\d+\.[.\d]+)'
name: 'Bun'
version: '$1'
url: 'https://bun.sh/'
- regex: 'Apidog/(\d+\.[.\d]+)'
name: 'Apidog'
version: '$1'
url: 'https://apidog.com/'
- regex: 'webchk v(\d+\.[.\d]+)'
name: 'webchk'
version: '$1'
url: 'https://github.com/amgedr/webchk'
- regex: 'MatomoTrackerSDK/(\d+[.\d]+)'
name: 'MatomoTracker'
version: '$1'
url: 'https://github.com/matomo-org/matomo-sdk-ios'
- regex: 'libHTTP/(\d+[.\d]+)'
name: 'LibHTTP'
version: '$1'
url: 'https://www.libhttp.org/'

View File

@@ -0,0 +1,183 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
- regex: 'Audacious(?:[ /]([\d.]+))?'
name: 'Audacious'
version: '$1'
- regex: '(?:AlexaMediaPlayer/|^AlexaMediaPlayer/|^Echo/|Amazon;Echo(?:_|;)|^AlexaService/|^Alexa Mobile Voice/)([a-z\d]+\.[a-z.\d]+)?'
name: 'Alexa'
version: '$1'
- regex: 'Banshee(?:[ /]([\d.]+))?'
name: 'Banshee'
version: '$1'
- regex: 'Boxee(?:[ /]([\d.]+))?'
name: 'Boxee'
version: '$1'
- regex: 'Clementine(?:[ /]([\d.]+))?'
name: 'Clementine'
version: '$1'
- regex: 'Deezer(?:/([\d.]+))?'
name: 'Deezer'
version: '$1'
- regex: 'iTunes(?:-iPhone|-iPad)?(?:/([\d.]+))?'
name: 'iTunes'
version: '$1'
- regex: 'FlyCast(?:/([\d.]+))?'
name: 'FlyCast'
version: '$1'
- regex: 'foobar2000(?:/([\d.]+))?'
name: 'Foobar2000'
version: '$1'
- regex: 'MediaMonkey(?:[ /](\d+[.\d]+))?'
name: 'MediaMonkey'
version: '$1'
- regex: 'Miro(?:/(\d+[.\d]+))?'
name: 'Miro'
version: '$1'
- regex: 'NexPlayer(?:/(\d+[.\d]+))?'
name: 'NexPlayer'
version: '$1'
- regex: 'Nightingale(?:/([\d.]+))?'
name: 'Nightingale'
version: '$1'
- regex: 'QuickTime(?:(?:(?:.+qtver=)|(?:(?: E-)?[\./]))([\d.]+))?'
name: 'QuickTime'
version: '$1'
- regex: 'Songbird(?:/([\d.]+))?'
name: 'Songbird'
version: '$1'
- regex: 'SubStream(?:/([\d.]+))?'
name: 'SubStream'
version: '$1'
- regex: 'Sonos/([\d.]+)?'
name: 'SONOS'
version: '$1'
- regex: '(?:Lib)?VLC(?:/([\d.]+))?'
name: 'VLC'
version: '$1'
- regex: 'Winamp(?:MPEG)?(?:/(\d+[.\d]+))?'
name: 'Winamp'
version: '$1'
- regex: 'J\. River Internet Reader/(\d+\.[.\d]+)'
name: 'JRiver Media Center'
version: '$1'
- regex: '(?:Windows-Media-Player|NSPlayer)(?:/(\d+[.\d]+))?'
name: 'Windows Media Player'
version: '$1'
- regex: 'XBMC(?:/([\d.]+))?'
name: 'XBMC'
version: '$1'
- regex: 'Kodi(?:/([\d.]+))?'
name: 'Kodi'
version: '$1'
- regex: 'stagefright(?:/([\d.]+))?'
name: 'Stagefright'
version: '$1'
- regex: 'GoogleChirp(?:/(\d+[.\d]+))?'
name: 'Google Podcasts'
version: '$1'
- regex: 'Music Player Daemon (?:(\d+[.\d]+))?'
name: 'Music Player Daemon'
version: '$1'
- regex: 'mpv (?:(\d+[.\d]+))?'
name: 'mpv'
version: '$1'
- regex: 'HTC Streaming Player'
name: 'HTC Streaming Player'
version: ''
- regex: 'MediaGo(?:/([\w\.]+))?'
name: 'Sony Media Go'
version: '$1'
- regex: 'MPlayer[ /](\d+\.[\d.])'
name: 'MPlayer'
version: '$1'
- regex: 'Downcast/(\d+\.[\d.]+)?'
name: 'Downcast'
version: '$1'
- regex: '^Juice/([\d.]+)'
name: 'Juice'
version: '$1'
- regex: 'just_audio/(\d+\.[.\d]+)'
name: 'Just Audio'
version: '$1'
# https://apps.kde.org/kasts/ ?
- regex: '^Kasts/(\d+\.[.\d]+)'
name: 'Kasts'
version: '$1'
- regex: 'MixerBox(?:%20Pro)?/([.\d]+)'
name: 'MixerBox'
version: '$1'
- regex: '^MusicBee(?:/(\d+\.[.\d]+))?'
name: 'MusicBee'
version: '$1'
- regex: '^amarok/(\d+\.[.\d]+)'
name: 'Amarok'
version: '$1'
- regex: 'Hubhopper/([\d.]+)'
name: 'Hubhopper'
version: '$1'
- regex: 'StudioDisplay/(\d+\.[\d.]+)'
name: 'StudioDisplay'
version: '$1'
# JHelioviewer (https://www.jhelioviewer.org/)
- regex: 'JHV/SWHV-([.\d+]+)'
name: 'JHelioviewer'
version: '$1'
# Xtream Player (https://play.google.com/store/apps/details?id=com.devcoder.iptvxtreamplayer)
- regex: 'com\.devcoder\.iptvxtreamplayer'
name: 'Xtream Player'
version: ''
# DIGA (https://av.jpn.support.panasonic.com/support/global/cs/bd/diga_player/2013/android/index.html)
- regex: 'DIGA(?:Plus/(\d+\.[.\d]+))?'
name: 'DIGA'
version: '$1'
# YouView (https://www.youview.com/)
- regex: 'YouView(?:HTML/(\d+\.[.\d]+))?'
name: 'YouView'
version: '$1'

View File

@@ -0,0 +1,167 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
- regex: 'Outlook-Express(?:/(\d+[.\d]+))?'
name: 'Outlook Express'
version: '$1'
# Outlook https://apps.apple.com/ru/app/microsoft-outlook/id951937596
- regex: '^Outlook-iOS/(?:.+\((\d+[.\d]+)\)$)?'
name: 'Microsoft Outlook'
version: '$1'
- regex: '(?:(?:Microsoft )?Outlook|MacOutlook)(?:[/ ](\d+[.\d]+))?'
name: 'Microsoft Outlook'
version: '$1'
# Default Mail Client for Windows
- regex: 'WindowsMail(?:/(\d+[.\d]+))'
name: 'Windows Mail'
version: '$1'
- regex: '(?:Thunderbird|Icedove|Shredder)(?:/(\d+[.\d]+))?'
name: 'Thunderbird'
version: '$1'
# Spicebird (http://www.spicebird.org/)
- regex: 'Spicebird/(\d+\.[.\d]+)'
name: 'Spicebird'
version: '$1'
- regex: 'Airmail(?: (\d+[.\d]+))?'
name: 'Airmail'
version: '$1'
- regex: 'Lotus-Notes(?:/(\d+[.\d]+))?'
name: 'Lotus Notes'
version: '$1'
- regex: 'Barca(?:Pro)?(?:[/ ](\d+[.\d]+))?'
name: 'Barca'
version: '$1'
- regex: 'Postbox(?:[/ ](\d+[.\d]+))?'
name: 'Postbox'
version: '$1'
- regex: 'MailBar(?:[/ ](\d+[.\d]+))?'
name: 'MailBar'
version: '$1'
- regex: 'The Bat!(?: Voyager)?(?:[/ ](\d+[.\d]+))?'
name: 'The Bat!'
version: '$1'
- regex: 'DAVdroid(?:/(\d+[.\d]+))?'
name: 'DAVdroid'
version: '$1'
# SeaMonkey
- regex: '(?:SeaMonkey|Iceape)(?:/(\d+[.\d]+))?'
name: 'SeaMonkey'
version: '$1'
# Live5ch
- regex: 'Live5ch/(\d+[.\d]+)'
name: 'Live5ch'
version: '$1'
- regex: 'JaneView/'
name: 'JaneView'
version: ''
- regex: 'BathyScaphe/'
name: 'BathyScaphe'
version: ''
# Raindrop.io (https://raindrop.io/)
- regex: 'Raindrop\.io/(\d+[.\d]+)'
name: 'Raindrop.io'
version: '$1'
# Franz (https://meetfranz.com/)
- regex: 'Franz/(\d+[.\d]+)'
name: 'Franz'
version: '$1'
# Mailspring (https://www.electronjs.org/apps/mailspring)
- regex: 'Mailspring/(\d+[.\d]+)'
name: 'Mailspring'
version: '$1'
# Notion (https://www.notion.so/)
- regex: 'Notion/(\d+[.\d]+)'
name: 'Notion'
version: '$1'
# Basecamp (https://basecamp.com/)
- regex: 'Basecamp[0-9]/?(\d+[.\d]+)'
name: 'Basecamp'
version: '$1'
# Evernote (https://evernote.com/)
- regex: 'Evernote/?(\d+[.\d]+)'
name: 'Evernote'
version: '$1'
# Rambox Pro (https://rambox.app/)
- regex: 'ramboxpro/(\d+\.[.\d]+)?'
name: 'Rambox Pro'
version: '$1'
# Mailbird (https://www.getmailbird.com/)
- regex: 'Mailbird/(\d+\.[.\d]+)/'
name: 'Mailbird'
version: '$1'
# Yahoo Mail (https://apps.apple.com/us/app/yahoo-mail-organised-email/id577586159)
- regex: 'Yahoo%20Mail'
name: 'Yahoo Mail'
version: ''
# Yahoo! Mail (https://play.google.com/store/apps/details?id=jp.co.yahoo.android.ymail | https://apps.apple.com/jp/app/yahoo-%E3%83%A1%E3%83%BC%E3%83%AB/id669931877)
- regex: 'jp.co.yahoo.ymail/([\d.]+)'
name: 'Yahoo! Mail'
version: '$1'
# eM Client (https://emclient.com/)
- regex: 'eM ?Client/(\d+\.[.\d]+)'
name: 'eM Client'
version: '$1'
# NAVER Mail (https://play.google.com/store/apps/details?id=com.nhn.android.mail)
- regex: 'NaverMailApp/(\d+\.[.\d]+)'
name: 'NAVER Mail'
version: '$1'
- regex: '^Mail/([\d.]+)'
name: 'Apple Mail'
version: '$1'
# Foxmail (https://www.foxmail.com/)
- regex: 'Foxmail/(\d+[.\d]+)'
name: 'Foxmail'
version: '$1'
# Mail Master (https://apps.apple.com/mw/app/mail-master-by-netease/id897003024)
- regex: 'MailMaster(?:PC|_Android_Mobile)?/(\d+[.\d]+)'
name: 'Mail Master'
version: '$1'
# BlueMail (https://bluemail.me/)
- regex: 'BlueMail/(\d+[.\d]+)'
name: 'BlueMail'
version: '$1'
- regex: 'mailapp/(\d+\.[.\d]+)'
name: 'mailapp'
version: '$1'
# Gmail
- regex: 'Android-Gmail'
name: 'Gmail'
version: ''

View File

@@ -0,0 +1,28 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
#Nikon
Nikon:
regex: 'Coolpix S800c'
device: 'camera'
model: 'Coolpix S800c'
# Samsung
Samsung:
regex: 'EK-G[CN][0-9]{3}'
device: 'camera'
models:
- regex: 'EK-GN120'
model: 'Galaxy NX'
- regex: 'EK-GC100'
model: 'Galaxy Camera'
- regex: 'EK-GC110'
model: 'Galaxy Camera WiFi only'
- regex: 'EK-GC200'
model: 'Galaxy Camera 2'
- regex: 'EK-GC([0-9]{3})'
model: 'Galaxy Camera $1'

View File

@@ -0,0 +1,48 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
# BMW (https://www.bmw.com/)
BMW:
regex: 'AFTLBT962E2(?:[);/ ]|$)'
device: 'car browser'
models:
- regex: 'AFTLBT962E2(?:[);/ ]|$)'
model: 'Car (2022)'
# Jeep (https://www.jeep.com/)
Jeep:
regex: 'AFTLFT962X3(?:[);/ ]|$)'
device: 'car browser'
models:
- regex: 'AFTLFT962X3(?:[);/ ]|$)'
model: 'Wagoneer'
# Tesla Model S
Tesla:
regex: '(?:Tesla/(?:(?:develop|feature|terminal-das-fsd-eap)-)?[0-9.]+|QtCarBrowser)'
device: 'car browser'
models:
- regex: 'QtCarBrowser'
model: 'Model S'
- regex: 'Tesla/[0-9.]+'
model: ''
# Mac Audio
MAC AUDIO:
regex: 'Mac Audio Spro'
device: 'car browser'
models:
- regex: 'Spro'
model: 'S Pro'
# Topway
Topway:
regex: 'sp9853i_1h10_vmm'
device: 'car browser'
models:
- regex: 'sp9853i_1h10_vmm'
model: 'TS9'

View File

@@ -0,0 +1,80 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
Archos:
regex: 'Archos.*GAMEPAD([2]?)'
device: 'console'
model: 'Gamepad $1'
Microsoft:
regex: 'Xbox'
device: 'console'
models:
- regex: 'Xbox Series X'
model: 'Xbox Series X'
- regex: 'Xbox One X'
model: 'Xbox One X'
- regex: 'Xbox One'
model: 'Xbox One'
- regex: 'XBOX_ONE_ED'
model: 'Xbox One S'
- regex: 'Xbox'
model: 'Xbox 360'
Nintendo:
regex: 'Nintendo (([3]?DS[i]?)|Wii[U]?|Switch|GameBoy)'
device: 'console'
model: '$1'
OUYA:
regex: 'OUYA'
device: 'console'
model: 'OUYA'
Sanyo:
regex: 'Aplix_SANYO'
device: 'console'
model: '3DO TRY'
Sega:
regex: 'Dreamcast|Aplix_SEGASATURN'
device: 'console'
models:
- regex: 'Dreamcast'
model: 'Dreamcast'
- regex: 'Aplix_SEGASATURN'
model: 'Saturn'
JXD:
regex: 'JXD_S601WIFI'
device: 'console'
model: 'S601 WiFi'
Sony:
regex: '(?:PlayStation ?(4 Pro|[2-5]|Portable|Vita)|sony_tv;ps5;|\(PS3\))'
device: 'console'
models:
- regex: 'sony_tv;ps5;'
model: 'PlayStation 5'
- regex: 'PlayStation 4 PRO'
model: 'PlayStation 4 Pro'
- regex: '\(PS3\)'
model: 'PlayStation 3'
- regex: 'PlayStation ?(4 Pro|[2-5]|Portable|Vita)'
model: 'PlayStation $1'
# Retroid Pocket (www.goretroid.com)
Retroid Pocket:
regex: 'Retroid Pocket'
device: 'console'
models:
- regex: 'Pocket ([23]) ?(?:Plus|\+)'
model: '$1 Plus'
- regex: 'Pocket 4 Pro'
model: '4 Pro'
- regex: 'Pocket ([235])'
model: '$1'

View File

@@ -0,0 +1,127 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
Acer:
regex: 'FBMD/(?:Aspire E5-421G|Z5WAL|One S1003);'
device: 'desktop'
models:
- regex: 'FBMD/Aspire E5-421G;'
model: 'Aspire E5-421G'
- regex: 'FBMD/Z5WAL;'
model: 'Aspire E5-511'
- regex: 'FBMD/One S1003;'
model: 'One 10'
Asus:
regex: 'FBMD/(?:K50IN|K54L|T100HAN|T103HAF|UX360CAK|X550LB|X553MA|X555LN|X556UQK);'
device: 'desktop'
models:
- regex: 'FBMD/K50IN;'
model: 'K50IN'
- regex: 'FBMD/K54L;'
model: 'K54L'
- regex: 'FBMD/T100HAN;'
model: 'Transformer Book'
- regex: 'FBMD/T103HAF;'
model: 'Transformer Mini'
- regex: 'FBMD/UX360CAK;'
model: 'ZenBook Flip'
- regex: 'FBMD/X550LB;'
model: 'X550LB'
- regex: 'FBMD/X553MA;'
model: 'X553MA'
- regex: 'FBMD/X555LN;'
model: 'X555LN'
- regex: 'FBMD/X556UQK;'
model: 'X556UQK'
Alienware:
regex: 'FBMD/(?:Alienware [0-9]{2,3}R[0-9]{1,2}|Area-51m|R3|R4|Alienware Aurora R[0-9]+(:? [0-9]+)?);'
device: 'desktop'
models:
- regex: 'Alienware 15R3;'
model: 'Alienware 15 R3'
- regex: 'Alienware 17R4;'
model: 'Alienware 17 R4'
- regex: 'Area-51m;'
model: 'Area-51m'
- regex: 'Aurora (R[0-9]+)'
model: 'Aurora $1'
Dell:
regex: 'FBMD/(?:Latitude E4300|Inspiron 3541|XPS 15 95[35]0);'
device: 'desktop'
models:
- regex: 'Latitude E4300'
model: 'Latitude E4300'
- regex: 'Inspiron 3541'
model: 'Inspiron 3541'
- regex: 'XPS 15 9530'
model: 'XPS 15 9530'
- regex: 'XPS 15 9550'
model: 'XPS 15 9550'
HP:
regex: 'FBMD/((?:Compaq|HP) |23-f364)'
device: 'desktop'
models:
- regex: 'Compaq Presario CQ61 Notebook PC'
model: 'Compaq Presario CQ61'
- regex: 'HP Pavilion x2 Detachable'
model: 'Pavilion x2'
- regex: 'HP Laptop 15-bs0xx'
model: '15 Laptop PC'
- regex: 'HP ENVY x360 Convertible 15-bp0xx'
model: 'ENVY x360 Convertible PC'
- regex: 'HP EliteBook (25[67]0p)'
model: 'EliteBook $1'
- regex: 'HP ProBook (440 G5|6[35]60b)'
model: 'ProBook $1'
- regex: 'HP Pavilion dv6 Notebook PC'
model: 'Pavilion dv6'
- regex: 'HP Pavilion Notebook'
model: 'Pavilion'
- regex: 'HP Spectre x360 Convertible'
model: 'Spectre x360'
- regex: 'HP Pavilion All-in-One 24-r0xx'
model: 'Pavilion 24-r0xx All-in-One Desktop PC'
device: 'desktop'
- regex: '23-f364'
model: 'Pavilion TouchSmart 23-f364 All-in-One Desktop PC'
device: 'desktop'
Lenovo:
regex: 'FBMD/(?:37021C5|80E5|80SM|80VR);'
device: 'desktop'
models:
- regex: 'FBMD/37021C5;'
model: 'ThinkPad Helix 3702'
- regex: 'FBMD/80E5;'
model: 'G50-80'
- regex: 'FBMD/80SM;'
model: 'Ideapad 310-15ISK'
- regex: 'FBMD/80VR;'
model: 'Legion Y720'
Schneider:
regex: 'FBMD/SCL141CTP;'
device: 'desktop'
model: 'Notebook 14" Cherry Trail'
Thomson:
regex: 'FBMD/TH360R12\.32CTW;'
device: 'desktop'
model: 'Prestige TH-360R12.32CTW'
Toshiba:
regex: 'FBMD/Satellite '
device: 'desktop'
models:
- regex: 'Satellite (A[25]00|C650|C855|L650|S855)'
model: 'Satellite $1'
- regex: 'Satellite ([^;\)]+);'
model: 'Satellite $1'

View File

@@ -0,0 +1,136 @@
###############
# Device Detector - The Universal Device Detection library for parsing User Agents
#
# @link https://matomo.org
# @license http://www.gnu.org/licenses/lgpl.html LGPL v3 or later
###############
Apple:
regex: '(?:Apple-)?iPod'
device: 'portable media player'
models:
- regex: '(?:Apple-)?iPod1[C,_]?1'
model: 'iPod Touch 1G'
- regex: '(?:Apple-)?iPod2[C,_]?1'
model: 'iPod Touch 2G'
- regex: '(?:Apple-)?iPod3[C,_]?1'
model: 'iPod Touch 3'
- regex: '(?:Apple-)?iPod4[C,_]?1'
model: 'iPod Touch 4'
- regex: '(?:Apple-)?iPod5[C,_]?1'
model: 'iPod Touch 5'
- regex: '(?:Apple-)?iPod7[C,_]?1'
model: 'iPod Touch 6'
- regex: '(?:Apple-)?iPod9[C,_]?1|iPodTouch7'
model: 'iPod Touch 7'
- regex: '(?:Apple-)?iPod'
model: 'iPod Touch'
Cowon:
regex: 'COWON ([^;/]+) Build'
device: 'portable media player'
model: '$1'
# FiiO (https://www.fiio.com/)
FiiO:
regex: 'FiiO'
device: 'portable media player'
models:
- regex: 'M11 Plus LTD'
model: 'M11 Plus LTD'
- regex: 'FiiO M(11S|1[157]|6)'
model: 'M$1'
Microsoft:
regex: 'Microsoft ZuneHD'
device: 'portable media player'
model: 'Zune HD'
Panasonic:
regex: '(SV-MV100)'
device: 'portable media player'
model: '$1'
Samsung:
regex: 'YP-(G[SIPB]?1|G[57]0|GB70D)'
device: 'portable media player'
models:
- regex: 'YP-G[B]?1'
model: 'Galaxy Player 4.0'
- regex: 'YP-G70'
model: 'Galaxy Player 5.0'
- regex: 'YP-GS1'
model: 'Galaxy Player 3.6'
- regex: 'YP-GI1'
model: 'Galaxy Player 4.2'
- regex: 'YP-GP1'
model: 'Galaxy Player 5.8'
- regex: 'YP-G50'
model: 'Galaxy Player 50'
- regex: 'YP-GB70D'
model: 'Galaxy Player 70 Plus'
Wizz:
regex: '(DV-PTB1080)(?:[);/ ]|$)'
device: 'portable media player'
model: '$1'
# Shanling
Shanling:
regex: 'Shanling M6'
device: 'portable media player'
models:
- regex: 'Shanling (M6\(21\))'
model: '$1'
# Sylvania
Sylvania:
regex: '(SLTDVD102[34])'
device: 'portable media player'
model: '$1'
# KuGou
KuGou:
regex: 'KuGou[_ -](P5)'
device: 'portable media player'
model: '$1'
# Surfans
Surfans:
regex: '(Y57A)(?:[);/ ]|$)'
device: 'portable media player'
model: '$1'
# Oilsky (oilsky.com.cn)
Oilsky:
regex: 'Oilsky (M501|M303)(?:-Pro)?(?:[);/ ]|$)'
device: 'portable media player'
models:
- regex: 'M303-Pro'
model: 'M303 Pro'
- regex: '(M501|M303)'
model: '$1'
# Diofox
Diofox:
regex: 'Diofox[ _](M8|M10|M508)(?:[);/ ]|$)'
device: 'portable media player'
model: '$1'
# MECHEN (mechen.com.cn)
MECHEN:
regex: 'MECHEN'
device: 'portable media player'
models:
- regex: 'MECHEN[- _]([^;/)]+)[- _]Pro(?: Build|[);])'
model: '$1 Pro'
- regex: 'MECHEN[- _]([^;/)]+)(?: Build|[);])'
model: '$1'
# Fanvace
Fanvace:
regex: 'Fanvace'
device: 'portable media player'
models:
- regex: 'Fanvace[- _]([^;/)]+)(?: Build|[);])'
model: '$1'

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