+ /**
+ * Validate an acceptable column name for sorting results.
+ *
+ * @param $str
+ *
+ * @return bool
+ */
+ public static function mysqlColumnName($str) {
+ // Check not empty.
+ if (empty($str)) {
+ return FALSE;
+ }
+
+ // Ensure it only contains valid characters (alphanumeric and underscores).
+ //
+ // MySQL permits column names that don't match this (eg containing spaces),
+ // but CiviCRM won't create those ...
+ if (!preg_match('/^\w{1,64}(\.\w{1,64})?$/i', $str)) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ /**
+ * Validate that a string is ASC or DESC.
+ *
+ * Empty string should be treated as invalid and ignored => default = ASC.
+ *
+ * @param $str
+ * @return bool
+ */
+ public static function mysqlOrderByDirection($str) {
+ if (!preg_match('/^(asc|desc)$/i', $str)) {
+ return FALSE;
+ }
+
+ return TRUE;
+ }
+
+ /**
+ * Validate that a string is valid order by clause.
+ *
+ * @param $str
+ * @return bool
+ */
+ public static function mysqlOrderBy($str) {
+ // Making a regex for a comma separated list is quite hard and not readable
+ // at all, so we split and loop over.
+ $parts = explode(',', $str);
+ foreach ($parts as $part) {
+ if (!preg_match('/^((\w{1,64})((\.)(\w{1,64}))?( (asc|desc))?)$/i', trim($part))) {
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+ }
+