diff --git a/user/classes/fields.php b/user/classes/fields.php index 20c92d20fc6..c4154d83308 100644 --- a/user/classes/fields.php +++ b/user/classes/fields.php @@ -377,9 +377,13 @@ class fields { $allowed = false; if ($allowcustom) { require_once($CFG->dirroot . '/user/profile/lib.php'); + + // Ensure the field exists (it may have been deleted since user identity was configured). $field = profile_get_custom_field_data_by_shortname($matches[1], false); - $fieldinstance = profile_get_user_field($field->datatype, $field->id, 0, $field); - $allowed = $fieldinstance->is_visible($context); + if ($field !== null) { + $fieldinstance = profile_get_user_field($field->datatype, $field->id, 0, $field); + $allowed = $fieldinstance->is_visible($context); + } } if (!$allowed) { unset($extra[$key]); diff --git a/user/tests/fields_test.php b/user/tests/fields_test.php index d046ee1bf15..1d7977be335 100644 --- a/user/tests/fields_test.php +++ b/user/tests/fields_test.php @@ -22,6 +22,7 @@ namespace core_user; * @package core * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * @covers \core_user\fields */ class fields_test extends \advanced_testcase { @@ -153,6 +154,27 @@ class fields_test extends \advanced_testcase { fields::get_identity_fields($usercontext, false)); } + /** + * Test getting identity fields, when one of them refers to a non-existing custom profile field + */ + public function test_get_identity_fields_invalid(): void { + $this->resetAfterTest(); + + $this->getDataGenerator()->create_custom_profile_field([ + 'datatype' => 'text', + 'shortname' => 'real', + 'name' => 'I\'m real', + ]); + + // The "fake" profile field does not exist. + set_config('showuseridentity', 'email,profile_field_real,profile_field_fake'); + + $this->assertEquals([ + 'email', + 'profile_field_real', + ], fields::get_identity_fields(null)); + } + /** * Tests the get_required_fields function. *