aboutsummaryrefslogtreecommitdiffstats
path: root/src/SimplePie.php
diff options
context:
space:
mode:
Diffstat (limited to 'src/SimplePie.php')
-rw-r--r--src/SimplePie.php999
1 files changed, 618 insertions, 381 deletions
diff --git a/src/SimplePie.php b/src/SimplePie.php
index 1dfa39f..bbc5218 100644
--- a/src/SimplePie.php
+++ b/src/SimplePie.php
@@ -1,51 +1,16 @@
<?php
+// SPDX-FileCopyrightText: 2004-2023 Ryan Parman, Sam Sneddon, Ryan McCue
+// SPDX-License-Identifier: BSD-3-Clause
+
declare(strict_types=1);
-/**
- * SimplePie
- *
- * A PHP-Based RSS and Atom Feed Framework.
- * Takes the hard work out of managing a complete RSS/Atom solution.
- *
- * Copyright (c) 2004-2022, Ryan Parman, Sam Sneddon, Ryan McCue, and contributors
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without modification, are
- * permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice, this list of
- * conditions and the following disclaimer.
- *
- * * Redistributions in binary form must reproduce the above copyright notice, this list
- * of conditions and the following disclaimer in the documentation and/or other materials
- * provided with the distribution.
- *
- * * Neither the name of the SimplePie Team nor the names of its contributors may be used
- * to endorse or promote products derived from this software without specific prior
- * written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
- * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
- * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS
- * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * @package SimplePie
- * @copyright 2004-2016 Ryan Parman, Sam Sneddon, Ryan McCue
- * @author Ryan Parman
- * @author Sam Sneddon
- * @author Ryan McCue
- * @link http://simplepie.org/ SimplePie
- * @license http://www.opensource.org/licenses/bsd-license.php BSD License
- */
namespace SimplePie;
use InvalidArgumentException;
+use Psr\Http\Client\ClientInterface;
+use Psr\Http\Message\RequestFactoryInterface;
+use Psr\Http\Message\UriFactoryInterface;
use Psr\SimpleCache\CacheInterface;
use SimplePie\Cache\Base;
use SimplePie\Cache\BaseDataCache;
@@ -54,12 +19,15 @@ use SimplePie\Cache\DataCache;
use SimplePie\Cache\NameFilter;
use SimplePie\Cache\Psr16;
use SimplePie\Content\Type\Sniffer;
+use SimplePie\Exception as SimplePieException;
+use SimplePie\HTTP\Client;
+use SimplePie\HTTP\ClientException;
+use SimplePie\HTTP\FileClient;
+use SimplePie\HTTP\Psr18Client;
+use SimplePie\HTTP\Response;
/**
* SimplePie
- *
- * @package SimplePie
- * @subpackage API
*/
class SimplePie
{
@@ -71,7 +39,7 @@ class SimplePie
/**
* SimplePie Version
*/
- public const VERSION = '1.8.0';
+ public const VERSION = '1.9.0';
/**
* SimplePie Website URL
@@ -412,16 +380,21 @@ class SimplePie
public const FILE_SOURCE_FILE_GET_CONTENTS = 16;
/**
- * @var array Raw data
+ * @internal Default value of the HTTP Accept header when fetching/locating feeds
+ */
+ public const DEFAULT_HTTP_ACCEPT_HEADER = 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1';
+
+ /**
+ * @var array<string, mixed> Raw data
* @access private
*/
public $data = [];
/**
- * @var mixed Error string
+ * @var string|string[]|null Error string (or array when multiple feeds are initialized)
* @access private
*/
- public $error;
+ public $error = null;
/**
* @var int HTTP status code
@@ -431,7 +404,7 @@ class SimplePie
public $status_code = 0;
/**
- * @var object Instance of \SimplePie\Sanitize (or other class)
+ * @var Sanitize instance of Sanitize class
* @see SimplePie::set_sanitize_class()
* @access private
*/
@@ -452,21 +425,20 @@ class SimplePie
public $feed_url;
/**
- * @var string Original feed URL, or new feed URL iff HTTP 301 Moved Permanently
+ * @var ?string Original feed URL, or new feed URL iff HTTP 301 Moved Permanently
* @see SimplePie::subscribe_url()
* @access private
*/
public $permanent_url = null;
/**
- * @var object Instance of \SimplePie\File to use as a feed
+ * @var File Instance of File class to use as a feed
* @see SimplePie::set_file()
- * @access private
*/
- public $file;
+ private $file;
/**
- * @var string Raw feed data
+ * @var string|false Raw feed data
* @see SimplePie::set_raw_data()
* @access private
*/
@@ -480,7 +452,7 @@ class SimplePie
public $timeout = 10;
/**
- * @var array Custom curl options
+ * @var array<int, mixed> Custom curl options
* @see SimplePie::set_curl_options()
* @access private
*/
@@ -551,7 +523,7 @@ class SimplePie
public $cache_location = './cache';
/**
- * @var string Function that creates the cache filename
+ * @var string&(callable(string): string) Function that creates the cache filename
* @see SimplePie::set_cache_name_function()
* @access private
*/
@@ -573,7 +545,7 @@ class SimplePie
public $input_encoding = false;
/**
- * @var int Feed Autodiscovery Level
+ * @var self::LOCATOR_* Feed Autodiscovery Level
* @see SimplePie::set_autodiscovery_level()
* @access private
*/
@@ -582,7 +554,7 @@ class SimplePie
/**
* Class registry object
*
- * @var \SimplePie\Registry
+ * @var Registry
*/
public $registry;
@@ -594,7 +566,7 @@ class SimplePie
public $max_checked_feeds = 10;
/**
- * @var array All the feeds found during the autodiscovery process
+ * @var array<Response>|null All the feeds found during the autodiscovery process
* @see SimplePie::get_all_discovered_feeds()
* @access private
*/
@@ -608,27 +580,27 @@ class SimplePie
public $image_handler = '';
/**
- * @var array Stores the URLs when multiple feeds are being initialized.
+ * @var array<string> Stores the URLs when multiple feeds are being initialized.
* @see SimplePie::set_feed_url()
* @access private
*/
public $multifeed_url = [];
/**
- * @var array Stores SimplePie objects when multiple feeds initialized.
+ * @var array<int, static> Stores SimplePie objects when multiple feeds initialized.
* @access private
*/
public $multifeed_objects = [];
/**
- * @var array Stores the get_object_vars() array for use with multifeeds.
+ * @var array<mixed> Stores the get_object_vars() array for use with multifeeds.
* @see SimplePie::set_feed_url()
* @access private
*/
public $config_settings = null;
/**
- * @var integer Stores the number of items to return per-feed with multifeeds.
+ * @var int Stores the number of items to return per-feed with multifeeds.
* @see SimplePie::set_item_limit()
* @access private
*/
@@ -641,28 +613,28 @@ class SimplePie
public $check_modified = false;
/**
- * @var array Stores the default attributes to be stripped by strip_attributes().
+ * @var array<string> Stores the default attributes to be stripped by strip_attributes().
* @see SimplePie::strip_attributes()
* @access private
*/
public $strip_attributes = ['bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'];
/**
- * @var array Stores the default attributes to add to different tags by add_attributes().
+ * @var array<string, array<string, string>> Stores the default attributes to add to different tags by add_attributes().
* @see SimplePie::add_attributes()
* @access private
*/
public $add_attributes = ['audio' => ['preload' => 'none'], 'iframe' => ['sandbox' => 'allow-scripts allow-same-origin'], 'video' => ['preload' => 'none']];
/**
- * @var array Stores the default tags to be stripped by strip_htmltags().
+ * @var array<string> Stores the default tags to be stripped by strip_htmltags().
* @see SimplePie::strip_htmltags()
* @access private
*/
public $strip_htmltags = ['base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'];
/**
- * @var array Stores the default attributes to be renamed by rename_attributes().
+ * @var string[]|string Stores the default attributes to be renamed by rename_attributes().
* @see SimplePie::rename_attributes()
* @access private
*/
@@ -675,6 +647,14 @@ class SimplePie
public $enable_exceptions = false;
/**
+ * @var Client|null
+ */
+ private $http_client = null;
+
+ /** @var bool Whether HTTP client has been injected */
+ private $http_client_injected = false;
+
+ /**
* The SimplePie class contains feed level data and options
*
* To use SimplePie, create the SimplePie object with no parameters. You can
@@ -691,8 +671,7 @@ class SimplePie
public function __construct()
{
if (version_compare(PHP_VERSION, '7.2', '<')) {
- trigger_error('Please upgrade to PHP 7.2 or newer.');
- die();
+ exit('Please upgrade to PHP 7.2 or newer.');
}
$this->set_useragent();
@@ -700,8 +679,8 @@ class SimplePie
$this->set_cache_namefilter(new CallableNameFilter($this->cache_name_function));
// Other objects, instances created here so we can set options on them
- $this->sanitize = new \SimplePie\Sanitize();
- $this->registry = new \SimplePie\Registry();
+ $this->sanitize = new Sanitize();
+ $this->registry = new Registry();
if (func_num_args() > 0) {
trigger_error('Passing parameters to the constructor is no longer supported. Please use set_feed_url(), set_cache_location(), and set_cache_duration() directly.', \E_USER_DEPRECATED);
@@ -723,6 +702,7 @@ class SimplePie
/**
* Used for converting object to a string
+ * @return string
*/
public function __toString()
{
@@ -731,6 +711,7 @@ class SimplePie
/**
* Remove items that link back to this before destroying this object
+ * @return void
*/
public function __destruct()
{
@@ -758,10 +739,11 @@ class SimplePie
*
* @since 1.1
* @param bool $enable Force the given data/URL to be treated as a feed
+ * @return void
*/
- public function force_feed($enable = false)
+ public function force_feed(bool $enable = false)
{
- $this->force_feed = (bool) $enable;
+ $this->force_feed = $enable;
}
/**
@@ -771,18 +753,20 @@ class SimplePie
* website you want to try to use auto-discovery on. This takes priority
* over any set raw data.
*
- * You can set multiple feeds to mash together by passing an array instead
+ * Deprecated since 1.9.0: You can set multiple feeds to mash together by passing an array instead
* of a string for the $url. Remember that with each additional feed comes
* additional processing and resources.
*
* @since 1.0 Preview Release
* @see set_raw_data()
- * @param string|array $url This is the URL (or array of URLs) that you want to parse.
+ * @param string|string[] $url This is the URL (or (deprecated) array of URLs) that you want to parse.
+ * @return void
*/
public function set_feed_url($url)
{
$this->multifeed_url = [];
if (is_array($url)) {
+ trigger_error('Fetching multiple feeds with single SimplePie instance is deprecated since SimplePie 1.9.0, create one SimplePie instance per feed and use SimplePie::merge_items to get a single list of items.', \E_USER_DEPRECATED);
foreach ($url as $value) {
$this->multifeed_url[] = $this->registry->call(Misc::class, 'fix_protocol', [$value, 1]);
}
@@ -793,20 +777,22 @@ class SimplePie
}
/**
- * Set an instance of {@see \SimplePie\File} to use as a feed
+ * Set an instance of {@see File} to use as a feed
+ *
+ * @deprecated since SimplePie 1.9.0, use \SimplePie\SimplePie::set_http_client() or \SimplePie\SimplePie::set_raw_data() instead.
*
- * @param \SimplePie\File &$file
+ * @param File &$file
* @return bool True on success, false on failure
*/
- public function set_file(&$file)
+ public function set_file(File &$file)
{
- if ($file instanceof \SimplePie\File) {
- $this->feed_url = $file->url;
- $this->permanent_url = $this->feed_url;
- $this->file =& $file;
- return true;
- }
- return false;
+ // trigger_error(sprintf('SimplePie\SimplePie::set_file() is deprecated since SimplePie 1.9.0, please use "SimplePie\SimplePie::set_http_client()" or "SimplePie\SimplePie::set_raw_data()" instead.'), \E_USER_DEPRECATED);
+
+ $this->feed_url = $file->get_final_requested_uri();
+ $this->permanent_url = $this->feed_url;
+ $this->file = &$file;
+
+ return true;
}
/**
@@ -821,13 +807,28 @@ class SimplePie
* @since 1.0 Beta 3
* @param string $data RSS or Atom data as a string.
* @see set_feed_url()
+ * @return void
*/
- public function set_raw_data($data)
+ public function set_raw_data(string $data)
{
$this->raw_data = $data;
}
/**
+ * Set a PSR-18 client and PSR-17 factories
+ *
+ * Allows you to use your own HTTP client implementations.
+ * This will become required with SimplePie 2.0.0.
+ */
+ final public function set_http_client(
+ ClientInterface $http_client,
+ RequestFactoryInterface $request_factory,
+ UriFactoryInterface $uri_factory
+ ): void {
+ $this->http_client = new Psr18Client($http_client, $request_factory, $uri_factory);
+ }
+
+ /**
* Set the default timeout for fetching remote feeds
*
* This allows you to change the maximum time the feed's server to respond
@@ -835,10 +836,32 @@ class SimplePie
*
* @since 1.0 Beta 3
* @param int $timeout The maximum number of seconds to spend waiting to retrieve a feed.
+ * @return void
*/
- public function set_timeout($timeout = 10)
+ public function set_timeout(int $timeout = 10)
{
+ if ($this->http_client_injected) {
+ throw new SimplePieException(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure timeout in your HTTP client instead.',
+ __METHOD__,
+ self::class
+ ));
+ }
+
$this->timeout = (int) $timeout;
+
+ // Reset a possible existing FileClient,
+ // so a new client with the changed value will be created
+ if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
+ $this->http_client = null;
+ } elseif (is_object($this->http_client)) {
+ // Trigger notice if a PSR-18 client was set
+ trigger_error(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure the timeout in your HTTP client instead.',
+ __METHOD__,
+ get_class($this)
+ ), \E_USER_NOTICE);
+ }
}
/**
@@ -847,11 +870,33 @@ class SimplePie
* This allows you to change default curl options
*
* @since 1.0 Beta 3
- * @param array $curl_options Curl options to add to default settings
+ * @param array<int, mixed> $curl_options Curl options to add to default settings
+ * @return void
*/
public function set_curl_options(array $curl_options = [])
{
+ if ($this->http_client_injected) {
+ throw new SimplePieException(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure custom curl options in your HTTP client instead.',
+ __METHOD__,
+ self::class
+ ));
+ }
+
$this->curl_options = $curl_options;
+
+ // Reset a possible existing FileClient,
+ // so a new client with the changed value will be created
+ if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
+ $this->http_client = null;
+ } elseif (is_object($this->http_client)) {
+ // Trigger notice if a PSR-18 client was set
+ trigger_error(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure the curl options in your HTTP client instead.',
+ __METHOD__,
+ get_class($this)
+ ), \E_USER_NOTICE);
+ }
}
/**
@@ -859,10 +904,32 @@ class SimplePie
*
* @since 1.0 Beta 3
* @param bool $enable Force fsockopen() to be used
+ * @return void
*/
- public function force_fsockopen($enable = false)
+ public function force_fsockopen(bool $enable = false)
{
- $this->force_fsockopen = (bool) $enable;
+ if ($this->http_client_injected) {
+ throw new SimplePieException(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure fsockopen in your HTTP client instead.',
+ __METHOD__,
+ self::class
+ ));
+ }
+
+ $this->force_fsockopen = $enable;
+
+ // Reset a possible existing FileClient,
+ // so a new client with the changed value will be created
+ if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
+ $this->http_client = null;
+ } elseif (is_object($this->http_client)) {
+ // Trigger notice if a PSR-18 client was set
+ trigger_error(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure fsockopen in your HTTP client instead.',
+ __METHOD__,
+ get_class($this)
+ ), \E_USER_NOTICE);
+ }
}
/**
@@ -873,16 +940,17 @@ class SimplePie
*
* @since 1.0 Preview Release
* @param bool $enable Enable caching
+ * @return void
*/
- public function enable_cache($enable = true)
+ public function enable_cache(bool $enable = true)
{
- $this->enable_cache = (bool) $enable;
+ $this->enable_cache = $enable;
}
/**
* Set a PSR-16 implementation as cache
*
- * @param CacheInterface $psr16cache The PSR-16 cache implementation
+ * @param CacheInterface $cache The PSR-16 cache implementation
*
* @return void
*/
@@ -902,11 +970,12 @@ class SimplePie
* @deprecated since SimplePie 1.8.0, expired cache will not be used anymore.
*
* @param bool $enable Force use of cache on fail.
+ * @return void
*/
- public function force_cache_fallback($enable = false)
+ public function force_cache_fallback(bool $enable = false)
{
// @trigger_error(sprintf('SimplePie\SimplePie::force_cache_fallback() is deprecated since SimplePie 1.8.0, expired cache will not be used anymore.'), \E_USER_DEPRECATED);
- $this->force_cache_fallback = (bool) $enable;
+ $this->force_cache_fallback = $enable;
}
/**
@@ -914,10 +983,11 @@ class SimplePie
* cached
*
* @param int $seconds The feed content cache duration
+ * @return void
*/
- public function set_cache_duration($seconds = 3600)
+ public function set_cache_duration(int $seconds = 3600)
{
- $this->cache_duration = (int) $seconds;
+ $this->cache_duration = $seconds;
}
/**
@@ -925,23 +995,25 @@ class SimplePie
* be cached
*
* @param int $seconds The autodiscovered feed URL cache duration.
+ * @return void
*/
- public function set_autodiscovery_cache_duration($seconds = 604800)
+ public function set_autodiscovery_cache_duration(int $seconds = 604800)
{
- $this->autodiscovery_cache_duration = (int) $seconds;
+ $this->autodiscovery_cache_duration = $seconds;
}
/**
* Set the file system location where the cached files should be stored
*
- * @deprecated since SimplePie 1.8.0, use \SimplePie\SimplePie::set_cache() instead.
+ * @deprecated since SimplePie 1.8.0, use SimplePie::set_cache() instead.
*
* @param string $location The file system location.
+ * @return void
*/
- public function set_cache_location($location = './cache')
+ public function set_cache_location(string $location = './cache')
{
// @trigger_error(sprintf('SimplePie\SimplePie::set_cache_location() is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache()" instead.'), \E_USER_DEPRECATED);
- $this->cache_location = (string) $location;
+ $this->cache_location = $location;
}
/**
@@ -950,7 +1022,7 @@ class SimplePie
* @param string $url The URL of the feed to be cached.
* @return string A filename (i.e. hash, without path and without extension).
*/
- public function get_cache_filename($url)
+ public function get_cache_filename(string $url)
{
// Append custom parameters to the URL to avoid cache pollution in case of multiple calls with different parameters.
$url .= $this->force_feed ? '#force_feed' : '';
@@ -958,7 +1030,7 @@ class SimplePie
if ($this->timeout != 10) {
$options[CURLOPT_TIMEOUT] = $this->timeout;
}
- if ($this->useragent !== \SimplePie\Misc::get_default_useragent()) {
+ if ($this->useragent !== Misc::get_default_useragent()) {
$options[CURLOPT_USERAGENT] = $this->useragent;
}
if (!empty($this->curl_options)) {
@@ -978,10 +1050,11 @@ class SimplePie
* Set whether feed items should be sorted into reverse chronological order
*
* @param bool $enable Sort as reverse chronological order.
+ * @return void
*/
- public function enable_order_by_date($enable = true)
+ public function enable_order_by_date(bool $enable = true)
{
- $this->order_by_date = (bool) $enable;
+ $this->order_by_date = $enable;
}
/**
@@ -990,7 +1063,8 @@ class SimplePie
* This overrides the encoding reported by the feed, however it will fall
* back to the normal encoding detection if the override fails
*
- * @param string $encoding Character encoding
+ * @param string|false $encoding Character encoding
+ * @return void
*/
public function set_input_encoding($encoding = false)
{
@@ -1004,25 +1078,25 @@ class SimplePie
/**
* Set how much feed autodiscovery to do
*
- * @see \SimplePie\SimplePie::LOCATOR_NONE
- * @see \SimplePie\SimplePie::LOCATOR_AUTODISCOVERY
- * @see \SimplePie\SimplePie::LOCATOR_LOCAL_EXTENSION
- * @see \SimplePie\SimplePie::LOCATOR_LOCAL_BODY
- * @see \SimplePie\SimplePie::LOCATOR_REMOTE_EXTENSION
- * @see \SimplePie\SimplePie::LOCATOR_REMOTE_BODY
- * @see \SimplePie\SimplePie::LOCATOR_ALL
- * @param int $level Feed Autodiscovery Level (level can be a combination of the above constants, see bitwise OR operator)
+ * @see self::LOCATOR_NONE
+ * @see self::LOCATOR_AUTODISCOVERY
+ * @see self::LOCATOR_LOCAL_EXTENSION
+ * @see self::LOCATOR_LOCAL_BODY
+ * @see self::LOCATOR_REMOTE_EXTENSION
+ * @see self::LOCATOR_REMOTE_BODY
+ * @see self::LOCATOR_ALL
+ * @param self::LOCATOR_* $level Feed Autodiscovery Level (level can be a combination of the above constants, see bitwise OR operator)
+ * @return void
*/
- public function set_autodiscovery_level($level = self::LOCATOR_ALL)
+ public function set_autodiscovery_level(int $level = self::LOCATOR_ALL)
{
- $this->autodiscovery = (int) $level;
+ $this->autodiscovery = $level;
}
/**
* Get the class registry
*
* Use this to override SimplePie's default classes
- * @see \SimplePie\Registry
*
* @return Registry
*/
@@ -1036,13 +1110,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see set_cache()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Cache> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_cache_class($class = Cache::class)
+ public function set_cache_class(string $class = Cache::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::set_cache()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::set_cache()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Cache::class, $class, true);
}
@@ -1052,13 +1126,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Locator> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_locator_class($class = Locator::class)
+ public function set_locator_class(string $class = Locator::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Locator::class, $class, true);
}
@@ -1068,13 +1142,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Parser> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_parser_class($class = Parser::class)
+ public function set_parser_class(string $class = Parser::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Parser::class, $class, true);
}
@@ -1084,13 +1158,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<File> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_file_class($class = File::class)
+ public function set_file_class(string $class = File::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(File::class, $class, true);
}
@@ -1100,13 +1174,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Sanitize> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_sanitize_class($class = Sanitize::class)
+ public function set_sanitize_class(string $class = Sanitize::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Sanitize::class, $class, true);
}
@@ -1116,13 +1190,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Item> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_item_class($class = Item::class)
+ public function set_item_class(string $class = Item::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Item::class, $class, true);
}
@@ -1132,13 +1206,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Author> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_author_class($class = Author::class)
+ public function set_author_class(string $class = Author::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Author::class, $class, true);
}
@@ -1148,13 +1222,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Category> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_category_class($class = Category::class)
+ public function set_category_class(string $class = Category::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Category::class, $class, true);
}
@@ -1164,13 +1238,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Enclosure> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_enclosure_class($class = Enclosure::class)
+ public function set_enclosure_class(string $class = Enclosure::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Enclosure::class, $class, true);
}
@@ -1180,13 +1254,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Caption> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_caption_class($class = Caption::class)
+ public function set_caption_class(string $class = Caption::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Caption::class, $class, true);
}
@@ -1196,13 +1270,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Copyright> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_copyright_class($class = Copyright::class)
+ public function set_copyright_class(string $class = Copyright::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Copyright::class, $class, true);
}
@@ -1212,13 +1286,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Credit> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_credit_class($class = Credit::class)
+ public function set_credit_class(string $class = Credit::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Credit::class, $class, true);
}
@@ -1228,13 +1302,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Rating> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_rating_class($class = Rating::class)
+ public function set_rating_class(string $class = Rating::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Rating::class, $class, true);
}
@@ -1244,13 +1318,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Restriction> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_restriction_class($class = Restriction::class)
+ public function set_restriction_class(string $class = Restriction::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Restriction::class, $class, true);
}
@@ -1260,13 +1334,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Sniffer> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_content_type_sniffer_class($class = Sniffer::class)
+ public function set_content_type_sniffer_class(string $class = Sniffer::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Sniffer::class, $class, true);
}
@@ -1276,13 +1350,13 @@ class SimplePie
*
* @deprecated since SimplePie 1.3, use {@see get_registry()} instead
*
- * @param string $class Name of custom class
+ * @param class-string<Source> $class Name of custom class
*
- * @return boolean True on success, false otherwise
+ * @return bool True on success, false otherwise
*/
- public function set_source_class($class = Source::class)
+ public function set_source_class(string $class = Source::class)
{
- // trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
+ trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.3, please use "SimplePie\SimplePie::get_registry()" instead.', __METHOD__), \E_USER_DEPRECATED);
return $this->registry->register(Source::class, $class, true);
}
@@ -1291,14 +1365,36 @@ class SimplePie
* Set the user agent string
*
* @param string $ua New user agent string.
+ * @return void
*/
- public function set_useragent($ua = null)
+ public function set_useragent(?string $ua = null)
{
+ if ($this->http_client_injected) {
+ throw new SimplePieException(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure user agent string in your HTTP client instead.',
+ __METHOD__,
+ self::class
+ ));
+ }
+
if ($ua === null) {
- $ua = \SimplePie\Misc::get_default_useragent();
+ $ua = Misc::get_default_useragent();
}
$this->useragent = (string) $ua;
+
+ // Reset a possible existing FileClient,
+ // so a new client with the changed value will be created
+ if (is_object($this->http_client) && $this->http_client instanceof FileClient) {
+ $this->http_client = null;
+ } elseif (is_object($this->http_client)) {
+ // Trigger notice if a PSR-18 client was set
+ trigger_error(sprintf(
+ 'Using "%s()" has no effect, because you already provided a HTTP client with "%s::set_http_client()". Configure the useragent in your HTTP client instead.',
+ __METHOD__,
+ get_class($this)
+ ), \E_USER_NOTICE);
+ }
}
/**
@@ -1318,17 +1414,20 @@ class SimplePie
*
* @deprecated since SimplePie 1.8.0, use {@see set_cache_namefilter()} instead
*
- * @param mixed $function Callback function
+ * @param (string&(callable(string): string))|null $function Callback function
+ * @return void
*/
- public function set_cache_name_function($function = 'md5')
+ public function set_cache_name_function(?string $function = null)
{
// trigger_error(sprintf('"%s()" is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache_namefilter()" instead.', __METHOD__), \E_USER_DEPRECATED);
- if (is_callable($function)) {
- $this->cache_name_function = $function;
-
- $this->set_cache_namefilter(new CallableNameFilter($this->cache_name_function));
+ if ($function === null) {
+ $function = 'md5';
}
+
+ $this->cache_name_function = $function;
+
+ $this->set_cache_namefilter(new CallableNameFilter($this->cache_name_function));
}
/**
@@ -1338,16 +1437,17 @@ class SimplePie
* turns SimplePie into a dumb parser of feeds.
*
* @param bool $set Whether to set them or not
+ * @return void
*/
- public function set_stupidly_fast($set = false)
+ public function set_stupidly_fast(bool $set = false)
{
if ($set) {
$this->enable_order_by_date(false);
$this->remove_div(false);
$this->strip_comments(false);
- $this->strip_htmltags(false);
- $this->strip_attributes(false);
- $this->add_attributes(false);
+ $this->strip_htmltags([]);
+ $this->strip_attributes([]);
+ $this->add_attributes([]);
$this->set_image_handler(false);
$this->set_https_domains([]);
}
@@ -1357,33 +1457,48 @@ class SimplePie
* Set maximum number of feeds to check with autodiscovery
*
* @param int $max Maximum number of feeds to check
+ * @return void
*/
- public function set_max_checked_feeds($max = 10)
+ public function set_max_checked_feeds(int $max = 10)
{
- $this->max_checked_feeds = (int) $max;
+ $this->max_checked_feeds = $max;
}
- public function remove_div($enable = true)
+ /**
+ * @return void
+ */
+ public function remove_div(bool $enable = true)
{
$this->sanitize->remove_div($enable);
}
- public function strip_htmltags($tags = '', $encode = null)
+ /**
+ * @param string[]|string|false $tags Set a list of tags to strip, or set empty string to use default tags, or false to strip nothing.
+ * @return void
+ */
+ public function strip_htmltags($tags = '', ?bool $encode = null)
{
if ($tags === '') {
$tags = $this->strip_htmltags;
}
$this->sanitize->strip_htmltags($tags);
if ($encode !== null) {
- $this->sanitize->encode_instead_of_strip($tags);
+ $this->sanitize->encode_instead_of_strip($encode);
}
}
- public function encode_instead_of_strip($enable = true)
+ /**
+ * @return void
+ */
+ public function encode_instead_of_strip(bool $enable = true)
{
$this->sanitize->encode_instead_of_strip($enable);
}
+ /**
+ * @param string[]|string $attribs
+ * @return void
+ */
public function rename_attributes($attribs = '')
{
if ($attribs === '') {
@@ -1392,6 +1507,10 @@ class SimplePie
$this->sanitize->rename_attributes($attribs);
}
+ /**
+ * @param string[]|string $attribs
+ * @return void
+ */
public function strip_attributes($attribs = '')
{
if ($attribs === '') {
@@ -1400,6 +1519,10 @@ class SimplePie
$this->sanitize->strip_attributes($attribs);
}
+ /**
+ * @param array<string, array<string, string>>|'' $attribs
+ * @return void
+ */
public function add_attributes($attribs = '')
{
if ($attribs === '') {
@@ -1429,13 +1552,17 @@ class SimplePie
* more information.
*
* @param string $encoding
+ * @return void
*/
- public function set_output_encoding($encoding = 'UTF-8')
+ public function set_output_encoding(string $encoding = 'UTF-8')
{
$this->sanitize->set_output_encoding($encoding);
}
- public function strip_comments($strip = false)
+ /**
+ * @return void
+ */
+ public function strip_comments(bool $strip = false)
{
$this->sanitize->strip_comments($strip);
}
@@ -1449,32 +1576,33 @@ class SimplePie
* |q|@cite
*
* @since 1.0
- * @param array|null $element_attribute Element/attribute key/value pairs, null for default
+ * @param array<string, string|string[]>|null $element_attribute Element/attribute key/value pairs, null for default
+ * @return void
*/
- public function set_url_replacements($element_attribute = null)
+ public function set_url_replacements(?array $element_attribute = null)
{
$this->sanitize->set_url_replacements($element_attribute);
}
/**
* Set the list of domains for which to force HTTPS.
- * @see \SimplePie\Sanitize::set_https_domains()
- * @param array List of HTTPS domains. Example array('biz', 'example.com', 'example.org', 'www.example.net').
+ * @see Sanitize::set_https_domains()
+ * @param array<string> $domains List of HTTPS domains. Example array('biz', 'example.com', 'example.org', 'www.example.net').
+ * @return void
*/
- public function set_https_domains($domains = [])
+ public function set_https_domains(array $domains = [])
{
- if (is_array($domains)) {
- $this->sanitize->set_https_domains($domains);
- }
+ $this->sanitize->set_https_domains($domains);
}
/**
* Set the handler to enable the display of cached images.
*
- * @param string $page Web-accessible path to the handler_image.php file.
+ * @param string|false $page Web-accessible path to the handler_image.php file.
* @param string $qs The query string that the value should be passed to.
+ * @return void
*/
- public function set_image_handler($page = false, $qs = 'i')
+ public function set_image_handler($page = false, string $qs = 'i')
{
if ($page !== false) {
$this->sanitize->set_image_handler($page . '?' . $qs . '=');
@@ -1486,19 +1614,21 @@ class SimplePie
/**
* Set the limit for items returned per-feed with multifeeds
*
- * @param integer $limit The maximum number of items to return.
+ * @param int $limit The maximum number of items to return.
+ * @return void
*/
- public function set_item_limit($limit = 0)
+ public function set_item_limit(int $limit = 0)
{
- $this->item_limit = (int) $limit;
+ $this->item_limit = $limit;
}
/**
* Enable throwing exceptions
*
- * @param boolean $enable Should we throw exceptions, or use the old-style error property?
+ * @param bool $enable Should we throw exceptions, or use the old-style error property?
+ * @return void
*/
- public function enable_exceptions($enable = true)
+ public function enable_exceptions(bool $enable = true)
{
$this->enable_exceptions = $enable;
}
@@ -1510,7 +1640,7 @@ class SimplePie
* configuration options get processed, feeds are fetched, cached, and
* parsed, and all of that other good stuff.
*
- * @return boolean True if successful, false otherwise
+ * @return bool True if successful, false otherwise
*/
public function init()
{
@@ -1525,7 +1655,9 @@ class SimplePie
if ($xml_is_sane === null) {
$parser_check = xml_parser_create();
xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values);
- xml_parser_free($parser_check);
+ if (\PHP_VERSION_ID < 80000) {
+ xml_parser_free($parser_check);
+ }
$xml_is_sane = isset($values[0]['value']);
}
if (!$xml_is_sane) {
@@ -1535,7 +1667,7 @@ class SimplePie
// The default sanitize class gets set in the constructor, check if it has
// changed.
- if ($this->registry->get_class(Sanitize::class) !== 'SimplePie\Sanitize') {
+ if ($this->registry->get_class(Sanitize::class) !== Sanitize::class) {
$this->sanitize = $this->registry->create(Sanitize::class);
}
if (method_exists($this->sanitize, 'set_registry')) {
@@ -1544,14 +1676,25 @@ class SimplePie
// Pass whatever was set with config options over to the sanitizer.
// Pass the classes in for legacy support; new classes should use the registry instead
+ $cache = $this->registry->get_class(Cache::class);
+ \assert($cache !== null, 'Cache must be defined');
$this->sanitize->pass_cache_data(
$this->enable_cache,
$this->cache_location,
$this->cache_namefilter,
- $this->registry->get_class(Cache::class),
+ $cache,
$this->cache
);
- $this->sanitize->pass_file_data($this->registry->get_class(File::class), $this->timeout, $this->useragent, $this->force_fsockopen, $this->curl_options);
+
+ $http_client = $this->get_http_client();
+
+ if ($http_client instanceof Psr18Client) {
+ $this->sanitize->set_http_client(
+ $http_client->getHttpClient(),
+ $http_client->getRequestFactory(),
+ $http_client->getUriFactory()
+ );
+ }
if (!empty($this->multifeed_url)) {
$i = 0;
@@ -1587,7 +1730,7 @@ class SimplePie
$cache = $this->get_cache($this->feed_url);
}
- // Fetch the data via \SimplePie\File into $this->raw_data
+ // Fetch the data into $this->raw_data
if (($fetched = $this->fetch_data($cache)) === true) {
return true;
} elseif ($fetched === false) {
@@ -1651,7 +1794,7 @@ class SimplePie
$parser = $this->registry->create(Parser::class);
// If it's parsed fine
- if ($parser->parse($utf8_data, 'UTF-8', $this->permanent_url)) {
+ if ($parser->parse($utf8_data, 'UTF-8', $this->permanent_url ?? '')) {
$this->data = $parser->get_data();
if (!($this->get_type() & ~self::TYPE_NONE)) {
$this->error = "A feed could not be found at `$this->feed_url`. This does not appear to be a valid RSS or Atom feed.";
@@ -1662,11 +1805,12 @@ class SimplePie
if (isset($headers)) {
$this->data['headers'] = $headers;
}
- $this->data['build'] = \SimplePie\Misc::get_build();
+ $this->data['build'] = Misc::get_build();
// Cache the file if caching is enabled
$this->data['cache_expiration_time'] = $this->cache_duration + time();
- if ($cache && ! $cache->set_data($this->get_cache_filename($this->feed_url), $this->data, $this->cache_duration)) {
+
+ if ($cache && !$cache->set_data($this->get_cache_filename($this->feed_url), $this->data, $this->cache_duration)) {
trigger_error("$this->cache_location is not writable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING);
}
return true;
@@ -1675,7 +1819,7 @@ class SimplePie
}
if (isset($parser)) {
- // We have an error, just set \SimplePie\Misc::error to it and quit
+ // We have an error, just set Misc::error to it and quit
$this->error = $this->feed_url;
$this->error .= sprintf(' is invalid XML, likely due to invalid characters. XML error: %s at line %d, column %d', $parser->get_error_string(), $parser->get_current_line(), $parser->get_current_column());
} else {
@@ -1703,20 +1847,22 @@ class SimplePie
}
/**
- * Fetch the data via \SimplePie\File
+ * Fetch the data
*
* If the data is already cached, attempt to fetch it from there instead
+ *
* @param Base|DataCache|false $cache Cache handler, or false to not load from the cache
- * @return array|true Returns true if the data was loaded from the cache, or an array of HTTP headers and sniffed type
+ * @return array{array<string, string>, string}|bool Returns true if the data was loaded from the cache, or an array of HTTP headers and sniffed type
*/
protected function fetch_data(&$cache)
{
- if (is_object($cache) && $cache instanceof Base) {
+ if ($cache instanceof Base) {
// @trigger_error(sprintf('Providing $cache as "\SimplePie\Cache\Base" in %s() is deprecated since SimplePie 1.8.0, please provide "\SimplePie\Cache\DataCache" implementation instead.', __METHOD__), \E_USER_DEPRECATED);
$cache = new BaseDataCache($cache);
}
- if ($cache !== false && ! $cache instanceof DataCache) {
+ // @phpstan-ignore-next-line Enforce PHPDoc type.
+ if ($cache !== false && !$cache instanceof DataCache) {
throw new InvalidArgumentException(sprintf(
'%s(): Argument #1 ($cache) must be of type %s|false',
__METHOD__,
@@ -1733,7 +1879,7 @@ class SimplePie
if (!empty($this->data)) {
// If the cache is for an outdated build of SimplePie
- if (!isset($this->data['build']) || $this->data['build'] !== \SimplePie\Misc::get_build()) {
+ if (!isset($this->data['build']) || $this->data['build'] !== Misc::get_build()) {
$cache->delete_data($cacheKey);
$this->data = [];
}
@@ -1758,14 +1904,14 @@ class SimplePie
$this->data = [];
}
// Check if the cache has been updated
- elseif (isset($this->data['cache_expiration_time']) && $this->data['cache_expiration_time'] > time()) {
+ elseif (!isset($this->data['cache_expiration_time']) || $this->data['cache_expiration_time'] < time()) {
// Want to know if we tried to send last-modified and/or etag headers
// when requesting this file. (Note that it's up to the file to
// support this, but we don't always send the headers either.)
$this->check_modified = true;
if (isset($this->data['headers']['last-modified']) || isset($this->data['headers']['etag'])) {
$headers = [
- 'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1',
+ 'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
];
if (isset($this->data['headers']['last-modified'])) {
$headers['if-modified-since'] = $this->data['headers']['last-modified'];
@@ -1774,25 +1920,31 @@ class SimplePie
$headers['if-none-match'] = $this->data['headers']['etag'];
}
- $file = $this->registry->create(File::class, [$this->feed_url, $this->timeout/10, 5, $headers, $this->useragent, $this->force_fsockopen, $this->curl_options]);
- $this->status_code = $file->status_code;
-
- if ($file->success) {
- if ($file->status_code === 304) {
- // Set raw_data to false here too, to signify that the cache
- // is still valid.
- $this->raw_data = false;
- $cache->set_data($cacheKey, $this->data, $this->cache_duration);
- return true;
- }
- } else {
+ try {
+ $file = $this->get_http_client()->request(Client::METHOD_GET, $this->feed_url, $headers);
+ $this->status_code = $file->get_status_code();
+ } catch (ClientException $th) {
$this->check_modified = false;
+ $this->status_code = 0;
+
if ($this->force_cache_fallback) {
+ $this->data['cache_expiration_time'] = $this->cache_duration + time();
$cache->set_data($cacheKey, $this->data, $this->cache_duration);
+
return true;
}
- unset($file);
+ $failedFileReason = $th->getMessage();
+ }
+
+ if ($this->status_code === 304) {
+ // Set raw_data to false here too, to signify that the cache
+ // is still valid.
+ $this->raw_data = false;
+ $this->data['cache_expiration_time'] = $this->cache_duration + time();
+ $cache->set_data($cacheKey, $this->data, $this->cache_duration);
+
+ return true;
}
}
}
@@ -1810,40 +1962,72 @@ class SimplePie
// If we don't already have the file (it'll only exist if we've opened it to check if the cache has been modified), open it.
if (!isset($file)) {
- if ($this->file instanceof \SimplePie\File && $this->file->url === $this->feed_url) {
- $file =& $this->file;
+ if ($this->file instanceof File && $this->file->get_final_requested_uri() === $this->feed_url) {
+ $file = &$this->file;
+ } elseif (isset($failedFileReason)) {
+ // Do not try to fetch again if we already failed once.
+ // If the file connection had an error, set SimplePie::error to that and quit
+ $this->error = $failedFileReason;
+
+ return !empty($this->data);
} else {
$headers = [
- 'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1',
+ 'Accept' => SimplePie::DEFAULT_HTTP_ACCEPT_HEADER,
];
- $file = $this->registry->create(File::class, [$this->feed_url, $this->timeout, 5, $headers, $this->useragent, $this->force_fsockopen, $this->curl_options]);
+ try {
+ $file = $this->get_http_client()->request(Client::METHOD_GET, $this->feed_url, $headers);
+ } catch (ClientException $th) {
+ // If the file connection has an error, set SimplePie::error to that and quit
+ $this->error = $th->getMessage();
+
+ return !empty($this->data);
+ }
}
}
- $this->status_code = $file->status_code;
+ $this->status_code = $file->get_status_code();
// If the file connection has an error, set SimplePie::error to that and quit
- if (!$file->success && !($file->method & self::FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300))) {
- $this->error = $file->error;
+ if (!(!Misc::is_remote_uri($file->get_final_requested_uri()) || ($file->get_status_code() === 200 || $file->get_status_code() > 206 && $file->get_status_code() < 300))) {
+ $this->error = 'Retrieved unsupported status code "' . $this->status_code . '"';
return !empty($this->data);
}
if (!$this->force_feed) {
// Check if the supplied URL is a feed, if it isn't, look for it.
- $locate = $this->registry->create(Locator::class, [&$file, $this->timeout, $this->useragent, $this->max_checked_feeds, $this->force_fsockopen, $this->curl_options]);
+ $locate = $this->registry->create(Locator::class, [
+ (!$file instanceof File) ? File::fromResponse($file) : $file,
+ $this->timeout,
+ $this->useragent,
+ $this->max_checked_feeds,
+ $this->force_fsockopen,
+ $this->curl_options
+ ]);
+
+ $http_client = $this->get_http_client();
+
+ if ($http_client instanceof Psr18Client) {
+ $locate->set_http_client(
+ $http_client->getHttpClient(),
+ $http_client->getRequestFactory(),
+ $http_client->getUriFactory()
+ );
+ }
if (!$locate->is_feed($file)) {
- $copyStatusCode = $file->status_code;
- $copyContentType = $file->headers['content-type'];
+ $copyStatusCode = $file->get_status_code();
+ $copyContentType = $file->get_header_line('content-type');
try {
$microformats = false;
if (class_exists('DOMXpath') && function_exists('Mf2\parse')) {
$doc = new \DOMDocument();
- @$doc->loadHTML($file->body);
+ @$doc->loadHTML($file->get_body_content());
$xpath = new \DOMXpath($doc);
// Check for both h-feed and h-entry, as both a feed with no entries
// and a list of entries without an h-feed wrapper are both valid.
$query = '//*[contains(concat(" ", @class, " "), " h-feed ") or '.
'contains(concat(" ", @class, " "), " h-entry ")]';
+
+ /** @var \DOMNodeList<\DOMElement> $result */
$result = $xpath->query($query);
$microformats = $result->length !== 0;
}
@@ -1854,13 +2038,14 @@ class SimplePie
$this->all_discovered_feeds
);
if ($microformats) {
- if ($hub = $locate->get_rel_link('hub')) {
- $self = $locate->get_rel_link('self');
- $this->store_links($file, $hub, $self);
+ $hub = $locate->get_rel_link('hub');
+ $self = $locate->get_rel_link('self');
+ if ($hub || $self) {
+ $file = $this->store_links($file, $hub, $self);
}
// Push the current file onto all_discovered feeds so the user can
// be shown this as one of the options.
- if (isset($this->all_discovered_feeds)) {
+ if ($this->all_discovered_feeds !== null) {
$this->all_discovered_feeds[] = $file;
}
} else {
@@ -1875,7 +2060,7 @@ class SimplePie
return false;
}
}
- } catch (\SimplePie\Exception $e) {
+ } catch (SimplePieException $e) {
// We need to unset this so that if SimplePie::set_file() has been called that object is untouched
unset($file);
// This is usually because DOMDocument doesn't exist
@@ -1887,8 +2072,8 @@ class SimplePie
if ($cache) {
$this->data = [
'url' => $this->feed_url,
- 'feed_url' => $file->url,
- 'build' => \SimplePie\Misc::get_build(),
+ 'feed_url' => $file->get_final_requested_uri(),
+ 'build' => Misc::get_build(),
'cache_expiration_time' => $this->cache_duration + time(),
];
@@ -1897,13 +2082,18 @@ class SimplePie
}
}
}
- $this->feed_url = $file->url;
+ $this->feed_url = $file->get_final_requested_uri();
$locate = null;
}
- $this->raw_data = $file->body;
- $this->permanent_url = $file->permanent_url;
- $headers = $file->headers;
+ $this->raw_data = $file->get_body_content();
+ $this->permanent_url = $file->get_permanent_uri();
+
+ $headers = [];
+ foreach ($file->get_headers() as $key => $values) {
+ $headers[$key] = implode(', ', $values);
+ }
+
$sniffer = $this->registry->create(Sniffer::class, [&$file]);
$sniffed = $sniffer->get_type();
@@ -1913,7 +2103,7 @@ class SimplePie
/**
* Get the error message for the occurred error
*
- * @return string|array Error message, or array of messages for multifeeds
+ * @return string|string[]|null Error message, or array of messages for multifeeds
*/
public function error()
{
@@ -1936,7 +2126,7 @@ class SimplePie
* This is the same as the old `$feed->enable_xml_dump(true)`, but returns
* the data instead of printing it.
*
- * @return string|boolean Raw XML data, false if the cache is used
+ * @return string|false Raw XML data, false if the cache is used
*/
public function get_raw_data()
{
@@ -1972,8 +2162,9 @@ class SimplePie
* top).
*
* @param string $mime MIME type to serve the page as
+ * @return void
*/
- public function handle_content_type($mime = 'text/html')
+ public function handle_content_type(string $mime = 'text/html')
{
if (!headers_sent()) {
$header = "Content-type: $mime;";
@@ -1989,28 +2180,28 @@ class SimplePie
/**
* Get the type of the feed
*
- * This returns a \SimplePie\SimplePie::TYPE_* constant, which can be tested against
+ * This returns a self::TYPE_* constant, which can be tested against
* using {@link http://php.net/language.operators.bitwise bitwise operators}
*
* @since 0.8 (usage changed to using constants in 1.0)
- * @see \SimplePie\SimplePie::TYPE_NONE Unknown.
- * @see \SimplePie\SimplePie::TYPE_RSS_090 RSS 0.90.
- * @see \SimplePie\SimplePie::TYPE_RSS_091_NETSCAPE RSS 0.91 (Netscape).
- * @see \SimplePie\SimplePie::TYPE_RSS_091_USERLAND RSS 0.91 (Userland).
- * @see \SimplePie\SimplePie::TYPE_RSS_091 RSS 0.91.
- * @see \SimplePie\SimplePie::TYPE_RSS_092 RSS 0.92.
- * @see \SimplePie\SimplePie::TYPE_RSS_093 RSS 0.93.
- * @see \SimplePie\SimplePie::TYPE_RSS_094 RSS 0.94.
- * @see \SimplePie\SimplePie::TYPE_RSS_10 RSS 1.0.
- * @see \SimplePie\SimplePie::TYPE_RSS_20 RSS 2.0.x.
- * @see \SimplePie\SimplePie::TYPE_RSS_RDF RDF-based RSS.
- * @see \SimplePie\SimplePie::TYPE_RSS_SYNDICATION Non-RDF-based RSS (truly intended as syndication format).
- * @see \SimplePie\SimplePie::TYPE_RSS_ALL Any version of RSS.
- * @see \SimplePie\SimplePie::TYPE_ATOM_03 Atom 0.3.
- * @see \SimplePie\SimplePie::TYPE_ATOM_10 Atom 1.0.
- * @see \SimplePie\SimplePie::TYPE_ATOM_ALL Any version of Atom.
- * @see \SimplePie\SimplePie::TYPE_ALL Any known/supported feed type.
- * @return int \SimplePie\SimplePie::TYPE_* constant
+ * @see self::TYPE_NONE Unknown.
+ * @see self::TYPE_RSS_090 RSS 0.90.
+ * @see self::TYPE_RSS_091_NETSCAPE RSS 0.91 (Netscape).
+ * @see self::TYPE_RSS_091_USERLAND RSS 0.91 (Userland).
+ * @see self::TYPE_RSS_091 RSS 0.91.
+ * @see self::TYPE_RSS_092 RSS 0.92.
+ * @see self::TYPE_RSS_093 RSS 0.93.
+ * @see self::TYPE_RSS_094 RSS 0.94.
+ * @see self::TYPE_RSS_10 RSS 1.0.
+ * @see self::TYPE_RSS_20 RSS 2.0.x.
+ * @see self::TYPE_RSS_RDF RDF-based RSS.
+ * @see self::TYPE_RSS_SYNDICATION Non-RDF-based RSS (truly intended as syndication format).
+ * @see self::TYPE_RSS_ALL Any version of RSS.
+ * @see self::TYPE_ATOM_03 Atom 0.3.
+ * @see self::TYPE_ATOM_10 Atom 1.0.
+ * @see self::TYPE_ATOM_ALL Any version of Atom.
+ * @see self::TYPE_ALL Any known/supported feed type.
+ * @return int-mask-of<self::TYPE_*> constant
*/
public function get_type()
{
@@ -2095,7 +2286,7 @@ class SimplePie
* iff it is a 301 redirection
* @return string|null
*/
- public function subscribe_url($permanent = false)
+ public function subscribe_url(bool $permanent = false)
{
if ($permanent) {
if ($this->permanent_url !== null) {
@@ -2153,9 +2344,9 @@ class SimplePie
* @see http://simplepie.org/wiki/faq/supported_xml_namespaces
* @param string $namespace The URL of the XML namespace of the elements you're trying to access
* @param string $tag Tag name
- * @return array
+ * @return array<array<string, mixed>>|null
*/
- public function get_feed_tags($namespace, $tag)
+ public function get_feed_tags(string $namespace, string $tag)
{
$type = $this->get_type();
if ($type & self::TYPE_ATOM_10) {
@@ -2193,9 +2384,9 @@ class SimplePie
* @see http://simplepie.org/wiki/faq/supported_xml_namespaces
* @param string $namespace The URL of the XML namespace of the elements you're trying to access
* @param string $tag Tag name
- * @return array
+ * @return array<array<string, mixed>>|null
*/
- public function get_channel_tags($namespace, $tag)
+ public function get_channel_tags(string $namespace, string $tag)
{
$type = $this->get_type();
if ($type & self::TYPE_ATOM_ALL) {
@@ -2239,9 +2430,9 @@ class SimplePie
* @see http://simplepie.org/wiki/faq/supported_xml_namespaces
* @param string $namespace The URL of the XML namespace of the elements you're trying to access
* @param string $tag Tag name
- * @return array
+ * @return array<array<string, mixed>>|null
*/
- public function get_image_tags($namespace, $tag)
+ public function get_image_tags(string $namespace, string $tag)
{
$type = $this->get_type();
if ($type & self::TYPE_RSS_10) {
@@ -2271,41 +2462,47 @@ class SimplePie
/**
* Get the base URL value from the feed
*
- * Uses `<xml:base>` if available, otherwise uses the first link in the
- * feed, or failing that, the URL of the feed itself.
+ * Uses `<xml:base>` if available,
+ * otherwise uses the first 'self' link or the first 'alternate' link of the feed,
+ * or failing that, the URL of the feed itself.
*
* @see get_link
* @see subscribe_url
*
- * @param array $element
+ * @param array<string, mixed> $element
* @return string
*/
- public function get_base($element = [])
+ public function get_base(array $element = [])
{
if (!empty($element['xml_base_explicit']) && isset($element['xml_base'])) {
return $element['xml_base'];
- } elseif ($this->get_link() !== null) {
- return $this->get_link();
+ }
+ if (($link = $this->get_link(0, 'alternate')) !== null) {
+ return $link;
+ }
+ if (($link = $this->get_link(0, 'self')) !== null) {
+ return $link;
}
- return $this->subscribe_url();
+ return $this->subscribe_url() ?? '';
}
/**
* Sanitize feed data
*
* @access private
- * @see \SimplePie\Sanitize::sanitize()
+ * @see Sanitize::sanitize()
* @param string $data Data to sanitize
- * @param int $type One of the \SimplePie\SimplePie::CONSTRUCT_* constants
+ * @param int-mask-of<SimplePie::CONSTRUCT_*> $type
* @param string $base Base URL to resolve URLs against
* @return string Sanitized data
*/
- public function sanitize($data, $type, $base = '')
+ public function sanitize(string $data, int $type, string $base = '')
{
try {
+ // This really returns string|false but changing encoding is uncommon and we are going to deprecate it, so let’s just lie to PHPStan in the interest of cleaner annotations.
return $this->sanitize->sanitize($data, $type, $base);
- } catch (\SimplePie\Exception $e) {
+ } catch (SimplePieException $e) {
if (!$this->enable_exceptions) {
$this->error = $e->getMessage();
$this->registry->call(Misc::class, 'error', [$this->error, E_USER_WARNING, $e->getFile(), $e->getLine()]);
@@ -2350,9 +2547,9 @@ class SimplePie
*
* @since Unknown
* @param int $key The category that you want to return. Remember that arrays begin with 0, not 1
- * @return \SimplePie\Category|null
+ * @return Category|null
*/
- public function get_category($key = 0)
+ public function get_category(int $key = 0)
{
$categories = $this->get_categories();
if (isset($categories[$key])) {
@@ -2368,7 +2565,7 @@ class SimplePie
* Uses `<atom:category>`, `<category>` or `<dc:subject>`
*
* @since Unknown
- * @return array|null List of {@see \SimplePie\Category} objects
+ * @return array<Category>|null List of {@see Category} objects
*/
public function get_categories()
{
@@ -2419,9 +2616,9 @@ class SimplePie
*
* @since 1.1
* @param int $key The author that you want to return. Remember that arrays begin with 0, not 1
- * @return \SimplePie\Author|null
+ * @return Author|null
*/
- public function get_author($key = 0)
+ public function get_author(int $key = 0)
{
$authors = $this->get_authors();
if (isset($authors[$key])) {
@@ -2437,7 +2634,7 @@ class SimplePie
* Uses `<atom:author>`, `<author>`, `<dc:creator>` or `<itunes:author>`
*
* @since 1.1
- * @return array|null List of {@see \SimplePie\Author} objects
+ * @return array<Author>|null List of {@see Author} objects
*/
public function get_authors()
{
@@ -2450,7 +2647,8 @@ class SimplePie
$name = $this->sanitize($author['child'][self::NAMESPACE_ATOM_10]['name'][0]['data'], self::CONSTRUCT_TEXT);
}
if (isset($author['child'][self::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
- $uri = $this->sanitize($author['child'][self::NAMESPACE_ATOM_10]['uri'][0]['data'], self::CONSTRUCT_IRI, $this->get_base($author['child'][self::NAMESPACE_ATOM_10]['uri'][0]));
+ $uri = $author['child'][self::NAMESPACE_ATOM_10]['uri'][0];
+ $uri = $this->sanitize($uri['data'], self::CONSTRUCT_IRI, $this->get_base($uri));
}
if (isset($author['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'])) {
$email = $this->sanitize($author['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'], self::CONSTRUCT_TEXT);
@@ -2467,7 +2665,8 @@ class SimplePie
$name = $this->sanitize($author[0]['child'][self::NAMESPACE_ATOM_03]['name'][0]['data'], self::CONSTRUCT_TEXT);
}
if (isset($author[0]['child'][self::NAMESPACE_ATOM_03]['url'][0]['data'])) {
- $url = $this->sanitize($author[0]['child'][self::NAMESPACE_ATOM_03]['url'][0]['data'], self::CONSTRUCT_IRI, $this->get_base($author[0]['child'][self::NAMESPACE_ATOM_03]['url'][0]));
+ $url = $author[0]['child'][self::NAMESPACE_ATOM_03]['url'][0];
+ $url = $this->sanitize($url['data'], self::CONSTRUCT_IRI, $this->get_base($url));
}
if (isset($author[0]['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'])) {
$email = $this->sanitize($author[0]['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'], self::CONSTRUCT_TEXT);
@@ -2498,9 +2697,9 @@ class SimplePie
*
* @since 1.1
* @param int $key The contrbutor that you want to return. Remember that arrays begin with 0, not 1
- * @return \SimplePie\Author|null
+ * @return Author|null
*/
- public function get_contributor($key = 0)
+ public function get_contributor(int $key = 0)
{
$contributors = $this->get_contributors();
if (isset($contributors[$key])) {
@@ -2516,7 +2715,7 @@ class SimplePie
* Uses `<atom:contributor>`
*
* @since 1.1
- * @return array|null List of {@see \SimplePie\Author} objects
+ * @return array<Author>|null List of {@see Author} objects
*/
public function get_contributors()
{
@@ -2529,7 +2728,8 @@ class SimplePie
$name = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_10]['name'][0]['data'], self::CONSTRUCT_TEXT);
}
if (isset($contributor['child'][self::NAMESPACE_ATOM_10]['uri'][0]['data'])) {
- $uri = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_10]['uri'][0]['data'], self::CONSTRUCT_IRI, $this->get_base($contributor['child'][self::NAMESPACE_ATOM_10]['uri'][0]));
+ $uri = $contributor['child'][self::NAMESPACE_ATOM_10]['uri'][0];
+ $uri = $this->sanitize($uri['data'], self::CONSTRUCT_IRI, $this->get_base($uri));
}
if (isset($contributor['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'])) {
$email = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_10]['email'][0]['data'], self::CONSTRUCT_TEXT);
@@ -2546,7 +2746,8 @@ class SimplePie
$name = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_03]['name'][0]['data'], self::CONSTRUCT_TEXT);
}
if (isset($contributor['child'][self::NAMESPACE_ATOM_03]['url'][0]['data'])) {
- $url = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_03]['url'][0]['data'], self::CONSTRUCT_IRI, $this->get_base($contributor['child'][self::NAMESPACE_ATOM_03]['url'][0]));
+ $url = $contributor['child'][self::NAMESPACE_ATOM_03]['url'][0];
+ $url = $this->sanitize($url['data'], self::CONSTRUCT_IRI, $this->get_base($url));
}
if (isset($contributor['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'])) {
$email = $this->sanitize($contributor['child'][self::NAMESPACE_ATOM_03]['email'][0]['data'], self::CONSTRUCT_TEXT);
@@ -2571,7 +2772,7 @@ class SimplePie
* @param string $rel The relationship of the link to return
* @return string|null Link URL
*/
- public function get_link($key = 0, $rel = 'alternate')
+ public function get_link(int $key = 0, string $rel = 'alternate')
{
$links = $this->get_links($rel);
if (isset($links[$key])) {
@@ -2604,9 +2805,9 @@ class SimplePie
*
* @since Beta 2
* @param string $rel The relationship of links to return
- * @return array|null Links found for the feed (strings)
+ * @return array<string>|null Links found for the feed (strings)
*/
- public function get_links($rel = 'alternate')
+ public function get_links(string $rel = 'alternate')
{
if (!isset($this->data['links'])) {
$this->data['links'] = [];
@@ -2641,12 +2842,12 @@ class SimplePie
if ($this->registry->call(Misc::class, 'is_isegment_nz_nc', [$key])) {
if (isset($this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key])) {
$this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key]);
- $this->data['links'][$key] =& $this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key];
+ $this->data['links'][$key] = &$this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key];
} else {
- $this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key];
+ $this->data['links'][self::IANA_LINK_RELATIONS_REGISTRY . $key] = &$this->data['links'][$key];
}
} elseif (substr($key, 0, 41) === self::IANA_LINK_RELATIONS_REGISTRY) {
- $this->data['links'][substr($key, 41)] =& $this->data['links'][$key];
+ $this->data['links'][substr($key, 41)] = &$this->data['links'][$key];
}
$this->data['links'][$key] = array_unique($this->data['links'][$key]);
}
@@ -2671,6 +2872,9 @@ class SimplePie
return null;
}
+ /**
+ * @return ?array<Response>
+ */
public function get_all_discovered_feeds()
{
return $this->all_discovered_feeds;
@@ -2774,7 +2978,7 @@ class SimplePie
* @since 1.0
* @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
* @link http://www.georss.org/ GeoRSS
- * @return string|null
+ * @return float|null
*/
public function get_latitude()
{
@@ -2797,7 +3001,7 @@ class SimplePie
* @since 1.0
* @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo
* @link http://www.georss.org/ GeoRSS
- * @return string|null
+ * @return float|null
*/
public function get_longitude()
{
@@ -2944,15 +3148,14 @@ class SimplePie
* @param int $max Maximum value to return. 0 for no limit
* @return int Number of items in the feed
*/
- public function get_item_quantity($max = 0)
+ public function get_item_quantity(int $max = 0)
{
- $max = (int) $max;
$qty = count($this->get_items());
if ($max === 0) {
return $qty;
}
- return ($qty > $max) ? $max : $qty;
+ return min($qty, $max);
}
/**
@@ -2965,9 +3168,9 @@ class SimplePie
* @see get_item_quantity()
* @since Beta 2
* @param int $key The item that you want to return. Remember that arrays begin with 0, not 1
- * @return \SimplePie\Item|null
+ * @return Item|null
*/
- public function get_item($key = 0)
+ public function get_item(int $key = 0)
{
$items = $this->get_items();
if (isset($items[$key])) {
@@ -2988,9 +3191,9 @@ class SimplePie
* @since Beta 2
* @param int $start Index to start at
* @param int $end Number of items to return. 0 for all items after `$start`
- * @return \SimplePie\Item[]|null List of {@see \SimplePie\Item} objects
+ * @return Item[] List of {@see Item} objects
*/
- public function get_items($start = 0, $end = 0)
+ public function get_items(int $start = 0, int $end = 0)
{
if (!isset($this->data['items'])) {
if (!empty($this->multifeed_objects)) {
@@ -3004,31 +3207,31 @@ class SimplePie
if ($items = $this->get_feed_tags(self::NAMESPACE_ATOM_10, 'entry')) {
$keys = array_keys($items);
foreach ($keys as $key) {
- $this->data['items'][] = $this->registry->create(Item::class, [$this, $items[$key]]);
+ $this->data['items'][] = $this->make_item($items[$key]);
}
}
if ($items = $this->get_feed_tags(self::NAMESPACE_ATOM_03, 'entry')) {
$keys = array_keys($items);
foreach ($keys as $key) {
- $this->data['items'][] = $this->registry->create(Item::class, [$this, $items[$key]]);
+ $this->data['items'][] = $this->make_item($items[$key]);
}
}
if ($items = $this->get_feed_tags(self::NAMESPACE_RSS_10, 'item')) {
$keys = array_keys($items);
foreach ($keys as $key) {
- $this->data['items'][] = $this->registry->create(Item::class, [$this, $items[$key]]);
+ $this->data['items'][] = $this->make_item($items[$key]);
}
}
if ($items = $this->get_feed_tags(self::NAMESPACE_RSS_090, 'item')) {
$keys = array_keys($items);
foreach ($keys as $key) {
- $this->data['items'][] = $this->registry->create(Item::class, [$this, $items[$key]]);
+ $this->data['items'][] = $this->make_item($items[$key]);
}
}
if ($items = $this->get_channel_tags(self::NAMESPACE_RSS_20, 'item')) {
$keys = array_keys($items);
foreach ($keys as $key) {
- $this->data['items'][] = $this->registry->create(Item::class, [$this, $items[$key]]);
+ $this->data['items'][] = $this->make_item($items[$key]);
}
}
}
@@ -3058,10 +3261,12 @@ class SimplePie
* Set the favicon handler
*
* @deprecated Use your own favicon handling instead
+ * @param string|false $page
+ * @return bool
*/
- public function set_favicon_handler($page = false, $qs = 'i')
+ public function set_favicon_handler($page = false, string $qs = 'i')
{
- trigger_error('Favicon handling has been removed, please use your own handling', \E_USER_DEPRECATED);
+ trigger_error('Favicon handling has been removed since SimplePie 1.3, please use your own handling', \E_USER_DEPRECATED);
return false;
}
@@ -3069,10 +3274,11 @@ class SimplePie
* Get the favicon for the current feed
*
* @deprecated Use your own favicon handling instead
+ * @return string|bool
*/
public function get_favicon()
{
- trigger_error('Favicon handling has been removed, please use your own handling', \E_USER_DEPRECATED);
+ trigger_error('Favicon handling has been removed since SimplePie 1.3, please use your own handling', \E_USER_DEPRECATED);
if (($url = $this->get_link()) !== null) {
return 'https://www.google.com/s2/favicons?domain=' . urlencode($url);
@@ -3085,36 +3291,49 @@ class SimplePie
* Magic method handler
*
* @param string $method Method name
- * @param array $args Arguments to the method
+ * @param array<mixed> $args Arguments to the method
* @return mixed
*/
- public function __call($method, $args)
+ public function __call(string $method, array $args)
{
if (strpos($method, 'subscribe_') === 0) {
- trigger_error('subscribe_*() has been deprecated, implement the callback yourself', \E_USER_DEPRECATED);
+ trigger_error('subscribe_*() has been deprecated since SimplePie 1.3, implement the callback yourself', \E_USER_DEPRECATED);
return '';
}
if ($method === 'enable_xml_dump') {
- trigger_error('enable_xml_dump() has been deprecated, use get_raw_data() instead', \E_USER_DEPRECATED);
+ trigger_error('enable_xml_dump() has been deprecated since SimplePie 1.3, use get_raw_data() instead', \E_USER_DEPRECATED);
return false;
}
$class = get_class($this);
$trace = debug_backtrace();
- $file = $trace[0]['file'];
- $line = $trace[0]['line'];
- trigger_error("Call to undefined method $class::$method() in $file on line $line", E_USER_ERROR);
+ $file = $trace[0]['file'] ?? '';
+ $line = $trace[0]['line'] ?? '';
+ throw new SimplePieException("Call to undefined method $class::$method() in $file on line $line");
+ }
+
+ /**
+ * Item factory
+ *
+ * @param array<string, mixed> $data
+ */
+ private function make_item(array $data): Item
+ {
+ $item = $this->registry->create(Item::class, [$this, $data]);
+ $item->set_sanitize($this->sanitize);
+
+ return $item;
}
/**
* Sorting callback for items
*
* @access private
- * @param SimplePie $a
- * @param SimplePie $b
- * @return boolean
+ * @param Item $a
+ * @param Item $b
+ * @return -1|0|1
*/
- public static function sort_items($a, $b)
+ public static function sort_items(Item $a, Item $b)
{
$a_date = $a->get_date('U');
$b_date = $b->get_date('U');
@@ -3138,19 +3357,21 @@ class SimplePie
* for the items or else SimplePie will refuse to sort them.
*
* @link http://simplepie.org/wiki/tutorial/sort_multiple_feeds_by_time_and_date#if_feeds_require_separate_per-feed_settings
- * @param array $urls List of SimplePie feed objects to merge
+ * @param array<SimplePie> $urls List of SimplePie feed objects to merge
* @param int $start Starting item
* @param int $end Number of items to return
* @param int $limit Maximum number of items per feed
- * @return array
+ * @return array<Item>
*/
- public static function merge_items($urls, $start = 0, $end = 0, $limit = 0)
+ public static function merge_items(array $urls, int $start = 0, int $end = 0, int $limit = 0)
{
- if (is_array($urls) && sizeof($urls) > 0) {
+ if (count($urls) > 0) {
$items = [];
foreach ($urls as $arg) {
if ($arg instanceof SimplePie) {
$items = array_merge($items, $arg->get_items(0, $limit));
+
+ // @phpstan-ignore-next-line Enforce PHPDoc type.
} else {
trigger_error('Arguments must be SimplePie objects', E_USER_WARNING);
}
@@ -3174,31 +3395,25 @@ class SimplePie
*
* There is no way to find PuSH links in the body of a microformats feed,
* so they are added to the headers when found, to be used later by get_links.
- * @param \SimplePie\File $file
- * @param string $hub
- * @param string $self
*/
- private function store_links(&$file, $hub, $self)
+ private function store_links(Response $file, ?string $hub, ?string $self): Response
{
- if (isset($file->headers['link']['hub']) ||
- (isset($file->headers['link']) &&
- preg_match('/rel=hub/', $file->headers['link']))) {
- return;
+ $linkHeaderLine = $file->get_header_line('link');
+ $linkHeader = $file->get_header('link');
+
+ if ($hub && !preg_match('/rel=hub/', $linkHeaderLine)) {
+ $linkHeader[] = '<'.$hub.'>; rel=hub';
}
- if ($hub) {
- if (isset($file->headers['link'])) {
- if ($file->headers['link'] !== '') {
- $file->headers['link'] = ', ';
- }
- } else {
- $file->headers['link'] = '';
- }
- $file->headers['link'] .= '<'.$hub.'>; rel=hub';
- if ($self) {
- $file->headers['link'] .= ', <'.$self.'>; rel=self';
- }
+ if ($self && !preg_match('/rel=self/', $linkHeaderLine)) {
+ $linkHeader[] = '<'.$self.'>; rel=self';
}
+
+ if (count($linkHeader) > 0) {
+ $file = $file->with_header('link', $linkHeader);
+ }
+
+ return $file;
}
/**
@@ -3208,7 +3423,7 @@ class SimplePie
*
* @return DataCache
*/
- private function get_cache($feed_url = '')
+ private function get_cache(string $feed_url = ''): DataCache
{
if ($this->cache === null) {
// @trigger_error(sprintf('Not providing as PSR-16 cache implementation is deprecated since SimplePie 1.8.0, please use "SimplePie\SimplePie::set_cache()".'), \E_USER_DEPRECATED);
@@ -3223,6 +3438,28 @@ class SimplePie
return $this->cache;
}
+
+ /**
+ * Get a HTTP client
+ */
+ private function get_http_client(): Client
+ {
+ if ($this->http_client === null) {
+ $this->http_client = new FileClient(
+ $this->get_registry(),
+ [
+ 'timeout' => $this->timeout,
+ 'redirects' => 5,
+ 'useragent' => $this->useragent,
+ 'force_fsockopen' => $this->force_fsockopen,
+ 'curl_options' => $this->curl_options,
+ ]
+ );
+ $this->http_client_injected = true;
+ }
+
+ return $this->http_client;
+ }
}
class_alias('SimplePie\SimplePie', 'SimplePie');