<?php

////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// Version 1.2.0                                                              //
// Author: Kim Birkeland Skorgenes (info@newstargeted.com)                    //
// Website: https://newstargeted.com                                          //
// CMS - CMS Made Simple                                                      //
// (c)2004 by Ted Kulp (wishy@users.sf.net)                                   //
// This project's homepage is: https://newstargeted.com                       //
//                                                                            //
// SECURITY WARNING: This plugin exposes sensitive server information.        //
// Access is restricted to administrators with "Manage Settings" permission.  //
//                                                                            //
// This program is free software; you can redistribute it and/or modify       //
// it under the terms of the GNU General Public License as published by       //
// the Free Software Foundation; either version 2 of the License, or          //
// (at your option) any later version.                                        //
// This program is distributed in the hope that it will be useful,            //
// but WITHOUT ANY WARRANTY; without even the implied warranty of             //
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              //
// GNU General Public License for more details.                               //
// You should have received a copy of the GNU General Public License          //
// along with this program; if not, write to the Free Software                //
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

/**
 * Minimum PHP versions that include upstream fixes for the critical
 * unauthenticated RCE advisories CVE-2026-109618 and CVE-2026-109619
 * (PHP security releases of 21 October 2026). Update this table when
 * php.net publishes newer security floors for a branch.
 *
 * Keys are major.minor branch strings. Values are the lowest safe
 * major.minor.patch release for that branch.
 *
 * @return array
 */
function phpinfo_plugin_security_floor_map()
{
    return array(
        '8.5' => '8.5.12',
        '8.4' => '8.4.27',
        '8.3' => '8.3.36',
        '8.2' => '8.2.35',
        // 8.6 was pre-GA when these CVEs shipped; RC4+ carries the fixes.
        // Treat any 8.6.0 release candidate below RC4 as vulnerable.
        '8.6' => '8.6.0RC4',
    );
}

/**
 * Normalize PHP_VERSION into comparable parts.
 *
 * @param string $version
 * @return array{branch:string,numeric:string,suffix:string,is_dev:bool,raw:string}
 */
function phpinfo_plugin_parse_php_version($version)
{
    $raw = trim((string) $version);
    $suffix = '';
    $numeric = $raw;
    $is_dev = false;

    if (preg_match('/^(\d+\.\d+\.\d+)(.*)$/', $raw, $m)) {
        $numeric = $m[1];
        $suffix = isset($m[2]) ? (string) $m[2] : '';
        if ($suffix !== '' && preg_match('/(alpha|beta|rc|dev)/i', $suffix)) {
            $is_dev = true;
        }
    }

    $branch = '0.0';
    if (preg_match('/^(\d+\.\d+)/', $numeric, $bm)) {
        $branch = $bm[1];
    }

    return array(
        'branch' => $branch,
        'numeric' => $numeric,
        'suffix' => $suffix,
        'is_dev' => $is_dev,
        'raw' => $raw,
    );
}

/**
 * Compare two version tokens that may include RC suffixes (e.g. 8.6.0RC5).
 *
 * @param string $a
 * @param string $b
 * @return int -1 if $a < $b, 0 if equal, 1 if $a > $b
 */
function phpinfo_plugin_version_compare_tokens($a, $b)
{
    $pa = phpinfo_plugin_parse_php_version($a);
    $pb = phpinfo_plugin_parse_php_version($b);

    $cmp = version_compare($pa['numeric'], $pb['numeric']);
    if ($cmp !== 0) {
        return $cmp;
    }

    // Stable (empty suffix) ranks above pre-release suffixes.
    $sa = strtoupper(ltrim($pa['suffix'], '-'));
    $sb = strtoupper(ltrim($pb['suffix'], '-'));
    if ($sa === $sb) {
        return 0;
    }
    if ($sa === '') {
        return 1;
    }
    if ($sb === '') {
        return -1;
    }

    // Normalize RC / ALPHA / BETA for strcmp of pre-release tags.
    return version_compare(
        preg_replace('/[^A-Z0-9.]/i', '.', $sa),
        preg_replace('/[^A-Z0-9.]/i', '.', $sb)
    );
}

/**
 * Assess whether the running PHP build meets known security floors.
 *
 * @param string|null $phpVersion Override for tests; defaults to PHP_VERSION.
 * @return array{
 *   status:string,
 *   title:string,
 *   message:string,
 *   php_version:string,
 *   branch:string,
 *   min_safe:string,
 *   cves:array,
 *   eol:bool,
 *   pre_release:bool
 * }
 */
function phpinfo_plugin_assess_php_security($phpVersion = null)
{
    $parsed = phpinfo_plugin_parse_php_version(
        $phpVersion !== null ? $phpVersion : PHP_VERSION
    );
    $floors = phpinfo_plugin_security_floor_map();
    $branch = $parsed['branch'];
    $cves = array('CVE-2026-109618', 'CVE-2026-109619');
    $eolBranches = array('5.6', '7.0', '7.1', '7.2', '7.3', '7.4', '8.0', '8.1');

    $result = array(
        'status' => 'unknown',
        'title' => 'PHP security status unknown',
        'message' => 'Could not classify this PHP version against the bundled security floor table.',
        'php_version' => $parsed['raw'],
        'branch' => $branch,
        'min_safe' => '',
        'cves' => $cves,
        'eol' => in_array($branch, $eolBranches, true),
        'pre_release' => $parsed['is_dev'],
    );

    // Unsupported / EOL branches: no complete upstream fix stream.
    if ($result['eol']) {
        $result['status'] = 'vulnerable';
        $result['title'] = 'PHP branch is end of life';
        $result['message'] = 'PHP ' . $branch . ' is end of life and does not receive regular upstream security fixes. '
            . 'CVE-2026-109618 / CVE-2026-109619 affect unpatched builds. Upgrade to a supported branch '
            . '(minimum patched: 8.2.35, 8.3.36, 8.4.27, or 8.5.12) or apply a trusted vendor backport.';
        return $result;
    }

    if (!isset($floors[$branch])) {
        // Newer than our table (e.g. future 8.7+): assume OK but note the check is best-effort.
        if (version_compare($branch, '8.6', '>')) {
            $result['status'] = 'ok';
            $result['title'] = 'PHP branch newer than bundled advisory table';
            $result['message'] = 'Running PHP ' . $parsed['raw'] . '. This branch is newer than the bundled CVE floor map. '
                . 'Confirm current advisories at https://www.php.net/releases/ and your OS vendor.';
            return $result;
        }

        $result['status'] = 'vulnerable';
        $result['title'] = 'Unsupported or unexpected PHP branch';
        $result['message'] = 'PHP ' . $parsed['raw'] . ' is not covered as a supported security branch in this plugin. Upgrade to a current supported release.';
        return $result;
    }

    $minSafe = $floors[$branch];
    $result['min_safe'] = $minSafe;
    $cmp = phpinfo_plugin_version_compare_tokens($parsed['raw'], $minSafe);

    if ($cmp < 0) {
        $result['status'] = 'vulnerable';
        $result['title'] = 'Vulnerable PHP version detected';
        $result['message'] = 'Running PHP ' . $parsed['raw'] . ', which is below the minimum patched release '
            . $minSafe . ' for branch ' . $branch . '. Critical unauthenticated RCE issues '
            . implode(' / ', $cves)
            . ' are fixed starting at that version. Update PHP immediately; there is no complete configuration-only mitigation.';
        return $result;
    }

    if ($parsed['is_dev']) {
        $result['status'] = 'warning';
        $result['title'] = 'Pre-release PHP build';
        $result['message'] = 'Running pre-release PHP ' . $parsed['raw'] . '. It meets or exceeds the known security floor '
            . $minSafe . ' for ' . implode(' / ', $cves)
            . ', but pre-release builds are not recommended for production. Prefer a stable GA release when available.';
        return $result;
    }

    $result['status'] = 'ok';
    $result['title'] = 'No known critical PHP version vulnerability';
    $result['message'] = 'Running PHP ' . $parsed['raw'] . ', which meets or exceeds the minimum patched release '
        . $minSafe . ' for ' . implode(' / ', $cves)
        . '. Keep PHP updated and re-check after each php.net security announcement. Distro backports may report an older version string while still being patched; verify with your vendor if unsure.';
    return $result;
}

/**
 * Render the security assessment banner (admin-only HTML).
 *
 * @param array $assessment
 * @return string
 */
function phpinfo_plugin_render_security_banner(array $assessment)
{
    $colors = array(
        'ok' => array('border' => '#2e7d32', 'bg' => '#e8f5e9', 'fg' => '#1b5e20'),
        'warning' => array('border' => '#ef6c00', 'bg' => '#fff3e0', 'fg' => '#e65100'),
        'vulnerable' => array('border' => '#c62828', 'bg' => '#ffebee', 'fg' => '#b71c1c'),
        'unknown' => array('border' => '#546e7a', 'bg' => '#eceff1', 'fg' => '#37474f'),
    );
    $status = isset($assessment['status']) ? $assessment['status'] : 'unknown';
    $palette = isset($colors[$status]) ? $colors[$status] : $colors['unknown'];

    $cveList = '';
    if (!empty($assessment['cves']) && is_array($assessment['cves'])) {
        $escaped = array();
        foreach ($assessment['cves'] as $cve) {
            $escaped[] = htmlspecialchars((string) $cve, ENT_QUOTES, 'UTF-8');
        }
        $cveList = implode(', ', $escaped);
    }

    $html = '<div class="nt-phpinfo-security" style="margin:12px 0;padding:12px 14px;border:2px solid '
        . $palette['border'] . ';background:' . $palette['bg'] . ';color:' . $palette['fg']
        . ';font-family:system-ui,Segoe UI,sans-serif;font-size:14px;line-height:1.45;">';
    $html .= '<strong style="display:block;margin-bottom:6px;">'
        . htmlspecialchars($assessment['title'], ENT_QUOTES, 'UTF-8')
        . '</strong>';
    $html .= '<p style="margin:0 0 8px 0;">'
        . htmlspecialchars($assessment['message'], ENT_QUOTES, 'UTF-8')
        . '</p>';
    $html .= '<ul style="margin:0;padding-left:18px;">';
    $html .= '<li><strong>Detected PHP:</strong> '
        . htmlspecialchars($assessment['php_version'], ENT_QUOTES, 'UTF-8') . '</li>';
    if ($assessment['min_safe'] !== '') {
        $html .= '<li><strong>Minimum patched for this branch:</strong> '
            . htmlspecialchars($assessment['min_safe'], ENT_QUOTES, 'UTF-8') . '</li>';
    }
    if ($cveList !== '') {
        $html .= '<li><strong>Tracked advisories:</strong> ' . $cveList . '</li>';
    }
    $html .= '<li><strong>Status code:</strong> '
        . htmlspecialchars($status, ENT_QUOTES, 'UTF-8') . '</li>';
    $html .= '</ul>';
    $html .= '<p style="margin:8px 0 0 0;font-size:12px;">Reference: '
        . '<a href="https://www.php.net/releases/" target="_blank" rel="noopener noreferrer">php.net releases</a>'
        . ' and the PHP Foundation security announcements.</p>';
    $html .= '</div>';

    return $html;
}

function smarty_function_phpinfo($params, $template)
{
    try {
        if (!check_permission(get_userid(false), 'Manage Settings')) {
            return '<div style="color:red;padding:10px;border:1px solid red;background:#ffe6e6;">'
                . '<strong>Access Denied:</strong> Administrator privileges required to view PHP information.'
                . '</div>';
        }

        $assessment = phpinfo_plugin_assess_php_security();
        $banner = phpinfo_plugin_render_security_banner($assessment);

        $mode = 'full';
        if (isset($params['mode'])) {
            $mode = strtolower(trim((string) $params['mode']));
        } elseif (isset($params['check_only']) && ($params['check_only'] === '1' || $params['check_only'] === 1 || $params['check_only'] === true)) {
            $mode = 'check';
        }

        if ($mode === 'check' || $mode === 'security') {
            return $banner;
        }

        ob_start();
        phpinfo();
        $output = ob_get_clean();

        if ($output === false || $output === '') {
            return $banner . '<div style="color:orange;padding:10px;border:1px solid orange;background:#fff8dc;">'
                . '<strong>Warning:</strong> Unable to retrieve PHP information.'
                . '</div>';
        }

        return $banner . $output;
    } catch (Exception $e) {
        error_log('phpinfo plugin error: ' . $e->getMessage());
        return '<div style="color:red;padding:10px;border:1px solid red;background:#ffe6e6;">'
            . '<strong>Error:</strong> An error occurred while retrieving PHP information.'
            . '</div>';
    }
}

function smarty_cms_help_function_phpinfo()
{
?>
	<h3>What does this do?</h3>
	<p>This plugin displays comprehensive PHP configuration information from the server, and runs a built-in check against known critical PHP version security floors (CVE-2026-109618 / CVE-2026-109619).</p>

	<h3>Security Notice</h3>
	<p style="color:red;"><strong>Important:</strong> This plugin is restricted to administrators with "Manage Settings" permission only.
	It exposes sensitive server information including PHP version, configuration, loaded extensions, and environment variables.</p>

	<h3>Usage</h3>
	<p><strong>Important:</strong> For best results, use this plugin on a page with a "block" template (minimal template without header/footer) to avoid HTML conflicts.</p>
	<p><strong>Example (Basic):</strong></p>
	<pre>{phpinfo}</pre>
	<p><strong>Example (Security check only):</strong></p>
	<pre>{phpinfo mode="check"}</pre>
	<p><strong>Recommended Setup:</strong></p>
	<ol>
		<li>Create a new page in CMS Made Simple (e.g., "PHP Info")</li>
		<li>Assign a "block" or minimal template to this page</li>
		<li>Add <code>{phpinfo}</code> to the page content</li>
		<li>Access the page as an administrator</li>
	</ol>
	<p>This will display:</p>
	<ul>
		<li>A PHP version vulnerability / security-floor banner</li>
		<li>PHP version and build information</li>
		<li>Server configuration and settings</li>
		<li>Loaded PHP extensions and modules</li>
		<li>Environment variables</li>
		<li>PHP directives and their values</li>
	</ul>
	<p><strong>Note:</strong> phpinfo() outputs a full HTML document. Using a block template prevents conflicts with your site's layout and ensures proper display.</p>

	<h3>Requirements</h3>
	<ul>
		<li>Administrator access with "Manage Settings" permission</li>
		<li>PHP 7.4 - 8.6 compatible (plugin runs on older PHP to warn about EOL / vulnerable builds)</li>
	</ul>

	<p>As you can see this is a simple yet powerful diagnostic plugin. Feel free to send your comments to: <a href="mailto:info@newstargeted.com">info@newstargeted.com</a>.</p>
<?php
}

function smarty_cms_about_function_phpinfo()
{
?>
	<p><strong>Author: </strong>Kim Birkeland Skorgenes<br />
	<strong>Version: </strong>1.2.0<br />
	<strong>PHP Compatibility: </strong>7.4 - 8.6<br />
	<strong>Change History: </strong><br />
	<ul>
		<li><strong>1.2.0</strong> (08.11.2026) - PHP version vulnerability check:
			<ul>
				<li>Added admin security banner that compares PHP_VERSION to known patched floors for CVE-2026-109618 and CVE-2026-109619 (8.2.35 / 8.3.36 / 8.4.27 / 8.5.12 / 8.6.0RC4+)</li>
				<li>Flags end-of-life branches (7.4 / 8.0 / 8.1 and older) as vulnerable / unsupported</li>
				<li>Warns on pre-release builds even when the security floor is met</li>
				<li>Added <code>{phpinfo mode="check"}</code> to show only the security assessment</li>
				<li>Verified on LiteSpeed lsphp85 (PHP 8.5.12) and Remi CLI php86 (8.6.0RC5)</li>
			</ul>
		</li>
		<li><strong>1.1</strong> (17.10.2025) - Security and compatibility update:
			<ul>
				<li>Added admin-only access restriction (requires "Manage Settings" permission)</li>
				<li>Fixed deprecated pass-by-reference syntax for PHP 8+ compatibility</li>
				<li>Implemented output buffering to properly capture phpinfo() output</li>
				<li>Added comprehensive error handling with try-catch blocks</li>
				<li>Fixed syntax errors in help function</li>
				<li>Added security warnings in documentation</li>
				<li>Verified compatibility with PHP 7.4 through 8.6</li>
			</ul>
		</li>
		<li><strong>1.0</strong> - Initial release</li>
	</ul>
	</p>
<?php
}
