first commit

This commit is contained in:
2025-06-17 11:53:18 +02:00
commit 9f0f7ba12b
8804 changed files with 1369176 additions and 0 deletions

View File

@ -0,0 +1,109 @@
local volumes = [
{
name: "composer-cache",
path: "/tmp/composer-cache",
},
];
local hostvolumes = [
{
name: "composer-cache",
host: {path: "/tmp/composer-cache"}
},
];
local composer(phpversion, params) = {
name: "composer",
image: "joomlaprojects/docker-images:php" + phpversion,
volumes: volumes,
commands: [
"php -v",
"composer update " + params,
]
};
local phpunit(phpversion) = {
name: "PHPUnit",
image: "joomlaprojects/docker-images:php" + phpversion,
[if phpversion == "8.3" then "failure"]: "ignore",
commands: [
"php -S localhost:8080 -t Tests/stubs &",
"vendor/bin/phpunit"
]
};
local pipeline(name, phpversion, params) = {
kind: "pipeline",
name: "PHP " + name,
volumes: hostvolumes,
steps: [
composer(phpversion, params),
phpunit(phpversion)
],
};
[
{
kind: "pipeline",
name: "Codequality",
volumes: hostvolumes,
steps: [
{
name: "composer",
image: "joomlaprojects/docker-images:php8.1",
volumes: volumes,
commands: [
"php -v",
"composer update"
]
},
{
name: "phpcs",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
commands: [
"vendor/bin/phpcs --standard=ruleset.xml src/"
]
},
{
name: "phan",
image: "joomlaprojects/docker-images:php8.1-ast",
depends: [ "composer" ],
failure: "ignore",
commands: [
"vendor/bin/phan"
]
},
{
name: "phpstan",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
failure: "ignore",
commands: [
"vendor/bin/phpstan analyse src",
]
},
{
name: "phploc",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
failure: "ignore",
commands: [
"phploc src",
]
},
{
name: "phpcpd",
image: "joomlaprojects/docker-images:php8.1",
depends: [ "composer" ],
failure: "ignore",
commands: [
"phpcpd src",
]
}
]
},
pipeline("8.1 lowest", "8.1", "--prefer-stable --prefer-lowest"),
pipeline("8.1", "8.1", "--prefer-stable"),
pipeline("8.2", "8.2", "--prefer-stable"),
]

118
libraries/vendor/joomla/http/.drone.yml vendored Normal file
View File

@ -0,0 +1,118 @@
---
kind: pipeline
name: Codequality
steps:
- commands:
- php -v
- composer update
image: joomlaprojects/docker-images:php8.1
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- vendor/bin/phpcs --standard=ruleset.xml src/
depends:
- composer
image: joomlaprojects/docker-images:php8.1
name: phpcs
- commands:
- vendor/bin/phan
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1-ast
name: phan
- commands:
- vendor/bin/phpstan analyse src
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1
name: phpstan
- commands:
- phploc src
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1
name: phploc
- commands:
- phpcpd src
depends:
- composer
failure: ignore
image: joomlaprojects/docker-images:php8.1
name: phpcpd
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: pipeline
name: PHP 8.1 lowest
steps:
- commands:
- php -v
- composer update --prefer-stable --prefer-lowest
image: joomlaprojects/docker-images:php8.1
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- php -S localhost:8080 -t Tests/stubs &
- vendor/bin/phpunit
image: joomlaprojects/docker-images:php8.1
name: PHPUnit
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: pipeline
name: PHP 8.1
steps:
- commands:
- php -v
- composer update --prefer-stable
image: joomlaprojects/docker-images:php8.1
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- php -S localhost:8080 -t Tests/stubs &
- vendor/bin/phpunit
image: joomlaprojects/docker-images:php8.1
name: PHPUnit
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: pipeline
name: PHP 8.2
steps:
- commands:
- php -v
- composer update --prefer-stable
image: joomlaprojects/docker-images:php8.2
name: composer
volumes:
- name: composer-cache
path: /tmp/composer-cache
- commands:
- php -S localhost:8080 -t Tests/stubs &
- vendor/bin/phpunit
image: joomlaprojects/docker-images:php8.2
name: PHPUnit
volumes:
- host:
path: /tmp/composer-cache
name: composer-cache
---
kind: signature
hmac: 22dea03e9152e3df41f95a832d2edb6b6a2ba49720766ded75238d26578e674d
...

340
libraries/vendor/joomla/http/LICENSE vendored Normal file
View File

@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) 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
this service 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 make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. 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.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

View File

@ -0,0 +1,92 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http;
/**
* Abstract transport class.
*
* @since 2.0.0
*/
abstract class AbstractTransport implements TransportInterface
{
/**
* The client options.
*
* @var array|\ArrayAccess
* @since 2.0.0
*/
protected $options;
/**
* Constructor.
*
* @param array|\ArrayAccess $options Client options array.
*
* @since 2.0.0
* @throws \RuntimeException
*/
public function __construct($options = [])
{
if (!static::isSupported()) {
throw new \RuntimeException(sprintf('The %s transport is not supported in this environment.', \get_class($this)));
}
if (!\is_array($options) && !($options instanceof \ArrayAccess)) {
throw new \InvalidArgumentException(
'The options param must be an array or implement the ArrayAccess interface.'
);
}
$this->options = $options;
}
/**
* Get an option from the HTTP transport.
*
* @param string $key The name of the option to get.
* @param mixed $default The default value if the option is not set.
*
* @return mixed The option value.
*
* @since 2.0.0
*/
protected function getOption(string $key, $default = null)
{
return $this->options[$key] ?? $default;
}
/**
* Processes the headers from a transport's response data.
*
* @param array $headers The headers to process.
*
* @return array
*
* @since 2.0.0
*/
protected function processHeaders(array $headers): array
{
$verifiedHeaders = [];
// Add the response headers to the response object.
foreach ($headers as $header) {
$pos = strpos($header, ':');
$keyName = trim(substr($header, 0, $pos));
if (!isset($verifiedHeaders[$keyName])) {
$verifiedHeaders[$keyName] = [];
}
$verifiedHeaders[$keyName][] = trim(substr($header, ($pos + 1)));
}
return $verifiedHeaders;
}
}

View File

@ -0,0 +1,21 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http\Exception;
use Psr\Http\Client\ClientExceptionInterface;
/**
* Exception representing an invalid or undefined HTTP response code
*
* @since 1.2.0
*/
class InvalidResponseCodeException extends \UnexpectedValueException implements ClientExceptionInterface
{
}

View File

@ -0,0 +1,58 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http\Exception;
use Joomla\Http\Response;
use Psr\Http\Client\ClientExceptionInterface;
/**
* Exception representing an unexpected response
*
* @since 1.2.0
*/
class UnexpectedResponseException extends \DomainException implements ClientExceptionInterface
{
/**
* The Response object.
*
* @var Response
* @since 1.2.0
*/
private $response;
/**
* Constructor
*
* @param Response $response The Response object.
* @param string $message The Exception message to throw.
* @param integer $code The Exception code.
* @param ?\Exception $previous The previous exception used for the exception chaining.
*
* @since 1.2.0
*/
public function __construct(Response $response, $message = '', $code = 0, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->response = $response;
}
/**
* Get the Response object.
*
* @return Response
*
* @since 1.2.0
*/
public function getResponse()
{
return $this->response;
}
}

View File

@ -0,0 +1,307 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http;
use Joomla\Uri\Uri;
use Joomla\Uri\UriInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* HTTP client class.
*
* @since 1.0
*/
class Http implements ClientInterface
{
/**
* Options for the HTTP client.
*
* @var array|\ArrayAccess
* @since 1.0
*/
protected $options;
/**
* The HTTP transport object to use in sending HTTP requests.
*
* @var TransportInterface
* @since 1.0
*/
protected $transport;
/**
* Constructor.
*
* @param array|\ArrayAccess $options Client options array. If the registry contains any headers.* elements,
* these will be added to the request headers.
* @param ?TransportInterface $transport The HTTP transport object.
*
* @since 1.0
* @throws \InvalidArgumentException
*/
public function __construct($options = [], TransportInterface $transport = null)
{
if (!\is_array($options) && !($options instanceof \ArrayAccess)) {
throw new \InvalidArgumentException(
'The options param must be an array or implement the ArrayAccess interface.'
);
}
$this->options = $options;
if (!$transport) {
$transport = (new HttpFactory())->getAvailableDriver($this->options);
// Ensure the transport is a TransportInterface instance or bail out
if (!($transport instanceof TransportInterface)) {
throw new \InvalidArgumentException(sprintf('A valid %s object was not set.', TransportInterface::class));
}
}
$this->transport = $transport;
}
/**
* Get an option from the HTTP client.
*
* @param string $key The name of the option to get.
* @param mixed $default The default value if the option is not set.
*
* @return mixed The option value.
*
* @since 1.0
*/
public function getOption($key, $default = null)
{
return $this->options[$key] ?? $default;
}
/**
* Set an option for the HTTP client.
*
* @param string $key The name of the option to set.
* @param mixed $value The option value to set.
*
* @return $this
*
* @since 1.0
*/
public function setOption($key, $value)
{
$this->options[$key] = $value;
return $this;
}
/**
* Method to send the OPTIONS command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
*/
public function options($url, array $headers = [], $timeout = null)
{
return $this->makeTransportRequest('OPTIONS', $url, null, $headers, $timeout);
}
/**
* Method to send the HEAD command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
*/
public function head($url, array $headers = [], $timeout = null)
{
return $this->makeTransportRequest('HEAD', $url, null, $headers, $timeout);
}
/**
* Method to send the GET command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
*/
public function get($url, array $headers = [], $timeout = null)
{
return $this->makeTransportRequest('GET', $url, null, $headers, $timeout);
}
/**
* Method to send the POST command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
*/
public function post($url, $data, array $headers = [], $timeout = null)
{
return $this->makeTransportRequest('POST', $url, $data, $headers, $timeout);
}
/**
* Method to send the PUT command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
*/
public function put($url, $data, array $headers = [], $timeout = null)
{
return $this->makeTransportRequest('PUT', $url, $data, $headers, $timeout);
}
/**
* Method to send the DELETE command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param mixed $data Either an associative array or a string to be sent with the request.
*
* @return Response
*
* @since 1.0
*/
public function delete($url, array $headers = [], $timeout = null, $data = null)
{
return $this->makeTransportRequest('DELETE', $url, $data, $headers, $timeout);
}
/**
* Method to send the TRACE command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
*/
public function trace($url, array $headers = [], $timeout = null)
{
return $this->makeTransportRequest('TRACE', $url, null, $headers, $timeout);
}
/**
* Method to send the PATCH command to the server.
*
* @param string|UriInterface $url The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
*/
public function patch($url, $data, array $headers = [], $timeout = null)
{
return $this->makeTransportRequest('PATCH', $url, $data, $headers, $timeout);
}
/**
* Sends a PSR-7 request and returns a PSR-7 response.
*
* @param RequestInterface $request The PSR-7 request object.
*
* @return ResponseInterface|Response
*
* @since 2.0.0
*/
public function sendRequest(RequestInterface $request): ResponseInterface
{
$data = $request->getBody()->getContents();
return $this->makeTransportRequest(
$request->getMethod(),
new Uri((string) $request->getUri()),
empty($data) ? null : $data,
$request->getHeaders()
);
}
/**
* Send a request to the server and return a Response object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param string|UriInterface $url The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
*
* @return Response
*
* @since 1.0
* @throws \InvalidArgumentException
*/
protected function makeTransportRequest($method, $url, $data = null, array $headers = [], $timeout = null)
{
// Look for headers set in the options.
if (isset($this->options['headers'])) {
$temp = (array) $this->options['headers'];
foreach ($temp as $key => $val) {
if (!isset($headers[$key])) {
$headers[$key] = $val;
}
}
}
// Look for timeout set in the options.
if ($timeout === null && isset($this->options['timeout'])) {
$timeout = $this->options['timeout'];
}
$userAgent = isset($this->options['userAgent']) ? $this->options['userAgent'] : null;
// Convert to a Uri object if we were given a string
if (\is_string($url)) {
$url = new Uri($url);
} elseif (!($url instanceof UriInterface)) {
throw new \InvalidArgumentException(
sprintf(
'A string or %s object must be provided, a "%s" was provided.',
UriInterface::class,
\gettype($url)
)
);
}
return $this->transport->request($method, $url, $data, $headers, $timeout, $userAgent);
}
}

View File

@ -0,0 +1,125 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http;
/**
* HTTP factory class.
*
* @since 1.0
*/
class HttpFactory
{
/**
* Method to create an Http instance.
*
* @param array|\ArrayAccess $options Client options array.
* @param array|string $adapters Adapter (string) or queue of adapters (array) to use for communication.
*
* @return Http
*
* @since 1.0
* @throws \InvalidArgumentException
* @throws \RuntimeException
*/
public function getHttp($options = [], $adapters = null)
{
if (!\is_array($options) && !($options instanceof \ArrayAccess)) {
throw new \InvalidArgumentException(
'The options param must be an array or implement the ArrayAccess interface.'
);
}
if (!$driver = $this->getAvailableDriver($options, $adapters)) {
throw new \RuntimeException('No transport driver available.');
}
return new Http($options, $driver);
}
/**
* Finds an available TransportInterface object for communication
*
* @param array|\ArrayAccess $options Options for creating TransportInterface object
* @param array|string $default Adapter (string) or queue of adapters (array) to use
*
* @return TransportInterface|boolean Interface sub-class or boolean false if no adapters are available
*
* @since 1.0
* @throws \InvalidArgumentException
*/
public function getAvailableDriver($options = [], $default = null)
{
if (!\is_array($options) && !($options instanceof \ArrayAccess)) {
throw new \InvalidArgumentException(
'The options param must be an array or implement the ArrayAccess interface.'
);
}
if ($default === null) {
$availableAdapters = $this->getHttpTransports();
} else {
settype($default, 'array');
$availableAdapters = $default;
}
// Check if there is at least one available http transport adapter
if (!\count($availableAdapters)) {
return false;
}
foreach ($availableAdapters as $adapter) {
$class = __NAMESPACE__ . '\\Transport\\' . ucfirst($adapter);
if (class_exists($class)) {
if ($class::isSupported()) {
return new $class($options);
}
}
}
return false;
}
/**
* Get the HTTP transport handlers
*
* @return string[] An array of available transport handler types
*
* @since 1.0
*/
public function getHttpTransports()
{
$names = [];
$iterator = new \DirectoryIterator(__DIR__ . '/Transport');
/** @var \DirectoryIterator $file */
foreach ($iterator as $file) {
$fileName = $file->getFilename();
// Only load for php files.
if ($file->isFile() && $file->getExtension() == 'php') {
$names[] = substr($fileName, 0, strrpos($fileName, '.'));
}
}
// Keep alphabetical order across all environments
sort($names);
// If curl is available set it to the first position
$key = array_search('Curl', $names);
if ($key) {
unset($names[$key]);
array_unshift($names, 'Curl');
}
return $names;
}
}

View File

@ -0,0 +1,63 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http;
use Laminas\Diactoros\Response as PsrResponse;
/**
* HTTP response data object class.
*
* @property-read string $body The response body as a string
* @property-read integer $code The status code of the response
* @property-read array $headers The headers as an array
*
* @since 1.0
*/
class Response extends PsrResponse
{
/**
* Magic getter for backward compatibility with the 1.x API
*
* @param string $name The variable to return
*
* @return mixed
*
* @since 2.0.0
* @deprecated 3.0 Access data via the PSR-7 ResponseInterface instead
*/
public function __get($name)
{
switch (strtolower($name)) {
case 'body':
return (string) $this->getBody();
case 'code':
return $this->getStatusCode();
case 'headers':
return $this->getHeaders();
default:
$trace = debug_backtrace();
trigger_error(
sprintf(
'Undefined property via __get(): %s in %s on line %s',
$name,
$trace[0]['file'],
$trace[0]['line']
),
E_USER_NOTICE
);
break;
}
}
}

View File

@ -0,0 +1,332 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http\Transport;
use Composer\CaBundle\CaBundle;
use Joomla\Http\AbstractTransport;
use Joomla\Http\Exception\InvalidResponseCodeException;
use Joomla\Http\Response;
use Joomla\Uri\UriInterface;
use Laminas\Diactoros\Stream as StreamResponse;
/**
* HTTP transport class for using cURL.
*
* @since 1.0
*/
class Curl extends AbstractTransport
{
/**
* Send a request to the server and return a Response object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param UriInterface $uri The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param string $userAgent The optional user agent string to send with the request.
*
* @return Response
*
* @since 1.0
* @throws \RuntimeException
*/
public function request($method, UriInterface $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null)
{
// Setup the cURL handle.
$ch = curl_init();
// Initialize the certificate store
$this->setCAOptionAndValue($ch);
$options = [];
// Set the request method.
switch (strtoupper($method)) {
case 'GET':
$options[\CURLOPT_HTTPGET] = true;
break;
case 'POST':
$options[\CURLOPT_POST] = true;
break;
default:
$options[\CURLOPT_CUSTOMREQUEST] = strtoupper($method);
break;
}
// Don't wait for body when $method is HEAD
$options[\CURLOPT_NOBODY] = ($method === 'HEAD');
// Initialize the certificate store
$options[CURLOPT_CAINFO] = $this->getOption('curl.certpath', CaBundle::getSystemCaRootBundlePath());
// If data exists let's encode it and make sure our Content-type header is set.
if (isset($data)) {
// If the data is a scalar value simply add it to the cURL post fields.
if (is_scalar($data) || (isset($headers['Content-Type']) && strpos($headers['Content-Type'], 'multipart/form-data') === 0)) {
$options[\CURLOPT_POSTFIELDS] = $data;
} else {
// Otherwise we need to encode the value first.
$options[\CURLOPT_POSTFIELDS] = http_build_query($data);
}
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
}
// Add the relevant headers.
if (is_scalar($options[\CURLOPT_POSTFIELDS])) {
$headers['Content-Length'] = \strlen($options[\CURLOPT_POSTFIELDS]);
}
}
// Build the headers string for the request.
$headerArray = [];
if (!empty($headers)) {
foreach ($headers as $key => $value) {
if (\is_array($value)) {
foreach ($value as $header) {
$headerArray[] = "$key: $header";
}
} else {
$headerArray[] = "$key: $value";
}
}
// Add the headers string into the stream context options array.
$options[\CURLOPT_HTTPHEADER] = $headerArray;
}
// Curl needs the accepted encoding header as option
if (isset($headers['Accept-Encoding'])) {
$options[\CURLOPT_ENCODING] = $headers['Accept-Encoding'];
}
// If an explicit timeout is given use it.
if (isset($timeout)) {
$options[\CURLOPT_TIMEOUT] = (int) $timeout;
$options[\CURLOPT_CONNECTTIMEOUT] = (int) $timeout;
}
// If an explicit user agent is given use it.
if (isset($userAgent)) {
$options[\CURLOPT_USERAGENT] = $userAgent;
}
// Set the request URL.
$options[\CURLOPT_URL] = (string) $uri;
// We want our headers. :-)
$options[\CURLOPT_HEADER] = true;
// Return it... echoing it would be tacky.
$options[\CURLOPT_RETURNTRANSFER] = true;
// Override the Expect header to prevent cURL from confusing itself in its own stupidity.
// Link: http://the-stickman.com/web-development/php-and-curl-disabling-100-continue-header/
$options[\CURLOPT_HTTPHEADER][] = 'Expect:';
// Follow redirects if server config allows
if ($this->redirectsAllowed()) {
$options[\CURLOPT_FOLLOWLOCATION] = (bool) $this->getOption('follow_location', true);
}
// Authentication, if needed
if ($this->getOption('userauth') && $this->getOption('passwordauth')) {
$options[\CURLOPT_USERPWD] = $this->getOption('userauth') . ':' . $this->getOption('passwordauth');
$options[\CURLOPT_HTTPAUTH] = CURLAUTH_BASIC;
}
// Configure protocol version
if ($protocolVersion = $this->getOption('protocolVersion')) {
$options[\CURLOPT_HTTP_VERSION] = $this->mapProtocolVersion($protocolVersion);
}
// Set any custom transport options
foreach ($this->getOption('transport.curl', []) as $key => $value) {
$options[$key] = $value;
}
// Set the cURL options.
curl_setopt_array($ch, $options);
// Execute the request and close the connection.
$content = curl_exec($ch);
// Check if the content is a string. If it is not, it must be an error.
if (!\is_string($content)) {
$message = curl_error($ch);
if (empty($message)) {
// Error but nothing from cURL? Create our own
$message = 'No HTTP response received';
}
throw new \RuntimeException($message);
}
// Get the request information.
$info = curl_getinfo($ch);
// Close the connection.
curl_close($ch);
return $this->getResponse($content, $info);
}
/**
* Configure the cURL resources with the appropriate root certificates.
*
* @param \CurlHandle $ch The cURL resource you want to configure the certificates on.
*
* @return void
*
* @since 1.3.2
*/
protected function setCAOptionAndValue($ch)
{
if ($certpath = $this->getOption('curl.certpath')) {
// Option is passed to a .PEM file.
curl_setopt($ch, \CURLOPT_CAINFO, $certpath);
return;
}
$caPathOrFile = CaBundle::getSystemCaRootBundlePath();
if (is_dir($caPathOrFile) || (is_link($caPathOrFile) && is_dir(readlink($caPathOrFile)))) {
curl_setopt($ch, \CURLOPT_CAPATH, $caPathOrFile);
return;
}
curl_setopt($ch, \CURLOPT_CAINFO, $caPathOrFile);
}
/**
* Method to get a response object from a server response.
*
* @param string $content The complete server response, including headers
* as a string if the response has no errors.
* @param array $info The cURL request information.
*
* @return Response
*
* @since 1.0
* @throws InvalidResponseCodeException
*/
protected function getResponse($content, $info)
{
// Try to get header size
if (isset($info['header_size'])) {
$headerString = trim(substr($content, 0, $info['header_size']));
$headerArray = explode("\r\n\r\n", $headerString);
// Get the last set of response headers as an array.
$headers = explode("\r\n", array_pop($headerArray));
// Set the body for the response.
$body = substr($content, $info['header_size']);
} else {
// Fallback and try to guess header count by redirect count
// Get the number of redirects that occurred.
$redirects = $info['redirect_count'] ?? 0;
/*
* Split the response into headers and body. If cURL encountered redirects, the headers for the redirected requests will
* also be included. So we split the response into header + body + the number of redirects and only use the last two
* sections which should be the last set of headers and the actual body.
*/
$response = explode("\r\n\r\n", $content, 2 + $redirects);
// Set the body for the response.
$body = array_pop($response);
// Get the last set of response headers as an array.
$headers = explode("\r\n", array_pop($response));
}
// Get the response code from the first offset of the response headers.
preg_match('/[0-9]{3}/', array_shift($headers), $matches);
$code = \count($matches) ? $matches[0] : null;
if (!is_numeric($code)) {
// No valid response code was detected.
throw new InvalidResponseCodeException('No HTTP response code found.');
}
$statusCode = (int) $code;
$verifiedHeaders = $this->processHeaders($headers);
$streamInterface = new StreamResponse('php://memory', 'rw');
$streamInterface->write($body);
return new Response($streamInterface, $statusCode, $verifiedHeaders);
}
/**
* Method to check if HTTP transport cURL is available for use
*
* @return boolean True if available, else false
*
* @since 1.0
*/
public static function isSupported()
{
return \function_exists('curl_version') && curl_version();
}
/**
* Get the cURL constant for a HTTP protocol version
*
* @param string $version The HTTP protocol version to use
*
* @return integer
*
* @since 1.3.1
*/
private function mapProtocolVersion(string $version): int
{
switch ($version) {
case '1.0':
return \CURL_HTTP_VERSION_1_0;
case '1.1':
return \CURL_HTTP_VERSION_1_1;
case '2.0':
case '2':
if (\defined('CURL_HTTP_VERSION_2')) {
return \CURL_HTTP_VERSION_2;
}
}
return \CURL_HTTP_VERSION_NONE;
}
/**
* Check if redirects are allowed
*
* @return boolean
*
* @since 1.2.1
*/
private function redirectsAllowed(): bool
{
return true;
}
}

View File

@ -0,0 +1,286 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http\Transport;
use Joomla\Http\AbstractTransport;
use Joomla\Http\Exception\InvalidResponseCodeException;
use Joomla\Http\Response;
use Joomla\Uri\Uri;
use Joomla\Uri\UriInterface;
use Laminas\Diactoros\Stream as StreamResponse;
/**
* HTTP transport class for using sockets directly.
*
* @since 1.0
*/
class Socket extends AbstractTransport
{
/**
* Reusable socket connections.
*
* @var array
* @since 1.0
*/
protected $connections;
/**
* Send a request to the server and return a Response object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param UriInterface $uri The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param string $userAgent The optional user agent string to send with the request.
*
* @return Response
*
* @since 1.0
* @throws \RuntimeException
*/
public function request($method, UriInterface $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null)
{
$connection = $this->connect($uri, $timeout);
// Make sure the connection is alive and valid.
if (!\is_resource($connection)) {
throw new \RuntimeException('Not connected to server.');
}
// Make sure the connection has not timed out.
$meta = stream_get_meta_data($connection);
if ($meta['timed_out']) {
throw new \RuntimeException('Server connection timed out.');
}
// Get the request path from the URI object.
$path = $uri->toString(['path', 'query']);
// If we have data to send make sure our request is setup for it.
if (!empty($data)) {
// If the data is not a scalar value encode it to be sent with the request.
if (!is_scalar($data)) {
$data = http_build_query($data);
}
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
}
// Add the relevant headers.
$headers['Content-Length'] = \strlen($data);
}
// Configure protocol version, use transport's default if not set otherwise.
$protocolVersion = $this->getOption('protocolVersion', '1.1');
// Build the request payload.
$request = [];
$request[] = strtoupper($method) . ' ' . ((empty($path)) ? '/' : $path) . ' HTTP/' . $protocolVersion;
if (!isset($headers['Host'])) {
$request[] = 'Host: ' . $uri->getHost();
}
// If an explicit user agent is given use it.
if (isset($userAgent)) {
$headers['User-Agent'] = $userAgent;
}
// If we have a username then we include basic authentication credentials.
if ($uri->getUser()) {
$authString = $uri->getUser() . ':' . $uri->getPass();
$headers['Authorization'] = 'Basic ' . base64_encode($authString);
}
// If there are custom headers to send add them to the request payload.
if (!empty($headers)) {
foreach ($headers as $key => $value) {
if (\is_array($value)) {
foreach ($value as $header) {
$request[] = "$key: $header";
}
} else {
$request[] = "$key: $value";
}
}
}
// Authentication, if needed
if ($this->getOption('userauth') && $this->getOption('passwordauth')) {
$request[] = 'Authorization: Basic ' . base64_encode($this->getOption('userauth') . ':' . $this->getOption('passwordauth'));
}
// Set any custom transport options
foreach ($this->getOption('transport.socket', []) as $value) {
$request[] = $value;
}
// If we have data to send add it to the request payload.
if (!empty($data)) {
$request[] = null;
$request[] = $data;
}
// Send the request to the server.
fwrite($connection, implode("\r\n", $request) . "\r\n\r\n");
// Get the response data from the server.
$content = '';
while (!feof($connection)) {
$content .= fgets($connection, 4096);
}
$content = $this->getResponse($content);
// Follow Http redirects
if ($content->getStatusCode() >= 301 && $content->getStatusCode() < 400 && $content->hasHeader('Location')) {
return $this->request($method, new Uri($content->getHeaderLine('Location')), $data, $headers, $timeout, $userAgent);
}
return $content;
}
/**
* Method to get a response object from a server response.
*
* @param string $content The complete server response, including headers.
*
* @return Response
*
* @since 1.0
* @throws \UnexpectedValueException
* @throws InvalidResponseCodeException
*/
protected function getResponse($content)
{
if (empty($content)) {
throw new \UnexpectedValueException('No content in response.');
}
// Split the response into headers and body.
$response = explode("\r\n\r\n", $content, 2);
// Get the response headers as an array.
$headers = explode("\r\n", $response[0]);
// Set the body for the response.
$body = empty($response[1]) ? '' : $response[1];
// Get the response code from the first offset of the response headers.
preg_match('/[0-9]{3}/', array_shift($headers), $matches);
$code = $matches[0];
if (!is_numeric($code)) {
// No valid response code was detected.
throw new InvalidResponseCodeException('No HTTP response code found.');
}
$statusCode = (int) $code;
$verifiedHeaders = $this->processHeaders($headers);
$streamInterface = new StreamResponse('php://memory', 'rw');
$streamInterface->write($body);
return new Response($streamInterface, $statusCode, $verifiedHeaders);
}
/**
* Method to connect to a server and get the resource.
*
* @param UriInterface $uri The URI to connect with.
* @param integer $timeout Read timeout in seconds.
*
* @return resource Socket connection resource.
*
* @since 1.0
* @throws \RuntimeException
*/
protected function connect(UriInterface $uri, $timeout = null)
{
$errno = null;
$err = null;
// Get the host from the uri.
$host = ($uri->isSsl()) ? 'ssl://' . $uri->getHost() : $uri->getHost();
// If the port is not explicitly set in the URI detect it.
if (!$uri->getPort()) {
$port = ($uri->getScheme() == 'https') ? 443 : 80;
} else {
// Use the set port.
$port = $uri->getPort();
}
// Build the connection key for resource memory caching.
$key = md5($host . $port);
// If the connection already exists, use it.
if (!empty($this->connections[$key]) && \is_resource($this->connections[$key])) {
// Connection reached EOF, cannot be used anymore
$meta = stream_get_meta_data($this->connections[$key]);
if ($meta['eof']) {
if (!fclose($this->connections[$key])) {
throw new \RuntimeException('Cannot close connection');
}
} elseif (!$meta['timed_out']) {
// Make sure the connection has not timed out.
return $this->connections[$key];
}
}
if (!is_numeric($timeout)) {
$timeout = ini_get('default_socket_timeout');
}
// Capture PHP errors
error_clear_last();
// PHP sends a warning if the uri does not exists; we silence it and throw an exception instead.
// Attempt to connect to the server
$connection = @fsockopen($host, $port, $errno, $err, $timeout);
if (!$connection) {
$error = error_get_last();
if ($error === null || $error['message'] === '') {
// Error but nothing from php? Create our own
$error = [
'message' => sprintf('Could not connect to resource %s: %s (%d)', $uri, $err, $errno),
];
}
throw new \RuntimeException($error['message']);
}
// Since the connection was successful let's store it in case we need to use it later.
$this->connections[$key] = $connection;
stream_set_timeout($this->connections[$key], (int) $timeout);
return $this->connections[$key];
}
/**
* Method to check if http transport socket available for use
*
* @return boolean True if available else false
*
* @since 1.0
*/
public static function isSupported()
{
return \function_exists('fsockopen') && \is_callable('fsockopen');
}
}

View File

@ -0,0 +1,235 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http\Transport;
use Composer\CaBundle\CaBundle;
use Joomla\Http\AbstractTransport;
use Joomla\Http\Exception\InvalidResponseCodeException;
use Joomla\Http\Response;
use Joomla\Uri\Uri;
use Joomla\Uri\UriInterface;
use Laminas\Diactoros\Stream as StreamResponse;
/**
* HTTP transport class for using PHP streams.
*
* @since 1.0
*/
class Stream extends AbstractTransport
{
/**
* Send a request to the server and return a Response object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param UriInterface $uri The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param string $userAgent The optional user agent string to send with the request.
*
* @return Response
*
* @since 1.0
* @throws \RuntimeException
*/
public function request($method, UriInterface $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null)
{
// Create the stream context options array with the required method offset.
$options = ['method' => strtoupper($method)];
// If data exists let's encode it and make sure our Content-Type header is set.
if (isset($data)) {
// If the data is a scalar value simply add it to the stream context options.
if (is_scalar($data)) {
$options['content'] = $data;
} else {
// Otherwise we need to encode the value first.
$options['content'] = http_build_query($data);
}
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
}
// Add the relevant headers.
$headers['Content-Length'] = \strlen($options['content']);
}
// If an explicit timeout is given user it.
if (isset($timeout)) {
$options['timeout'] = (int) $timeout;
}
// If an explicit user agent is given use it.
if (isset($userAgent)) {
$options['user_agent'] = $userAgent;
}
// Ignore HTTP errors so that we can capture them.
$options['ignore_errors'] = 1;
// Follow redirects.
$options['follow_location'] = (int) $this->getOption('follow_location', 1);
// Configure protocol version, use transport's default if not set otherwise.
$options['follow_location'] = $this->getOption('protocolVersion', '1.0');
// Add the proxy configuration if enabled
if ($this->getOption('proxy.enabled', false)) {
$options['request_fulluri'] = true;
if ($this->getOption('proxy.host') && $this->getOption('proxy.port')) {
$options['proxy'] = $this->getOption('proxy.host') . ':' . (int) $this->getOption('proxy.port');
}
// If authentication details are provided, add those as well
if ($this->getOption('proxy.user') && $this->getOption('proxy.password')) {
$headers['Proxy-Authorization'] = 'Basic ' . base64_encode($this->getOption('proxy.user') . ':' . $this->getOption('proxy.password'));
}
}
// Build the headers string for the request.
if (!empty($headers)) {
$headerString = '';
foreach ($headers as $key => $value) {
if (\is_array($value)) {
foreach ($value as $header) {
$headerString .= "$key: $header\r\n";
}
} else {
$headerString .= "$key: $value\r\n";
}
}
// Add the headers string into the stream context options array.
$options['header'] = trim($headerString, "\r\n");
}
// Authentication, if needed
if ($uri instanceof Uri && $this->getOption('userauth') && $this->getOption('passwordauth')) {
$uri->setUser($this->getOption('userauth'));
$uri->setPass($this->getOption('passwordauth'));
}
// Set any custom transport options
foreach ($this->getOption('transport.stream', []) as $key => $value) {
$options[$key] = $value;
}
// Get the current context options.
$contextOptions = stream_context_get_options(stream_context_get_default());
// Add our options to the currently defined options, if any.
$contextOptions['http'] = isset($contextOptions['http']) ? array_merge($contextOptions['http'], $options) : $options;
// Create the stream context for the request.
$streamOptions = [
'http' => $options,
'ssl' => [
'verify_peer' => true,
'verify_depth' => 5,
'verify_peer_name' => true,
],
];
// The cacert may be a file or path
$certpath = $this->getOption('stream.certpath', CaBundle::getSystemCaRootBundlePath());
if (is_dir($certpath)) {
$streamOptions['ssl']['capath'] = $certpath;
} else {
$streamOptions['ssl']['cafile'] = $certpath;
}
$context = stream_context_create($streamOptions);
// Capture PHP errors
error_clear_last();
// Open the stream for reading.
$stream = @fopen((string) $uri, 'r', false, $context);
if (!$stream) {
$error = error_get_last();
if ($error === null || $error['message'] === '') {
// Error but nothing from php? Create our own
$error = [
'message' => sprintf('Could not connect to resource %s', $uri),
];
}
throw new \RuntimeException($error['message']);
}
// Get the metadata for the stream, including response headers.
$metadata = stream_get_meta_data($stream);
// Get the contents from the stream.
$content = stream_get_contents($stream);
// Close the stream.
fclose($stream);
$headers = [];
if (isset($metadata['wrapper_data']['headers'])) {
$headers = $metadata['wrapper_data']['headers'];
} elseif (isset($metadata['wrapper_data'])) {
$headers = $metadata['wrapper_data'];
}
return $this->getResponse($headers, $content);
}
/**
* Method to get a response object from a server response.
*
* @param array $headers The response headers as an array.
* @param string $body The response body as a string.
*
* @return Response
*
* @since 1.0
* @throws InvalidResponseCodeException
*/
protected function getResponse(array $headers, $body)
{
// Get the response code from the first offset of the response headers.
preg_match('/[0-9]{3}/', array_shift($headers), $matches);
$code = $matches[0];
if (!is_numeric($code)) {
// No valid response code was detected.
throw new InvalidResponseCodeException('No HTTP response code found.');
}
$statusCode = (int) $code;
$verifiedHeaders = $this->processHeaders($headers);
$streamInterface = new StreamResponse('php://memory', 'rw');
$streamInterface->write($body);
return new Response($streamInterface, $statusCode, $verifiedHeaders);
}
/**
* Method to check if http transport stream available for use
*
* @return boolean True if available else false
*
* @since 1.0
*/
public static function isSupported()
{
return \function_exists('fopen') && \is_callable('fopen') && ini_get('allow_url_fopen');
}
}

View File

@ -0,0 +1,45 @@
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2021 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http;
use Joomla\Uri\UriInterface;
/**
* HTTP transport class interface.
*
* @since 1.0
*/
interface TransportInterface
{
/**
* Send a request to the server and return a Response object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param UriInterface $uri The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param string $userAgent The optional user agent string to send with the request.
*
* @return Response
*
* @since 1.0
*/
public function request($method, UriInterface $uri, $data = null, array $headers = [], $timeout = null, $userAgent = null);
/**
* Method to check if HTTP transport layer available for using
*
* @return boolean True if available else false
*
* @since 1.0
*/
public static function isSupported();
}