From e81eed542c3d005a745103b6a33b6bab3d0ac41b Mon Sep 17 00:00:00 2001 From: Tim Hunt Date: Wed, 16 Feb 2011 11:42:33 +0000 Subject: [PATCH] MDL-26425 tablelib better validation of the sort code, also some cleanup. You may think that the extra validation is unnecessary, since the sort fields are already validated when the URL parameters are parsed, however that overlooks an important point. There may be other options that affect which columns are in the SQL, for example the quiz show individual question grades setting. These other options can cause a column that was in the table, and being sorted on, to disappear. Therefore, it is necessary to re-validate the sort columns when they are used, to make sure they are still present, otherwise you can get ORDER BY sql that refers to non-existant columns, which then causes DB errors. --- lib/tablelib.php | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/tablelib.php b/lib/tablelib.php index 6df00292920..c31a1ed65af 100644 --- a/lib/tablelib.php +++ b/lib/tablelib.php @@ -549,6 +549,18 @@ class flexible_table { return array(); } + foreach ($this->sess->sortby as $column => $notused) { + if (isset($this->columns[$column])) { + continue; // This column is OK. + } + if (in_array($column, array('firstname', 'lastname')) && + isset($this->columns['fullname'])) { + continue; // This column is OK. + } + // This column is not OK. + unset($this->sess->sortby[$column]); + } + return $this->sess->sortby; } @@ -573,7 +585,7 @@ class flexible_table { } /** - * @return array - sql where, params array + * @return string sql to add to where statement. */ function get_sql_where() { global $DB; @@ -1304,8 +1316,15 @@ class table_sql extends flexible_table { // Fetch the attempts $sort = $this->get_sql_sort(); - $sort = $sort?" ORDER BY {$sort}":''; - $sql = "SELECT {$this->sql->fields} FROM {$this->sql->from} WHERE {$this->sql->where}{$sort}"; + if ($sort) { + $sort = "ORDER BY $sort"; + } + $sql = "SELECT + {$this->sql->fields} + FROM {$this->sql->from} + WHERE {$this->sql->where} + {$sort}"; + if (!$this->is_downloading()) { $this->rawdata = $DB->get_records_sql($sql, $this->sql->params, $this->get_page_start(), $this->get_page_size()); } else {