Skip to content

Wallos: Open-source, self-hostable personal subscription tracker. Visualize your recurring expenses, manage your budget, and save money.

fix: sort categories by the order column, not by the string 'order' (#1198)

thorstenhornung1098d1b0a9d32
diff --git a/includes/stats_calculations.php b/includes/stats_calculations.php
index 047937d..fc827c7 100644
--- a/includes/stats_calculations.php
+++ b/includes/stats_calculations.php
@@ -29,7 +29,7 @@ function getPriceConverted($price, $currency, $database, $userId)
// Get categories
$categories = array();
-$query = "SELECT * FROM categories WHERE user_id = :userId ORDER BY 'order' ASC";
+$query = "SELECT * FROM categories WHERE user_id = :userId ORDER BY `order` ASC";
$stmt = $db->prepare($query);
$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
diff --git a/tests/cases/order_by_test.php b/tests/cases/order_by_test.php
new file mode 100644
index 0000000..0e06095
--- /dev/null
+++ b/tests/cases/order_by_test.php
@@ -0,0 +1,55 @@
+<?php
+/*
+ ORDER BY names a column, not a string.
+
+ `ORDER BY 'order'` sorts by a constant. Every row gets the same sort key, so
+ SQLite returns them in whatever order it happens to have them and the list
+ looks unsorted for no visible reason: the statement is valid, nothing warns,
+ and the column the user drags into place is never consulted.
+
+ The same query is written four other times in this codebase, all four with
+ the column quoted as an identifier. This checks that they stay that way, and
+ that a fifth is not written the other way.
+
+ The rule is general on purpose: `ORDER BY '<anything>'` is a constant, and
+ sorting by a constant is never what anybody means.
+*/
+
+wallos_test('no query sorts by a string constant', function () {
+ $offenders = [];
+ $checked = 0;
+
+ $directory = new RecursiveIteratorIterator(
+ new RecursiveDirectoryIterator(WALLOS_ROOT, RecursiveDirectoryIterator::SKIP_DOTS));
+
+ foreach ($directory as $file) {
+ $path = str_replace(WALLOS_ROOT . '/', '', $file->getPathname());
+
+ if ($file->getExtension() !== 'php'
+ || strpos($path, 'libs/') === 0
+ || strpos($path, 'tests/') === 0) {
+ continue;
+ }
+
+ foreach (preg_split('/\R/', file_get_contents($file->getPathname())) as $number => $line) {
+ if (stripos($line, 'ORDER BY') === false) {
+ continue;
+ }
+
+ $checked++;
+
+ // A single-quoted token straight after ORDER BY is a constant. An
+ // identifier is bare, backticked or double-quoted.
+ if (preg_match("/ORDER\s+BY\s+'/i", $line) === 1) {
+ $offenders[] = $path . ':' . ($number + 1) . ' - ' . trim($line);
+ }
+ }
+ }
+
+ // A guard that finds nothing passes its own assertion.
+ assert_true($checked >= 5,
+ 'the ORDER BY clauses were found (' . $checked . ' lines)');
+
+ assert_same([], $offenders,
+ 'no ORDER BY sorts by a constant: ' . implode(' | ', $offenders));
+});