Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CRM/Upgrade/DispatchPolicy.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static function pick(): ?array {
}

// Are there outstanding core version upgrades?
$upgradeFinished = !CRM_Core_BAO_Domain::isDBUpdateRequired();
$upgradeFinished = !\CRM_Upgrade_Versions::upgradesPending();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW | CONFIRMED] Other 'upgrade pending' checks still compare the DB version to the XML version only

Only DispatchPolicy::pick() moved to CRM_Upgrade_Versions::upgradesPending(). These still compare against CRM_Utils_System::version(): CRM_Core_BAO_Domain::isDBUpdateRequired() (used by Env.php:830/916, Schema.php:97 and civiimport.php:87) and Civi\Schema\EntityProvider::getSupportedFields(). When pre-release steps are pending and the DB version equals the XML version, these report no upgrade needed and do not hide fields that have not been added yet.

Suggested fix: Have isDBUpdateRequired() delegate to CRM_Upgrade_Versions::upgradesPending(), or state explicitly that this is out of scope for dev sites.

Evidence (80%, `correctness`)

Failure scenario: A dev site's DB version equals the XML version, and an unapplied pre-release step exists above it. The 'database upgrade required' status check never appears, so the site owner is not told to run the upgrade. Behaviour now differs between the upgrader and the status checks.

Verification evidence: I read Domain.php:112-116 at head and EntityProvider.php:69-83. civicrm_grep lists the remaining callers. This only affects dev sites that have pre-release steps (the PR body says so), which is why severity is low. I did not run it, because the stack has no step above the XML version.

References: civicrm-core/CRM/Core/BAO/Domain.php:112, civicrm-core/Civi/Schema/EntityProvider.php:71, civicrm-core/CRM/Utils/Check/Component/Env.php:916


return CRM_Upgrade_DispatchPolicy::get($upgradeFinished ? 'upgrade.finish' : 'upgrade.main');
}
Expand Down
63 changes: 11 additions & 52 deletions CRM/Upgrade/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,38 +96,19 @@ public function __construct(
*/
public static function &incrementalPhpObject($version) {
static $incrementalPhpObject = [];

$versionParts = explode('.', $version);
$versionName = CRM_Utils_EnglishNumber::toCamelCase($versionParts[0]) . CRM_Utils_EnglishNumber::toCamelCase($versionParts[1]);

if (!array_key_exists($versionName, $incrementalPhpObject)) {
$className = "CRM_Upgrade_Incremental_php_{$versionName}";
$incrementalPhpObject[$versionName] = new $className();
$version = (string) $version;
if (!array_key_exists($version, $incrementalPhpObject)) {
$incrementalPhpObject[$version] = CRM_Upgrade_Versions::getIncrementalPhpObject($version);
}
return $incrementalPhpObject[$versionName];
return $incrementalPhpObject[$version];
}

/**
* @return array
* ex: ['5.13', '5.14', '5.15']
*/
public static function incrementalPhpObjectVersions() {
$versions = [];

$phpDir = implode(DIRECTORY_SEPARATOR, [dirname(__FILE__), 'Incremental', 'php']);
$phpFiles = glob("$phpDir/*.php");
foreach ($phpFiles as $phpFile) {
$phpWord = substr(basename($phpFile), 0, -4);
if (CRM_Utils_EnglishNumber::isNumeric($phpWord)) {
/** @var \CRM_Upgrade_Incremental_Base $instance */
$className = 'CRM_Upgrade_Incremental_php_' . $phpWord;
$instance = new $className();
$versions[] = $instance->getMajorMinor();
}
}

usort($versions, 'version_compare');
return $versions;
return \CRM_Upgrade_Versions::incrementalPhpObjectVersions();
}

/**
Expand Down Expand Up @@ -241,15 +222,7 @@ public function logVersion($newVersion) {
* @throws Exception
*/
public function getRevisionSequence() {
$revList = [];

foreach (self::incrementalPhpObjectVersions() as $majorMinor) {
$phpUpgrader = self::incrementalPhpObject($majorMinor);
$revList = array_merge($revList, array_values($phpUpgrader->getRevisionSequence()));
}

usort($revList, 'version_compare');
return $revList;
return \CRM_Upgrade_Versions::getRevisionSequence();
}

/**
Expand Down Expand Up @@ -315,19 +288,9 @@ public function processSQL($rev) {
* @return array(0=>$currentVer, 1=>$latestVer)
*/
public function getUpgradeVersions() {
$latestVer = CRM_Utils_System::version();
$currentVer = CRM_Core_BAO_Domain::version(TRUE);
if (!$currentVer) {
throw new CRM_Core_Exception(ts('Version information missing in civicrm database.'));
}
elseif (stripos($currentVer, 'upgrade')) {
throw new CRM_Core_Exception(ts('Database check failed - the database looks to have been partially upgraded. You may want to reload the database with the backup and try the upgrade process again.'));
}
if (!$latestVer) {
throw new CRM_Core_Exception(ts('Version information missing in civicrm codebase.'));
}

return [$currentVer, $latestVer];
$versions = \CRM_Upgrade_Versions::getUpgradeVersions();
\CRM_Upgrade_Versions::validateUpgradeVersions($versions[0], $versions[1]);
return $versions;
}

/**
Expand Down Expand Up @@ -546,12 +509,8 @@ public static function buildQueue($currentVer, $latestVer, $postUpgradeMessageFi
);
$queue->createItem($task, ['weight' => 0]);

$revisions = $upgrade->getRevisionSequence();
$maxRevision = empty($revisions) ? NULL : end($revisions);
$revisions = \CRM_Upgrade_Versions::getRevisionSequence();
reset($revisions);
if (version_compare($latestVer, $maxRevision, '<')) {
throw new CRM_Core_Exception("Malformed upgrade sequence. The incremental update $maxRevision exceeds target version $latestVer");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The trouble with removing this is that if would have caught typos in upgrade method/sql.tpl names.
I would suggest only skipping the exception if the version string ends in .alpha\d so it works on CI but only for pre-release versions... but that doesn't actually solve #38063 since it's 6.20.1 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeh, I don't think checking alpha works.

if would have caught typos in upgrade method/sql.tpl names.

What sort of typo? At any rate to me that feels like a check that should happen at release time (maybe as part of set-version.php) rather than at runtime

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've added a sanity check to set-version.php now

}

foreach ($revisions as $rev) {
// proceed only if $currentVer < $rev
Expand Down Expand Up @@ -937,7 +896,7 @@ public function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $latestVe
// Scan through all php files and see if any file is interested in setting pre-upgrade-message
// based on $currentVer, $latestVer.
// Please note, at this point upgrade hasn't started executing queries.
$revisions = $this->getRevisionSequence();
$revisions = \CRM_Upgrade_Versions::getRevisionSequence();
foreach ($revisions as $rev) {
if (version_compare($currentVer, $rev) < 0) {
$versionObject = $this->incrementalPhpObject($rev);
Expand Down
8 changes: 8 additions & 0 deletions CRM/Upgrade/Incremental/General.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ public static function setPreUpgradeMessage(&$preUpgradeMessage, $currentVer, $l
]);
$preUpgradeMessage .= '</p>';
}
if (version_compare(CRM_Utils_System::version(), $latestVer, '<')) {
$preUpgradeMessage .= '<p>';
$preUpgradeMessage .= ts('This upgrade includes pre-release database upgrade steps up to %1. The released code version is %2. You should only continue if you know what you are doing.', [
1 => $latestVer,
2 => CRM_Utils_System::version(),
]);
$preUpgradeMessage .= '</p>';
}

// http://issues.civicrm.org/jira/browse/CRM-13572
// Depending on how the code was upgraded, some sites may still have copies of old
Expand Down
112 changes: 112 additions & 0 deletions CRM/Upgrade/Versions.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
<?php
/*
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC. All rights reserved. |
| |
| This work is published under the GNU AGPLv3 license with some |
| permitted exceptions and without any warranty. For full license |
| and copyright information, see https://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/

/**
* Upgrade version management
*/
class CRM_Upgrade_Versions {

/**
* @param string $version
* Ex: '5.22' or '5.22.3'
*
* @return CRM_Upgrade_Incremental_Base
* Ex: CRM_Upgrade_Incremental_php_FiveTwentyTwo
*/
public static function getIncrementalPhpObject(string $version) {
$versionParts = explode('.', $version);
$versionName = CRM_Utils_EnglishNumber::toCamelCase($versionParts[0]) . CRM_Utils_EnglishNumber::toCamelCase($versionParts[1]);
$className = "CRM_Upgrade_Incremental_php_{$versionName}";
return new $className();
}

/**
* @return array
* ex: ['5.13', '5.14', '5.15']
*/
public static function incrementalPhpObjectVersions() {
$versions = [];
$phpDir = implode(DIRECTORY_SEPARATOR, [dirname(__FILE__), 'Incremental', 'php']);
$phpFiles = glob("$phpDir/*.php");
foreach ($phpFiles as $phpFile) {
$phpWord = substr(basename($phpFile), 0, -4);
if (CRM_Utils_EnglishNumber::isNumeric($phpWord)) {
/** @var \CRM_Upgrade_Incremental_Base $instance */
$className = 'CRM_Upgrade_Incremental_php_' . $phpWord;
$instance = new $className();
$versions[] = $instance->getMajorMinor();
}
}
usort($versions, 'version_compare');

return $versions;
}

/**
* Get a list of all patch-versions that appear in upgrade steps, whether
* as *.mysql.tpl or as *.php.
*
* @return array
* @throws Exception
*/
public static function getRevisionSequence() {
$revList = [];

foreach (self::incrementalPhpObjectVersions() as $majorMinor) {
$phpUpgrader = self::getIncrementalPhpObject($majorMinor);
$revList = array_merge($revList, array_values($phpUpgrader->getRevisionSequence()));
}

usort($revList, 'version_compare');
return $revList;
}

public static function getLatestVersion() {
$xmlVersion = \CRM_Utils_System::version();

$revisions = self::getRevisionSequence();
$maxRevision = empty($revisions) ? NULL : end($revisions);
if ($maxRevision && version_compare($xmlVersion, $maxRevision, '<')) {
// e.g. running upgrader pre-release
return $maxRevision;
}
return $xmlVersion;
}

/**
* Determine the start and end version of the upgrade process.
*
* @return array(0=>$currentVer, 1=>$latestVer)
*/
public static function getUpgradeVersions() {
$latestVer = self::getLatestVersion();
$currentVer = CRM_Core_BAO_Domain::version(TRUE);
return [$currentVer, $latestVer];
}

public static function validateUpgradeVersions(string $currentVer, string $latestVer) {
if (!$currentVer) {
throw new CRM_Core_Exception(ts('Version information missing in civicrm database.'));
}
elseif (stripos($currentVer, 'upgrade')) {
throw new CRM_Core_Exception(ts('Database check failed - the database looks to have been partially upgraded. You may want to reload the database with the backup and try the upgrade process again.'));
}
if (!$latestVer) {
throw new CRM_Core_Exception(ts('Version information missing in civicrm codebase.'));
}
Comment on lines +95 to +104

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW | PROVEN] validateUpgradeVersions(string $currentVer) turns the 'Version information missing' error into a TypeError

CRM_Core_BAO_Domain::version(TRUE) returns whatever singleValueQuery() returns, which is NULL when there is no version. CRM_Upgrade_Form::getUpgradeVersions() passes that value straight into validateUpgradeVersions(string $currentVer, string $latestVer). PHP throws a TypeError for a NULL argument to a non-nullable string parameter, so the friendly if (!$currentVer) CRM_Core_Exception can never be reached for NULL. Before this PR, the inline code handled NULL correctly.

Suggested fix: Make the parameters nullable or untyped, so the existing falsy checks still run and throw CRM_Core_Exception.

Suggested change
public static function validateUpgradeVersions(string $currentVer, string $latestVer) {
if (!$currentVer) {
throw new CRM_Core_Exception(ts('Version information missing in civicrm database.'));
}
elseif (stripos($currentVer, 'upgrade')) {
throw new CRM_Core_Exception(ts('Database check failed - the database looks to have been partially upgraded. You may want to reload the database with the backup and try the upgrade process again.'));
}
if (!$latestVer) {
throw new CRM_Core_Exception(ts('Version information missing in civicrm codebase.'));
}
public static function validateUpgradeVersions(?string $currentVer, ?string $latestVer) {
Evidence (95%, `correctness`)

Failure scenario: A database whose civicrm_domain.version is NULL or whose domain row is missing runs the web upgrader or cv updb. The user should see 'Version information missing in civicrm database.' Instead they get an uncaught TypeError: ... Argument #1 ($currentVer) must be of type string, null given.

Verification evidence: I read Versions.php:95-105 and Domain.php:88-103 at head. A live probe on stack B passed a NULL from singleValueQuery and got a TypeError instead of a CRM_Core_Exception. Severity is lowered to low because a NULL domain version is a rare, already-broken database state. Only the error message gets worse.

Proof command: cv ev "try { \CRM_Upgrade_Versions::validateUpgradeVersions(CRM_Core_DAO::singleValueQuery('SELECT NULL'), '6.22.alpha1'); } catch (\Throwable $e) { echo get_class($e) . ': ' . $e->getMessage(); }" (target B)

TypeError: CRM_Upgrade_Versions::validateUpgradeVersions(): Argument #1 ($currentVer) must be of type string, null given

References: civicrm-core/CRM/Core/BAO/Domain.php:88

}

public static function upgradesPending(): bool {
[$dbVersion, $codeVersion] = self::getUpgradeVersions();
return version_compare($dbVersion, $codeVersion) < 0;
}

}
19 changes: 13 additions & 6 deletions tools/bin/scripts/set-version.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

$oldVersion = (string) simplexml_load_file("xml/version.xml")->version_no;
if (!isVersionValid($oldVersion)) {
fatal("failed to read old version from \"xml/version.xml\"\n");
fatal("failed to read old version from \"xml/version.xml\"");
}

/**
Expand All @@ -34,7 +34,7 @@
extract(parseArgs($argv));

if (!isVersionValid($newVersion)) {
fatal("failed to read new version\n");
fatal("failed to read new version");
}

/* *********************************************************************** */
Expand All @@ -44,6 +44,11 @@

echo "Changing version from $oldVersion to $newVersion...\n";

$latestVersion = exec("cv ev --level=classloader 'echo \CRM_Upgrade_Versions::getLatestVersion();'");
if (version_compare($newVersion, $latestVersion, '<')) {
fatal("db upgrade steps are declared up to {$latestVersion} - cannot set release version lower than this!");
}
Comment on lines +47 to +50

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[LOW | PROVEN] set-version.php upgrade-step guard silently passes if cv is missing or fails

exec("cv ev --level=classloader ...") returns an empty string when cv is not installed, cannot find the checkout or errors out, because errors go to stderr. version_compare($newVersion, '', '<') is FALSE, so the check passes without any message. The exit code and output format are not checked. This check replaces the removed runtime 'Malformed upgrade sequence' guard, so failing open removes the only remaining protection. It also runs after syncPackagesBranch() (line 43), so any failure would come after that step has already run.

Suggested fix: Capture the return code and validate the output, then fail hard. Move the check above syncPackagesBranch().

Suggested change
$latestVersion = exec("cv ev --level=classloader 'echo \CRM_Upgrade_Versions::getLatestVersion();'");
if (version_compare($newVersion, $latestVersion, '<')) {
fatal("db upgrade steps are declared up to {$latestVersion} - cannot set release version lower than this!");
}
$latestVersion = exec("cv ev --level=classloader 'echo \\CRM_Upgrade_Versions::getLatestVersion();'", $out, $rc);
if ($rc !== 0 || !isVersionValid($latestVersion)) {
fatal("unable to determine latest declared upgrade version via cv");
}
Evidence (90%, `correctness`)

Failure scenario: The release script runs set-version.php somewhere without a working cv (for example a bare checkout, as colemanw and seamuslee001 described). A release is tagged with a version below the highest declared upgrade step and no error appears. Sites then upgrade to a DB version above the code version.

Verification evidence: I read set-version.php:40-50 at head. A live probe on B showed that exec() of a failing command returns an empty string, and that version_compare('6.22.0', '', '<') is FALSE. I did not verify whether the releaser environment has a working cv.

Proof command: php -r "$v = exec('cv-does-not-exist ev x 2>/dev/null'); var_dump($v, version_compare('6.22.0', $v, '<'));" (target B)

string(0) ""
bool(false)


$verName = makeVerName($newVersion);
$phpFile = initFile("CRM/Upgrade/Incremental/php/{$verName}.php", function () use ($verName, $newVersion) {
ob_start();
Expand Down Expand Up @@ -121,7 +126,7 @@ function($file) {
*/
function updateFile($file, $callback) {
if (!file_exists($file)) {
die("File does not exist: $file\n");
die("File does not exist: $file");
}
echo "Update \"$file\"\n";
$content = file_get_contents($file);
Expand Down Expand Up @@ -187,7 +192,9 @@ function isVersionValid($v) {
* @param $error
*/
function fatal($error) {
echo $error;
echo "\n";
echo "ERROR: {$error}\n";
echo "\n";
echo "usage: set-version.php <new-version> [<new-date>] [--sql|--no-sql] [--commit|--no-commit]\n";
echo " --sql A placeholder *.sql file will be created.\n";
echo " --no-sql A placeholder *.sql file will not be created.\n";
Expand Down Expand Up @@ -236,7 +243,7 @@ function parseArgs($argv) {
$positional[] = $arg;
}
else {
fatal("Unrecognized argument: $arg\n");
fatal("Unrecognized argument: $arg");
}
break;
}
Expand All @@ -248,7 +255,7 @@ function parseArgs($argv) {
}

if (!isset($parsed['doCommit'])) {
fatal("Must specify --commit or --no-commit\n");
fatal("Must specify --commit or --no-commit");
}

return $parsed;
Expand Down