Author: Ayesh Karunaratne (Ayesh) Committer: GitHub (web-flow) Pusher: cmb69 Date: 2022-07-03T12:24:14+02:00
Commit: https://github.com/php/web-php/commit/1b83fd7ab7b4234e777d43587c53f421194a29b2 Raw diff: https://github.com/php/web-php/commit/1b83fd7ab7b4234e777d43587c53f421194a29b2.diff Multiple micro-optimizations * Replace `ob_get_contents();ob_clean()` with `ob_get_clean()` `ob_get_clean()` is equivalent to `ob_get_contents()` followed by `ob_clean()`. * Replace `intval()` calls with `(int)` type cast This is a micro-optimization because `intval()` is a function call, and the type cast is about 6 times fast. * Replace `preg_replace` call that could be done with an `rtrim()` call In `./error.php`, there is a `preg_replace('!/+$!', '', $URI);` call that essentially is equivalent to `rtrim()`, that both calls removing trailing slash characters in `$URI`. The `rtim()` call is more legible and faster. * Combine consecutive `str_replace` calls to a single `str_replace` call * Use short ternary operator where possible Improves code readability. * Cascade various `else` statements where possible Cleans up the code by removing unnecessary `else` blocks and moving the code to the parent context if the previous `if` block exits the function by either terminating the script, or with a `return` statement. * Combine multiple `isset()` calls to a single `isset()` `isset()` accepts multiple parameters and returns `true` only if all of the parameters are `isset`. It makes sense to combine multiple individual `isset` calls to a single call for better readability. * Replace `for` loop with a `foreach` loop * Remove unnecessary character escapes in regular expressions Regular expression special characters are context-sensitive. For example, special characters such as `.` are not considered special within square braces (`[]`). This removes several of such instances that certain characters are escaped, but it is not strictly necessary within the context. This improves the readability of the expression. See more information at [PHP.Watch: Writing better Regular Expressions in PHP](https://php.watch/articles/php-regex-readability#reduce-escape) * Remove unnecessary break statement * Remove unnecessary PHP close tags * Remove redundant JSON_ERROR_NONE check Remove unnecessary `json_last_error() == JSON_ERROR_NONE` where the decoded object is inspected already. Closes GH-603. Changed paths: M bin/bumpRelease M bin/news2html M cal.php M credits.php M error.php M images/elephpants.php M include/branches.inc M include/email-validation.inc M include/historical_mirrors.inc M include/ip-to-country.inc M include/langchooser.inc M include/layout.inc M include/pregen-confs.inc M include/results.inc M include/shared-manual.inc M include/site.inc M index.php M manual-lookup.php M manual/add-note.php M manual/index.php M manual/spam_challenge.php M manual/vote-note.php M releases/index.php M security/index.php M src/UserNotes/Sorter.php Diff: diff --git a/bin/bumpRelease b/bin/bumpRelease index f8fca16aa8..37c83012b6 100755 --- a/bin/bumpRelease +++ b/bin/bumpRelease @@ -11,9 +11,9 @@ if ($_SERVER['argc'] < 1) { exit(1); } -$major = intval($_SERVER['argv'][1]); +$major = (int) $_SERVER['argv'][1]; isset($RELEASES[$major]) or die("Unkown major version $major"); -$minor = isset($_SERVER['argv'][2]) ? intval($_SERVER['argv'][2]) : null; +$minor = isset($_SERVER['argv'][2]) ? (int) $_SERVER['argv'][2] : null; $version = get_current_release_for_branch($major, $minor); $info = $RELEASES[$major][$version] ?? null; diff --git a/bin/news2html b/bin/news2html index c2c8c59e95..0b72e8824a 100755 --- a/bin/news2html +++ b/bin/news2html @@ -84,8 +84,7 @@ foreach($entries as $module => $items) { echo "</ul>\n<!-- }}} --></section>\n\n"; if ($changelog) { - $contents = ob_get_contents(); - ob_end_clean(); + $contents = ob_get_clean(); $log = file_get_contents($changelog); if (empty($log)) { diff --git a/cal.php b/cal.php index 984d5bb203..b8f71fd84f 100644 --- a/cal.php +++ b/cal.php @@ -222,11 +222,10 @@ function date_for_recur($recur, $day, $bom, $eom) } // ${recur}th to last $day of the month - else { - $eomd = date("w",$eom) + 1; - $days = (($eomd - $day + 7) % 7) + ((abs($recur) - 1) * 7); - return mktime(0,0,1, date("m",$bom)+1, -$days, date("Y",$bom)); - } + $eomd = date("w",$eom) + 1; + $days = (($eomd - $day + 7) % 7) + ((abs($recur) - 1) * 7); + + return mktime(0, 0, 1, date("m", $bom)+1, -$days, date("Y", $bom)); } // Display a <div> for each of the events that are on a given day diff --git a/credits.php b/credits.php index 540919c059..1ba4ab0545 100644 --- a/credits.php +++ b/credits.php @@ -5,8 +5,7 @@ // Put credits information to $credits ob_start(); phpcredits(); -$credits = ob_get_contents(); -ob_end_clean(); +$credits = ob_get_clean(); // Strip all but the body and drop styles preg_match('!<body.*?>(.*)</body>!ims', $credits, $m); @@ -26,5 +25,3 @@ echo $credits; site_footer(); } - -?> diff --git a/error.php b/error.php index 68cebbe5c1..ebf8895b5d 100644 --- a/error.php +++ b/error.php @@ -116,7 +116,7 @@ // ============================================================================ // The trailing slash only causes problems from now on -$URI = preg_replace('!/+$!', '', $URI); +$URI = rtrim($URI, '/'); // ============================================================================ // Some nice URLs for getting something for download @@ -700,4 +700,3 @@ /* * vim: set et ts=4 sw=4 ft=php: : */ -?> diff --git a/images/elephpants.php b/images/elephpants.php index 4b51650eb2..361d6c58b9 100644 --- a/images/elephpants.php +++ b/images/elephpants.php @@ -35,7 +35,7 @@ // determine how many images to serve. if (isset($_REQUEST['count'])) { - $count = min(intval($_REQUEST['count']), 50); + $count = min((int) $_REQUEST['count'], 50); } else { header('HTTP/1.1 400', true, 400); print json_encode(array( diff --git a/include/branches.inc b/include/branches.inc index 46a54f1dd8..4b2fd1d39e 100644 --- a/include/branches.inc +++ b/include/branches.inc @@ -162,7 +162,7 @@ function get_active_branches($include_recent_eols = true) { * must be in $RELEASES _and_ must be the full version number, not the branch: * ie provide array('5.3.29'), not array('5.3'). */ function get_eol_branches($always_include = null) { - $always_include = $always_include ? $always_include : array(); + $always_include = $always_include ?: array(); $branches = array(); $now = new DateTime; @@ -329,13 +329,17 @@ function get_branch_support_state($branch) { if ($now >= $security) { return 'eol'; - } elseif ($now >= $bug) { + } + + if ($now >= $bug) { return 'security'; - } elseif ($now >= $initial) { + } + + if ($now >= $initial) { return 'stable'; - } else { - return 'future'; } + + return 'future'; } return null; diff --git a/include/email-validation.inc b/include/email-validation.inc index 3c38d51eb3..3c460187eb 100644 --- a/include/email-validation.inc +++ b/include/email-validation.inc @@ -18,7 +18,7 @@ function is_emailable_address($email) $host = substr($email, strrpos($email, '@') + 1); // addresses from our mailing-list servers - $host_regex = "!(lists\.php\.net|chek[^\.*]\.com)!i"; + $host_regex = "!(lists\.php\.net|chek[^.*]\.com)!i"; if (preg_match($host_regex, $host)) { return false; } diff --git a/include/historical_mirrors.inc b/include/historical_mirrors.inc index 9ee4e40ecb..3ba6a92aaa 100644 --- a/include/historical_mirrors.inc +++ b/include/historical_mirrors.inc @@ -87,4 +87,3 @@ $historical_mirrors = array( array("USA", "us3.php.net", "C7 Data Centers", "https://www.c7.com/"), array("VNM", "vn1.php.net", "DigiStar Co., Ltd", "http://www.digistar.vn/"), ); -?> diff --git a/include/ip-to-country.inc b/include/ip-to-country.inc index c6418b0561..c9e0acc31f 100644 --- a/include/ip-to-country.inc +++ b/include/ip-to-country.inc @@ -95,12 +95,12 @@ function i2c_search_in_index($ip) // Read in granularity from index file and // convert current IP to something useful - $granularity = intval(fgets($dbidx, 64)); + $granularity = (int) fgets($dbidx, 64); if (!$granularity) { // The file is empty (demo file) return false; } - $ip_chunk = intval($ip / $granularity); + $ip_chunk = (int) ($ip / $granularity); // Loop till we can read the file while (!feof($dbidx)) { @@ -217,7 +217,7 @@ function i2c_realip() } // Return with the found IP or the remote address - return ($ip ? $ip : $_SERVER['REMOTE_ADDR']); + return $ip ?: $_SERVER['REMOTE_ADDR']; } /* vim: set et ts=4 sw=4 ft=php: : */ diff --git a/include/langchooser.inc b/include/langchooser.inc index d09b036f2c..6fa8e2376b 100644 --- a/include/langchooser.inc +++ b/include/langchooser.inc @@ -102,11 +102,11 @@ function language_choose_code() $browser_accept = explode(",", $_SERVER['HTTP_ACCEPT_LANGUAGE']); // Go through all language preference specs - for ($i = 0; $i < count($browser_accept); $i++) { + foreach ($browser_accept as $value) { // The language part is either a code or a code with a quality // We cannot do anything with a * code, so it is skipped // If the quality is missing, it is assumed to be 1 according to the RFC - if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($browser_accept[$i]), $found)) { + if (preg_match("!([a-z-]+)(;q=([0-9\\.]+))?!", trim($value), $found)) { $quality = (isset($found[3]) ? (float) $found[3] : 1.0); $browser_langs[] = array($found[1], $quality); } diff --git a/include/layout.inc b/include/layout.inc index 6561838da3..6d5d8db1f1 100644 --- a/include/layout.inc +++ b/include/layout.inc @@ -52,7 +52,7 @@ function highlight_php_trimmed($code, $return = false) { $code = "<?php\n" . $code; $highlighted_code = highlight_php($code, true); - $highlighted_code = preg_replace("/\<\?php(\<br \/\>)+/", '', $highlighted_code, 1); + $highlighted_code = preg_replace("!<\?php(<br />)+!", '', $highlighted_code, 1); if ($return) { return $highlighted_code; } echo $highlighted_code; @@ -109,7 +109,7 @@ function make_image($file, $alt = FALSE, $align = FALSE, $extras = FALSE, return sprintf('<img src="%s/%s" alt="%s"%s%s%s>', $webdir, $file, - ($alt ? $alt : ''), + ($alt ?: ''), $sizeparams, $align, ($extras ? ' ' . $extras : '') @@ -159,7 +159,7 @@ function make_link ($url, $linktext = FALSE, $target = FALSE, $extras = FALSE) $url, ($target ? ' target="' . $target . '"' : ''), ($extras ? ' ' . $extras : ''), - ($linktext ? $linktext : $url) + ($linktext ?: $url) ); } @@ -175,12 +175,12 @@ function print_link($url, $linktext = FALSE, $target = FALSE, $extras = FALSE) function make_popup_link ($url, $linktext=false, $target=false, $windowprops="", $extras=false) { return sprintf("<a href=\"%s\" target=\"%s\" onclick=\"window.open('%s','%s','%s');return false;\"%s>%s</a>", htmlspecialchars($url, ENT_QUOTES | ENT_IGNORE), - ($target ? $target : "_new"), + ($target ?: "_new"), htmlspecialchars($url, ENT_QUOTES | ENT_IGNORE), - ($target ? $target : "_new"), + ($target ?: "_new"), $windowprops, ($extras ? ' '.$extras : ''), - ($linktext ? $linktext : $url) + ($linktext ?: $url) ); } @@ -230,8 +230,7 @@ function download_link($file, $title) function sect_to_file($string) { $string = strtolower($string); - $string = str_replace(' ','-',$string); - $string = str_replace('_','-',$string); + $string = str_replace([' ', '_'], '-', $string); $func = "function.$string.php"; $chap = "ref.$string.php"; $feat = "features.$string.php"; @@ -255,7 +254,7 @@ function clean_note($text) // Turn urls into links return preg_replace( - '!((mailto:|(https?|ftp|nntp|news):\/\/).*?)(\s|<|\)|"|\\\\|\'|$)!', + '!((mailto:|(https?|ftp|nntp|news)://).*?)(\s|<|\)|"|\\\\|\'|$)!', '<a href="\1" rel="nofollow" target="_blank">\1</a>\4', $text ); @@ -397,7 +396,7 @@ function news_archive_sidebar() function print_news($news, $dog, $max = 5, $onlyyear = null, $return = false) { $retval = array(); $count = 0; - $news = $news ? $news : array(); // default to empty array (if no news) + $news = $news ?: array(); // default to empty array (if no news) foreach($news as $item) { $ok = false; diff --git a/include/pregen-confs.inc b/include/pregen-confs.inc index 2dd70b9716..e4ba03d52b 100644 --- a/include/pregen-confs.inc +++ b/include/pregen-confs.inc @@ -36,5 +36,4 @@ $CONF_TEASER = array ( 'http://php.net/conferences/index.php#id2015-06-19-1' => 'ZendCon 2015', 'http://php.net/conferences/index.php#id2015-06-01-1' => 'PHP Barcelona Conference 2015', ), -) -?> +); diff --git a/include/results.inc b/include/results.inc index 6075fc9797..f499dd80ef 100644 --- a/include/results.inc +++ b/include/results.inc @@ -92,4 +92,3 @@ EOB; echo '</ul></div>'; endif; } -?> diff --git a/include/shared-manual.inc b/include/shared-manual.inc index 2472ada7da..7d67a2c3ed 100644 --- a/include/shared-manual.inc +++ b/include/shared-manual.inc @@ -129,7 +129,7 @@ function manual_note_display($date, $name, $text, $id, $votes = array('up'=>0,'d // Calculate note rating by up/down votes $vote = $votes['up'] - $votes['down']; - $p = floor(($votes['up'] / (($votes['up'] + $votes['down']) ? $votes['up'] + $votes['down'] : 1)) * 100); + $p = floor(($votes['up'] / (($votes['up'] + $votes['down']) ?: 1)) * 100); $rate = !$p && !($votes['up'] + $votes['down']) ? "no votes..." : "$p% like this..."; // Vote User Notes Div diff --git a/include/site.inc b/include/site.inc index 52abf35052..2e804a0690 100644 --- a/include/site.inc +++ b/include/site.inc @@ -71,7 +71,9 @@ function mirror_provider($site = FALSE) if (isset($MIRRORS[$site])) { return $MIRRORS[$site][1]; - } elseif (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) { + } + + if (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) { return $MIRRORS[$_SERVER['SERVER_ADDR']][1]; } @@ -87,7 +89,9 @@ function mirror_provider_url($site = FALSE) if (isset($MIRRORS[$site])) { return $MIRRORS[$site][3]; - } elseif (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) { + } + + if (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) { return $MIRRORS[$_SERVER['SERVER_ADDR']][3]; } @@ -103,7 +107,9 @@ function mirror_type($site = FALSE) if (isset($MIRRORS[$site])) { return $MIRRORS[$site][4]; - } elseif (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) { + } + + if (isset($MIRRORS[$_SERVER['SERVER_ADDR']])) { return $MIRRORS[$_SERVER['SERVER_ADDR']][4]; } @@ -138,12 +144,12 @@ function mirror_setcookie($name, $content, $exptime) if (!headers_sent()) { if (is_official_mirror()) { return setcookie($name, $content, time() + $exptime, '/', '.php.net'); - } else { - return setcookie($name, $content, time() + $exptime, '/'); } - } else { - return FALSE; + + return setcookie($name, $content, time() + $exptime, '/'); } + + return FALSE; } // Use this function to write out proper headers on @@ -216,7 +222,6 @@ function get_shortname($page) { if (strpos($shorturl, $section) === 0) { // We can make it even shorter return substr($shorturl, strlen($section), -4); - break; } } diff --git a/index.php b/index.php index 352d5750ee..7c6199945c 100644 --- a/index.php +++ b/index.php @@ -42,10 +42,9 @@ header("HTTP/1.1 304 Not Modified"); exit(); } + // Inform the user agent what is our last modification date -else { - header("Last-Modified: " . $tsstring); -} +header("Last-Modified: " . $tsstring); $_SERVER['BASE_PAGE'] = 'index.php'; include_once 'include/prepend.inc'; @@ -186,7 +185,7 @@ $announcements .= ' <a href="/conferences" class="headline" title="' . $conftype[$category] . '">' . $conftype[$category] .'</a>'; $announcements .= '<div class="body"><ul>'; foreach (array_slice($entries, 0, 4) as $url => $title) { - $title = preg_replace("'([A-Za-z0-9])([\s\:\-\,]*?)call for(.*?)$'i", "$1", $title); + $title = preg_replace("'([A-Za-z0-9])([\s:\-,]*?)call for(.*?)$'i", "$1", $title); $announcements .= "<li><a href='$url' title='$title'>$title</a></li>"; } $announcements .= '</ul></div>'; diff --git a/manual-lookup.php b/manual-lookup.php index f20d4a44e2..3715fef43e 100644 --- a/manual-lookup.php +++ b/manual-lookup.php @@ -31,5 +31,3 @@ // Fall back to a quick reference search $notfound = $function; include __DIR__ . '/quickref.php'; - -?> diff --git a/manual/add-note.php b/manual/add-note.php index c1ac4a3d64..52c3f51114 100644 --- a/manual/add-note.php +++ b/manual/add-note.php @@ -36,8 +36,7 @@ // Convert all line-endings to unix format, // and don't allow out-of-control blank lines - $note = str_replace("\r\n", "\n", $note); - $note = str_replace("\r", "\n", $note); + $note = str_replace(["\r\n", "\r"], "\n", $note); $note = preg_replace("/\n{2,}/", "\n\n", $note); // Don't pass through example username @@ -135,17 +134,14 @@ } // There was an error, or a preview is needed - else { - - // If there was an error, print out - if ($error) { echo "<p class=\"formerror\">$error</p>\n"; } - - // Print out preview of note - echo '<p>This is what your entry will look like, roughly:</p>'; - echo '<div id="usernotes">'; - manual_note_display(time(), $user, $note, FALSE); - echo '</div><br><br>'; - } + // If there was an error, print out + if ($error) { echo "<p class=\"formerror\">$error</p>\n"; } + + // Print out preview of note + echo '<p>This is what your entry will look like, roughly:</p>'; + echo '<div id="usernotes">'; + manual_note_display(time(), $user, $note, FALSE); + echo '</div><br><br>'; } // Any needed variable was missing => display instructions @@ -345,7 +341,7 @@ if (empty($_POST['user'])) { $_POST['user'] = "u...@example.com"; } // There is no section to add note to -if (!isset($_POST['sect']) || !isset($_POST['redirect'])) { +if (!isset($_POST['sect'], $_POST['redirect'])) { echo '<p class="formerror">To add a note, you must click on the "Add Note" button (the plus sign) ', 'on the bottom of a manual page so we know where to add the note!</p>'; } diff --git a/manual/index.php b/manual/index.php index 01404eda1f..b749d8a628 100644 --- a/manual/index.php +++ b/manual/index.php @@ -1,4 +1,3 @@ <?php include_once __DIR__ . '/../include/prepend.inc'; mirror_redirect("/manual/$LANG/index.php"); -?> diff --git a/manual/spam_challenge.php b/manual/spam_challenge.php index 1dbf94b93a..cd74ce5965 100644 --- a/manual/spam_challenge.php +++ b/manual/spam_challenge.php @@ -68,6 +68,3 @@ function test_answer($name, $an, $bn, $answer) { return ($nums[$c[0]($a, $b)] === $answer); } - - -?> diff --git a/manual/vote-note.php b/manual/vote-note.php index cb3a6be4be..c7040cdb97 100644 --- a/manual/vote-note.php +++ b/manual/vote-note.php @@ -39,10 +39,10 @@ } else { $r = json_decode($r); - if (json_last_error() == JSON_ERROR_NONE && isset($r->status) && $r->status && isset($r->votes)) { + if (isset($r->status, $r->votes) && $r->status) { $response["success"] = true; $response["update"] = (int)$r->votes; - } elseif (json_last_error() == JSON_ERROR_NONE && isset($r->status, $r->message) && $r->status == false) { + } elseif (isset($r->status, $r->message) && !$r->status) { $response["success"] = false; $response["msg"] = $r->message; } else { @@ -79,7 +79,7 @@ ); if (($r = posttohost($master_url, $data)) !== null && strpos($r,"failed to open socket to") === false) { $r = json_decode($r); - if (json_last_error() == JSON_ERROR_NONE && isset($r->status) && $r->status && isset($r->votes)) { + if (isset($r->status, $r->votes) && $r->status) { $thankyou = true; } else { $error = "Invalid request."; diff --git a/releases/index.php b/releases/index.php index 5fe76c287c..e60e36eabe 100644 --- a/releases/index.php +++ b/releases/index.php @@ -20,7 +20,7 @@ if (isset($RELEASES[$ver])) { $combinedReleases = array_replace_recursive($RELEASES, $OLDRELEASES); - $max = intval($_GET['max'] ?? 1); + $max = (int) ($_GET['max'] ?? 1); if ($max == -1) { $max = PHP_INT_MAX; } diff --git a/security/index.php b/security/index.php index dbccfbca14..b6d2bc1737 100644 --- a/security/index.php +++ b/security/index.php @@ -130,7 +130,7 @@ function cmp_records($a, $b) { $title = ucfirst(strtr($field, "-", " ")); // Turn urls into links (stolen from master/manage/user-notes.php) $data = preg_replace( - '!((mailto:|(http|ftp|nntp|news):\/\/).*?)(\s|<|\)|"|\\|\'|$)!', + '!((mailto:|(http|ftp|nntp|news)://).*?)(\s|<|\)|"|\\|\'|$)!', '<a href="\1" target="_blank">\1</a>\4', $data ); diff --git a/src/UserNotes/Sorter.php b/src/UserNotes/Sorter.php index 3fb32188a7..7850f214ee 100644 --- a/src/UserNotes/Sorter.php +++ b/src/UserNotes/Sorter.php @@ -45,9 +45,9 @@ private function calcVotePriority(array $note) { private function calcRatingPriority(array $note) { if ($note['total'] <= 2) { return 0.5; - } else { - return $note['rating']; } + + return $note['rating']; } @@ -70,11 +70,13 @@ private function calcSortPriority(array &$notes) { private function factorSort($a, $b) { if ($a['sort'] < $b['sort']) { return 1; - } elseif ($a['sort'] == $b['sort']) { + } + + if ($a['sort'] == $b['sort']) { return 0; - } else { - return -1; } + + return -1; } -- PHP Webmaster List Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php