Use PHP 8 'str_' functions.

A few more characters in some places, but helps with readability.
This commit is contained in:
wn_ 2024-11-23 18:23:49 +00:00
parent 53fee911e6
commit 667528d5b9
32 changed files with 67 additions and 70 deletions

View File

@ -96,7 +96,7 @@
];
// shortcut syntax for plugin methods (?op=plugin--pmethod&...params)
/* if (strpos($op, PluginHost::PUBLIC_METHOD_DELIMITER) !== false) {
/* if (str_contains($op, PluginHost::PUBLIC_METHOD_DELIMITER)) {
list ($plugin, $pmethod) = explode(PluginHost::PUBLIC_METHOD_DELIMITER, $op, 2);
// TODO: better implementation that won't modify $_REQUEST
@ -111,7 +111,7 @@
if (class_exists($op) || $override) {
if (strpos($method, "_") === 0) {
if (str_starts_with($method, "_")) {
user_error("Refusing to invoke method $method of handler $op which starts with underscore.", E_USER_WARNING);
header("Content-Type: text/json");
print Errors::to_json(Errors::E_UNAUTHORIZED);

View File

@ -623,7 +623,7 @@ class Article extends Handler_Protected {
if (!$article_image)
foreach ($enclosures as $enc) {
if (strpos($enc["content_type"], "image/") !== false) {
if (str_contains($enc["content_type"], "image/")) {
$article_image = $enc["content_url"];
break;
}

View File

@ -510,7 +510,7 @@ class Config {
$errors = [];
if (strpos(self::get(Config::PLUGINS), "auth_") === false) {
if (!str_contains(self::get(Config::PLUGINS), "auth_")) {
array_push($errors, "Please enable at least one authentication module via PLUGINS");
}

View File

@ -190,7 +190,7 @@ class Db_Migrations {
if (file_exists($filename)) {
$lines = array_filter(preg_split("/[\r\n]/", file_get_contents($filename)),
fn($line) => strlen(trim($line)) > 0 && strpos($line, "--") !== 0);
fn($line) => strlen(trim($line)) > 0 && !str_starts_with($line, "--"));
return array_filter(explode(";", implode("", $lines)),
fn($line) => strlen(trim($line)) > 0 && !in_array(strtolower($line), ["begin", "commit"]));

View File

@ -152,8 +152,8 @@ class Feeds extends Handler_Protected {
$feed_title = $qfh_ret[1];
$feed_site_url = $qfh_ret[2];
$last_error = $qfh_ret[3];
$last_updated = strpos($qfh_ret[4] ?? "", '1970-') === false ?
TimeHelper::make_local_datetime($qfh_ret[4], false) : __("Never");
$last_updated = str_contains($qfh_ret[4] ?? "", '1970-') ?
__("Never") : TimeHelper::make_local_datetime($qfh_ret[4], false);
$highlight_words = $qfh_ret[5];
$reply['first_id'] = $qfh_ret[6];
$reply['is_vfeed'] = $qfh_ret[7];
@ -1073,7 +1073,7 @@ class Feeds extends Handler_Protected {
return array("code" => 5, "message" => UrlHelper::$fetch_last_error);
}
if (mb_strpos(UrlHelper::$fetch_last_content_type, "html") !== false && self::_is_html($contents)) {
if (str_contains(UrlHelper::$fetch_last_content_type, "html") && self::_is_html($contents)) {
$feedUrls = self::_get_feeds_from_html($url, $contents);
if (count($feedUrls) == 0) {
@ -2205,7 +2205,7 @@ class Feeds extends Handler_Protected {
/** @var string $k a keyword pair (not yet split) or standalone value */
foreach ($keywords as $k) {
if (strpos($k, "-") === 0) {
if (str_starts_with($k, "-")) {
$k = substr($k, 1);
$not = "NOT";
} else {
@ -2311,7 +2311,7 @@ class Feeds extends Handler_Protected {
break;
default:
// @{date} handling
if (strpos($k, "@") === 0) {
if (str_starts_with($k, "@")) {
$user_tz_string = Prefs::get(Prefs::USER_TIMEZONE, $_SESSION['uid']);
$orig_ts = strtotime(substr($k, 1));
$k = date("Y-m-d", TimeHelper::convert_timestamp($orig_ts, $user_tz_string, 'UTC'));

View File

@ -217,7 +217,7 @@ class OPML extends Handler_Protected {
$match = [];
foreach (json_decode($tmp_line["match_on"], true) as $feed_id) {
if (strpos($feed_id, "CAT:") === 0) {
if (str_starts_with($feed_id, "CAT:")) {
$feed_id = (int)substr($feed_id, 4);
if ($feed_id) {
array_push($match, [Feeds::_get_cat_title($feed_id), true, false]);

View File

@ -385,7 +385,7 @@ class Pref_Feeds extends Handler_Protected {
if ($item['_reference']) {
if (strpos($id, "FEED") === 0) {
if (str_starts_with($id, "FEED")) {
$feed = ORM::for_table('ttrss_feeds')
->where('owner_uid', $_SESSION['uid'])
@ -396,7 +396,7 @@ class Pref_Feeds extends Handler_Protected {
$feed->cat_id = ($item_id != "root" && $bare_item_id) ? $bare_item_id : null;
$feed->save();
}
} else if (strpos($id, "CAT:") === 0) {
} else if (str_starts_with($id, "CAT:")) {
$this->process_category_order($data_map, $item['_reference'], $item_id,
$nest_level+1);

View File

@ -106,7 +106,7 @@ class Pref_Filters extends Handler_Protected {
/** @var int|string $feed_id may be a category string (e.g. 'CAT:7') or feed ID int */
foreach ($rule["feed_id"] as $feed_id) {
if (strpos("$feed_id", "CAT:") === 0) {
if (str_starts_with("$feed_id", "CAT:")) {
$cat_id = (int) substr("$feed_id", 4);
array_push($scope_inner_qparts, "cat_id = " . $cat_id);
} else if (is_numeric($feed_id) && $feed_id > 0) {
@ -206,7 +206,7 @@ class Pref_Filters extends Handler_Protected {
foreach ($feeds as $feed_id) {
if (strpos($feed_id, "CAT:") === 0) {
if (str_starts_with($feed_id, "CAT:")) {
$feed_id = (int)substr($feed_id, 4);
array_push($feeds_fmt, Feeds::_get_cat_title($feed_id));
} else {
@ -404,7 +404,7 @@ class Pref_Filters extends Handler_Protected {
foreach ($feeds as $feed_id) {
if (strpos($feed_id, "CAT:") === 0) {
if (str_starts_with($feed_id, "CAT:")) {
$feed_id = (int)substr($feed_id, 4);
array_push($feeds_fmt, Feeds::_get_cat_title($feed_id));
} else {

View File

@ -23,7 +23,7 @@ class RPC extends Handler_Protected {
for ($i = 0; $i < $l10n->total; $i++) {
if (isset($l10n->table_originals[$i * 2 + 2]) && $orig = $l10n->get_original_string($i)) {
if(strpos($orig, "\000") !== false) { // Plural forms
if(str_contains($orig, "\000")) { // Plural forms
$key = explode(chr(0), $orig);
$rv[$key[0]] = _ngettext($key[0], $key[1], 1); // Singular
@ -774,7 +774,7 @@ class RPC extends Handler_Protected {
if (!empty($omap[$action])) {
foreach ($omap[$action] as $sequence) {
if (strpos($sequence, "|") !== false) {
if (str_contains($sequence, "|")) {
$sequence = substr($sequence,
strpos($sequence, "|")+1,
strlen($sequence));

View File

@ -1432,7 +1432,7 @@ class RSSUtils {
/** @var DOMElement $entry */
foreach ($entries as $entry) {
foreach (array('src', 'poster') as $attr) {
if ($entry->hasAttribute($attr) && strpos($entry->getAttribute($attr), "data:") !== 0) {
if ($entry->hasAttribute($attr) && !str_starts_with($entry->getAttribute($attr), "data:")) {
self::cache_media_url($cache, $entry->getAttribute($attr), $site_url);
}
}
@ -1753,7 +1753,7 @@ class RSSUtils {
if ($dh) {
while (($old_filename = readdir($dh)) !== false) {
if (strpos($old_filename, ".ico") !== false) {
if (str_ends_with($old_filename, ".ico")) {
$new_filename = str_replace(".ico", "", $old_filename);
$old_full_path = "$old_dir/$old_filename";

View File

@ -20,11 +20,11 @@ class Sanitizer {
foreach ($entry->attributes as $attr) {
if (strpos($attr->nodeName, 'on') === 0) {
if (str_starts_with($attr->nodeName, 'on')) {
array_push($attrs_to_remove, $attr);
}
if (strpos($attr->nodeName, "data-") === 0) {
if (str_starts_with($attr->nodeName, 'data-')) {
array_push($attrs_to_remove, $attr);
}

View File

@ -5,7 +5,7 @@ class Templator extends MiniTemplator {
/* this reads tt-rss template from templates.local/ or templates/ if only base filename is given */
function readTemplateFromFile ($fileName) {
if (strpos($fileName, "/") === false) {
if (!str_contains($fileName, "/")) {
$fileName = basename($fileName);

View File

@ -9,7 +9,7 @@ class TimeHelper {
return T_sprintf("%d min", date("i", time() + $tz_offset - $timestamp));
} else if (date("Y.m.d", $timestamp) == date("Y.m.d", time() + $tz_offset)) {
$format = Prefs::get(Prefs::SHORT_DATE_FORMAT, $owner_uid, $profile);
if (strpos((strtolower($format)), "a") === false)
if (!str_contains((strtolower($format)), "a"))
return date("G:i", $timestamp);
else
return date("g:i a", $timestamp);

View File

@ -86,7 +86,7 @@ class UrlHelper {
return self::validate($rel_url);
// protocol-relative URL (rare but they exist)
} else if (strpos($rel_url, "//") === 0) {
} else if (str_starts_with($rel_url, "//")) {
return self::validate("https:" . $rel_url);
// allow some extra schemes for A href
} else if (in_array($rel_parts["scheme"] ?? "", self::EXTRA_HREF_SCHEMES, true) &&
@ -118,10 +118,10 @@ class UrlHelper {
// 1. absolute relative path (/test.html) = no-op, proceed as is
// 2. dotslash relative URI (./test.html) - strip "./", append base path
if (strpos($rel_parts['path'], './') === 0) {
if (str_starts_with($rel_parts['path'], './')) {
$rel_parts['path'] = $base_path . substr($rel_parts['path'], 2);
// 3. anything else relative (test.html) - append dirname() of base path
} else if (strpos($rel_parts['path'], '/') !== 0) {
} else if (!str_starts_with($rel_parts['path'], '/')) {
$rel_parts['path'] = $base_path . $rel_parts['path'];
}
@ -141,7 +141,7 @@ class UrlHelper {
$url = clean($url);
# fix protocol-relative URLs
if (strpos($url, "//") === 0)
if (str_starts_with($url, "//"))
$url = "https:" . $url;
$tokens = parse_url($url);
@ -191,7 +191,8 @@ class UrlHelper {
if (!in_array($tokens['port'] ?? '', [80, 443, '']))
return false;
if (strtolower($tokens['host']) == 'localhost' || $tokens['host'] == '::1' || strpos($tokens['host'], '127.') === 0)
if (strtolower($tokens['host']) == 'localhost' || $tokens['host'] == '::1'
|| str_starts_with($tokens['host'], '127.'))
return false;
}
@ -295,7 +296,7 @@ class UrlHelper {
$url_host = parse_url($url, PHP_URL_HOST);
$ip_addr = gethostbyname($url_host);
if (!$ip_addr || strpos($ip_addr, '127.') === 0) {
if (!$ip_addr || str_starts_with($ip_addr, '127.')) {
self::$fetch_last_error = "URL hostname failed to resolve or resolved to a loopback address ($ip_addr)";
return false;
}
@ -396,7 +397,7 @@ class UrlHelper {
self::$fetch_last_content_type = $ex->getResponse()->getHeaderLine('content-type');
if ($type && strpos(self::$fetch_last_content_type, "$type") === false)
if ($type && !str_contains(self::$fetch_last_content_type, "$type"))
self::$fetch_last_error_content = (string) $ex->getResponse()->getBody();
} elseif (array_key_exists('errno', $ex->getHandlerContext())) {
$errno = (int) $ex->getHandlerContext()['errno'];
@ -433,7 +434,7 @@ class UrlHelper {
self::$fetch_effective_ip_addr = gethostbyname(parse_url(self::$fetch_effective_url, PHP_URL_HOST));
if (!self::$fetch_effective_ip_addr || strpos(self::$fetch_effective_ip_addr, '127.') === 0) {
if (!self::$fetch_effective_ip_addr || str_starts_with(self::$fetch_effective_ip_addr, '127.')) {
self::$fetch_last_error = 'URL hostname received after redirection failed to resolve or resolved to a loopback address (' .
self::$fetch_effective_ip_addr . ')';
return false;

View File

@ -221,7 +221,7 @@ function _color_hue2rgb(float $m1, float $m2, float $h): int {
* @return array{0: int, 1: int, 2: int}
*/
function _color_unpack(string $hex, bool $normalize = false): array {
$hex = strpos($hex, '#') !== 0 ? _resolve_htmlcolor($hex) : substr($hex, 1);
$hex = str_starts_with($hex, '#') ? substr($hex, 1) : _resolve_htmlcolor($hex);
if (strlen($hex) == 4) {
$hex = $hex[1] . $hex[1] . $hex[2] . $hex[2] . $hex[3] . $hex[3];

View File

@ -46,7 +46,7 @@
*/
function input_tag(string $name, string $value, string $type = "text", array $attributes = [], string $id = ""): string {
$attributes_str = attributes_to_string($attributes);
$dojo_type = strpos($attributes_str, "dojoType") === false ? "dojoType='dijit.form.TextBox'" : "";
$dojo_type = str_contains($attributes_str, "dojoType") ? "" : "dojoType='dijit.form.TextBox'";
return "<input name=\"".htmlspecialchars($name)."\" $dojo_type ".attributes_to_string($attributes)." id=\"".htmlspecialchars($id)."\"
type=\"$type\" value=\"".htmlspecialchars($value)."\">";
@ -86,7 +86,7 @@
*/
function select_tag(string $name, mixed $value, array $values, array $attributes = [], string $id = ""): string {
$attributes_str = attributes_to_string($attributes);
$dojo_type = strpos($attributes_str, "dojoType") === false ? "dojoType='fox.form.Select'" : "";
$dojo_type = str_contains($attributes_str, "dojoType") ? "" : "dojoType='fox.form.Select'";
$rv = "<select $dojo_type name=\"".htmlspecialchars($name)."\"
id=\"".htmlspecialchars($id)."\" name=\"".htmlspecialchars($name)."\" $attributes_str>";
@ -115,7 +115,7 @@
*/
function select_hash(string $name, $value, array $values, array $attributes = [], string $id = ""): string {
$attributes_str = attributes_to_string($attributes);
$dojo_type = strpos($attributes_str, "dojoType") === false ? "dojoType='fox.form.Select'" : "";
$dojo_type = str_contains($attributes_str, "dojoType") ? "" : "dojoType='fox.form.Select'";
$rv = "<select $dojo_type name=\"".htmlspecialchars($name)."\"
id=\"".htmlspecialchars($id)."\" name=\"".htmlspecialchars($name)."\" $attributes_str>";

View File

@ -279,11 +279,7 @@
}
function with_trailing_slash(string $str) : string {
if (substr($str, -1) === "/") {
return $str;
} else {
return "$str/";
}
return str_ends_with($str, '/') ? $str : "$str/";
}
function make_password(int $length = 12): string {

View File

@ -138,7 +138,7 @@
onblur="UtilityApp.fetchProfiles()"
value="<?= $_SESSION["fake_password"] ?? "" ?>"/>
</fieldset>
<?php if (strpos(Config::get(Config::PLUGINS), "auth_internal") !== false) { ?>
<?php if (str_contains(Config::get(Config::PLUGINS), "auth_internal")) { ?>
<fieldset class="align-right">
<a href="public.php?op=forgotpass"><?= __("I forgot my password") ?></a>
</fieldset>

View File

@ -6,8 +6,8 @@ class Af_Comics_Cad extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["link"], "cad-comic.com") !== false) {
if (strpos($article["title"], "News:") === false) {
if (str_contains($article["link"], "cad-comic.com")) {
if (!str_contains($article["title"], "News:")) {
$doc = new DOMDocument();
$res = UrlHelper::fetch([

View File

@ -6,7 +6,7 @@ class Af_Comics_ComicClass extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["guid"], "loadingartist.com") !== false) {
if (str_contains($article["guid"], "loadingartist.com")) {
// lol at people who block clients by user agent
// oh noes my ad revenue Q_Q

View File

@ -8,15 +8,15 @@ class Af_Comics_ComicPress extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["guid"], "bunicomic.com") !== false ||
strpos($article["guid"], "buttersafe.com") !== false ||
strpos($article["guid"], "extrafabulouscomics.com") !== false ||
strpos($article["guid"], "danbydraws.com") !== false ||
strpos($article["guid"], "theduckwebcomics.com/Powerup_Comics") !== false ||
strpos($article["guid"], "happyjar.com") !== false ||
strpos($article["guid"], "nedroid.com") !== false ||
strpos($article["guid"], "stonetoss.com") !== false ||
strpos($article["guid"], "csectioncomics.com") !== false) {
if (str_contains($article["guid"], "bunicomic.com") ||
str_contains($article["guid"], "buttersafe.com") ||
str_contains($article["guid"], "extrafabulouscomics.com") ||
str_contains($article["guid"], "danbydraws.com") ||
str_contains($article["guid"], "theduckwebcomics.com/Powerup_Comics") ||
str_contains($article["guid"], "happyjar.com") ||
str_contains($article["guid"], "nedroid.com") ||
str_contains($article["guid"], "stonetoss.com") ||
str_contains($article["guid"], "csectioncomics.com")) {
// lol at people who block clients by user agent
// oh noes my ad revenue Q_Q

View File

@ -7,7 +7,7 @@ class Af_Comics_DarkLegacy extends Af_ComicFilter {
function process(&$article) {
if (strpos($article["guid"], "darklegacycomics.com") !== false) {
if (str_contains($article["guid"], "darklegacycomics.com")) {
$res = UrlHelper::fetch([
'url' => $article['link'],
'useragent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',

View File

@ -7,8 +7,8 @@ class Af_Comics_Dilbert extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["link"], "dilbert.com") !== false ||
strpos($article["link"], "/DilbertDailyStrip") !== false) {
if (str_contains($article["link"], "dilbert.com") ||
str_contains($article["link"], "/DilbertDailyStrip")) {
$res = UrlHelper::fetch([
'url' => $article['link'],
'useragent' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0',
@ -34,7 +34,7 @@ class Af_Comics_Dilbert extends Af_ComicFilter {
foreach ($matches as $tag) {
// Only strings starting with a number sign are considered tags
if ( substr($tag->textContent, 0, 1) == '#' ) {
if (str_starts_with($tag->textContent, '#')) {
$tags[] = mb_strtolower(substr($tag->textContent, 1), 'utf-8');
}
}

View File

@ -7,7 +7,7 @@ class Af_Comics_Explosm extends Af_ComicFilter {
function process(&$article) {
if (strpos($article["link"], "explosm.net/comics") !== false) {
if (str_contains($article["link"], "explosm.net/comics")) {
$doc = new DOMDocument();

View File

@ -6,7 +6,7 @@ class Af_Comics_Pa extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["link"], "penny-arcade.com") !== false && strpos($article["title"], "Comic:") !== false) {
if (str_contains($article["link"], "penny-arcade.com") && str_contains($article["title"], "Comic:")) {
$doc = new DOMDocument();
@ -22,7 +22,7 @@ class Af_Comics_Pa extends Af_ComicFilter {
return true;
}
if (strpos($article["link"], "penny-arcade.com") !== false && strpos($article["title"], "News Post:") !== false) {
if (str_contains($article["link"], "penny-arcade.com") && str_contains($article["title"], "News Post:")) {
$doc = new DOMDocument();
$res = UrlHelper::fetch(['url' => $article['link']]);

View File

@ -6,7 +6,7 @@ class Af_Comics_Pvp extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["guid"], "pvponline.com") !== false) {
if (str_contains($article["guid"], "pvponline.com")) {
$res = UrlHelper::fetch([
'url' => $article['link'],
'useragent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',

View File

@ -6,8 +6,8 @@ class Af_Comics_Tfd extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["link"], "toothpastefordinner.com") !== false ||
strpos($article["link"], "marriedtothesea.com") !== false) {
if (str_contains($article["link"], "toothpastefordinner.com") ||
str_contains($article["link"], "marriedtothesea.com")) {
$res = UrlHelper::fetch([
'url' => $article['link'],
'useragent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',

View File

@ -7,7 +7,7 @@ class Af_Comics_Twp extends Af_ComicFilter {
function process(&$article) {
if (strpos($article["link"], "threewordphrase.com") !== false) {
if (str_contains($article["link"], "threewordphrase.com")) {
$doc = new DOMDocument();

View File

@ -6,7 +6,7 @@ class Af_Comics_Whomp extends Af_ComicFilter {
}
function process(&$article) {
if (strpos($article["guid"], "whompcomic.com") !== false) {
if (str_contains($article["guid"], "whompcomic.com")) {
$res = UrlHelper::fetch([
'url' => $article['link'],
'useragent' => 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)',

View File

@ -205,7 +205,7 @@ class Cache_Starred_Images extends Plugin {
foreach ($entries as $entry) {
if ($entry->hasAttribute('src') && strpos($entry->getAttribute('src'), "data:") !== 0) {
if ($entry->hasAttribute('src') && !str_starts_with($entry->getAttribute('src'), "data:")) {
$has_images = true;

View File

@ -14,7 +14,7 @@
$method = (string)clean($_REQUEST["op"]);
// shortcut syntax for public (exposed) methods (?op=plugin--pmethod&...params)
if (strpos($method, PluginHost::PUBLIC_METHOD_DELIMITER) !== false) {
if (str_contains($method, PluginHost::PUBLIC_METHOD_DELIMITER)) {
list ($plugin, $pmethod) = explode(PluginHost::PUBLIC_METHOD_DELIMITER, $method, 2);
// TODO: better implementation that won't modify $_REQUEST
@ -32,7 +32,7 @@
$handler = new Handler_Public($_REQUEST);
}
if (strpos($method, "_") === 0) {
if (str_starts_with($method, "_")) {
user_error("Refusing to invoke method $method which starts with underscore.", E_USER_WARNING);
header("Content-Type: text/json");
print Errors::to_json(Errors::E_UNAUTHORIZED);

View File

@ -123,7 +123,7 @@
$options_help = [];
foreach ($options_map as $option => $descr) {
if (substr($option, -1) === ":")
if (str_ends_with($option, ':'))
$option = substr($option, 0, -1);
$help_key = trim(sprintf("--%s %s",