Fixing Custom Plugins Broken by APIs Moodle Has Removed
Every major Moodle release removes functions deprecated several versions earlier, and you usually find out through a fatal error in a scheduled task. What went in 4.3, what 4.4, 5.0 and 5.1 took away, and how to find the same problem in your own plugins first.
Every major Moodle release removes functions that were deprecated several versions earlier, and the usual way you find out is a fatal error in a scheduled task at three in the morning. This guide works through the 4.3 removals in detail, because they are the ones that catch the most plugin code, then covers what 4.4, 5.0 and 5.1 took away, and sets out a repeatable method for finding the same class of problem in your own plugins before an upgrade rather than after.
Why this surfaces late
A deprecation removal rarely breaks a page load. It breaks the code paths nobody looks at: cron tasks, adhoc tasks, web service endpoints, scheduled report generators, event observers.
The failure looks like this in the task log:
Execute scheduled task: Fill user cache (local_yourplugin\task\fill_cache)
... started 03:14:07. Current memory use 12.3MB.
Error: Call to undefined function get_all_user_name_fields()
The site keeps working. Nobody notices for days. Then a report is empty, or a sync has silently not run since the upgrade, and the trail leads back to an upgrade that everyone signed off as clean.
That is the real lesson here, and it is worth internalizing before the specifics: an upgrade that passes a smoke test has not been tested. A deprecation removal breaks the parts a smoke test does not touch, and that is not a coincidence: a smoke test exercises the interface, while the code that quietly calls a removed function is usually running on cron.
What Moodle 4.3 removed
From lib/upgrade.txt, under the 4.3 heading:
* The following previously deprecated methods have been removed and can no longer be used:
- `get_extra_user_fields`
- `get_extra_user_fields_sql`
- `get_user_field_name`
- `get_all_user_name_fields`
- `unzip_file`
- `zip_files`
The first four are the user field functions. They were deprecated in Moodle 3.11, when the \core_user\fields API was introduced to replace them, and removed four major releases later. If your plugin still calls them, it has been emitting deprecation warnings for years in a log nobody reads.
Note the version. This landed in 4.3. A site on 4.2 crosses the boundary on its very next major upgrade, and a jump from 4.1 or 4.2 straight to 4.4 or 4.5 crosses it on the way, so the breakage arrives bundled with everything else.
Later releases continued the pattern with different functions. Moodle 4.4 removed download_as_dataformat and a set of question helpers including question_preview_url and flatten_category_tree. Read the notes for every version you are crossing, not just the one you are landing on.
Replacing the user name field functions
The old pattern looked like this:
$fields = get_all_user_name_fields(true, 'u');
$sql = "SELECT u.id, $fields
FROM {user} u
WHERE u.deleted = 0";
The modern equivalent goes through \core_user\fields. For a plain list of name field names:
$namefields = \core_user\fields::get_name_fields();
// ['firstnamephonetic', 'lastnamephonetic', 'middlename',
// 'alternatename', 'firstname', 'lastname']
For SQL, the API builds the select list, any required joins, and the parameters together:
$userfields = \core_user\fields::for_name()->get_sql('u');
$sql = "SELECT u.id{$userfields->selects}
FROM {user} u
{$userfields->joins}
WHERE u.deleted = 0";
$records = $DB->get_records_sql($sql, $userfields->params);
The get_sql() signature is worth reading properly, because the defaults are not what you want in every case:
public function get_sql(
string $alias = '', // table alias, e.g. 'u'
bool $namedparams = false, // named :params instead of ?
string $prefix = '', // prefix result columns, e.g. 'u_'
string $renameid = '', // rename the id column, e.g. 'userid'
bool $leadingcomma = true // start the select list with a comma
): \stdClass
It returns an object with selects, joins, params, and mappings.
$leadingcomma is the argument that catches people, and the snippet above depends on getting it right. It defaults to true, which is what you want when appending to an existing list, as in SELECT u.id{$userfields->selects}. Pass false only when the field list starts the select. Getting it backwards produces SELECT u.idu.firstnamephonetic, ... and a database error about an unknown column.
The other class members you are likely to need:
\core_user\fields::for_identity($context)replacesget_extra_user_fields()and its SQL variant\core_user\fields::get_display_name($field)replacesget_user_field_name()\core_user\fields::get_sql_fullname()helps you sort and filter on a full name in the database rather than in PHP. It returns[$select, $params], so destructure it and merge those parameters into your own:[$select, $params] = \core_user\fields::get_sql_fullname('u');
The builder methods chain, so a query that needs both a picture and a name is one expression:
$userfields = \core_user\fields::for_userpic()
->with_name()
->excluding('id')
->get_sql('u', false, '', '', false);
For unzip_file() and zip_files(), the replacement is the file packer:
$packer = get_file_packer('application/zip');
$packer->extract_to_pathname($archivepath, $targetdir);
$packer->archive_to_pathname($files, $archivepath);
Finding the rest of them before the upgrade
Fixing the one function that broke is not the job. The job is finding everything in the same class before you upgrade production.
Grep your own code against core’s deprecation lists. Moodle keeps removed and deprecated functions documented per component. Start with the core file and the component files for anything your plugins touch:
UPGRADING.md <- 4.5 and later
lib/upgrade.txt <- up to 4.4
lib/deprecatedlib.php
mod/*/upgrade.txt
admin/tool/*/upgrade.txt
Do not stop at lib/upgrade.txt. From 4.5 it stops being maintained and says so in its own header: the notes moved to UPGRADING.md in the root. A reading list that omits it has a hole at exactly the version you are upgrading to.
Read every version heading between your current release and your target. If you are going from 4.1 to 4.5, that is four sets of notes, and the removals are cumulative.
Turn debugging up on a staging copy and exercise the code. Deprecated functions emit a notice while they still exist. That is your window: on the version before the removal, every call site announces itself.
// config.php on staging only
$CFG->debug = E_ALL;
$CFG->debugdisplay = 1;
Then run the parts of the site that never get clicked:
sudo -u www-data php admin/cli/cron.php
sudo -u www-data php admin/cli/scheduled_task.php --list
sudo -u www-data php admin/cli/scheduled_task.php --execute='\local_yourplugin\task\your_task'
Running each of your own scheduled tasks by hand on the pre-upgrade version, with debugging on, will surface more real problems than any amount of reading.
Search the plugin tree directly. For a known removal list this is fast and complete:
grep -rn --include=*.php \
-e 'get_all_user_name_fields' \
-e 'get_extra_user_fields' \
-e 'get_user_field_name' \
-e 'unzip_file' \
-e 'zip_files' \
local/ blocks/ mod/ theme/ admin/tool/
Those directories hold core plugins as well as your own, so the results will be noisy. Core hits are not what you are looking for: core does not call these functions, and where a name matches it is a private method of core’s own that happens to share it, or a substring of a longer identifier. The two you will see on a 4.5 tree are an unrelated import_zip_files() in the assignment feedback plugin and a private unzip_file() in the language customization tool. Neither is a call to the removed function. That noise is worse than useless: it trains you to skim past hits, and the real ones are in the same list. The reliable way to see only your code is to name your own plugin directories explicitly:
find local/yourplugin blocks/yourblock mod/yourmodule \
-type f -name '*.php' -print0 \
| xargs -0 grep -n \
-e 'get_all_user_name_fields' \
-e 'get_extra_user_fields' \
-e 'get_user_field_name' \
-e 'unzip_file' \
-e 'zip_files'
If your plugins were copied into an otherwise clean Moodle checkout and were never committed, git ls-files --others --exclude-standard will list them for you. That only works while they are untracked, so it is not a general answer: on any site where the plugins are committed alongside core it returns nothing.
While you are in there, add user_picture::fields() to the same sweep. It was deprecated alongside the others in 3.11 and it is not in the 4.3 removal list, so it still works on 4.5 and only emits a developer-level debugging notice. It is a strong candidate for the next removal, and \core_user\fields::for_userpic() already replaces it, so migrating it in the same pass costs almost nothing:
find local/yourplugin blocks/yourblock mod/yourmodule \
-type f -name '*.php' -print0 \
| xargs -0 grep -n 'user_picture::fields'
Making the next one cheap
The reason this bites is that custom scheduled tasks often have no test coverage at all. A task that is never instantiated in a test will never fail in CI, and its first execution is in production.
A minimal execution test per task catches an undefined function on the path it exercises:
<?php
namespace local_yourplugin;
/**
* @covers \local_yourplugin\task\fill_cache
*/
final class fill_cache_task_test extends \advanced_testcase {
public function test_task_executes(): void {
$this->resetAfterTest();
$this->setAdminUser();
$task = new \local_yourplugin\task\fill_cache();
ob_start();
$task->execute();
ob_end_clean();
$this->assertDebuggingNotCalled();
}
}
The assertDebuggingNotCalled() line is the part that earns its keep. It fails the test when the task calls something deprecated, which gives you a CI failure years before the function disappears instead of a production incident on upgrade night.
Be clear about what it does and does not prove. It only sees code that actually ran during the test. A deprecated call on a branch the test never reaches stays invisible, so a single happy-path test is a floor, not a guarantee. If a task has meaningfully different branches, give each one a case.
Run it the usual way:
php vendor/bin/phpunit local/yourplugin/tests/fill_cache_task_test.php
What 5.0 and 5.1 removed
The 4.3 removals are the ones that break quietly. The releases after 4.5 remove larger things that break loudly, and they are worth knowing about before you plan an upgrade path rather than after.
Moodle 5.0 is the disruptive one for plugin authors:
- The Atto editor and all its standard subplugins are gone from core. On a stock 5.0 site an
atto_*plugin has no host editor to plug into. Atto can still be installed separately, and subplugins for it are still being published, so this is a question of what the site actually has rather than an automatic dead end. - Support for
subplugins.phphas been removed. If your plugin declares subplugins that way, it needs converting tosubplugins.json. - Oracle support has been removed. Any Oracle-specific SQL you carry is now dead weight, and any site still on Oracle cannot go to 5.0.
- Several plugins left core, including
auth_cas,auth_mnet,block_mnet_hosts,mnetservice_enrol,portfolio_mahara,mlbackend_php, and thesurveyandchatactivity modules. Code that assumes any of these is present will not find it. - Smaller API removals:
core_renderer::activity_information(),task_base::is_blocking()andset_blocking(),action_menu::set_alignment(),set_constraint()anddo_not_enhance(), thecore_output_load_fontawesome_icon_mapweb service, and the OpenSSL fallback in\core\encryption.
A note on what “removed” means in the newer notes, because it changes what you will see in the log. Some of these are true deletions and produce Call to undefined method. Others reach final deprecation: the method is still in the file, but its whole body is a deprecation call, and a final deprecation throws coding_exception rather than warning. For a caller the consequence is identical, it is an immediate break; only the error text differs. Do not read “the method still exists” as “the code still works”.
Moodle 5.1 has far fewer API removals than 5.0, but do not read that as the quiet release. It carries the structural change:
- Most of the web-facing codebase, including every plugin, moves into
public/. Not quite everything:admin/and a stublib/stay at the top of the tree. The document root has to move, and any deployment script, vhost, backup job or CI configuration carrying a hard-coded path into the old tree needs reviewing. In our experience this can be the largest single piece of work in the upgrade, well ahead of any individual API change.
Two API items also catch code that survived 4.3:
core_useragent::get_device_type_theme()andget_device_type_cfg_var_name()reach final deprecation, so calling either throws. They were deprecated in 4.3, in the same release that removed the user field functions, so a site that crossed that boundary got both the removal and this warning in one upgrade. The symbols themselves are not deleted until 5.2.- A set of quiz helpers goes the same way, including
quiz_has_question_use()andquiz_update_sumgrades(). Several files under the quiz report directory are genuine deletions, as isblock_section_links.
The method in this guide does not change for any of it. Read the notes for every version you cross, grep your own plugin directories, and run your scheduled tasks with debugging on before the upgrade rather than after. What changes is where you read: from 4.5 the notes live in UPGRADING.md rather than lib/upgrade.txt, and the 5.0 and 5.1 entries are in that file.
Supporting more than one Moodle version
If your plugin has to run on releases either side of a removal, there are three approaches and the right one depends on how wide the range is.
Drop the old versions. Write against the new API and set $plugin->requires in version.php to the first release that has it. Cleanest option when the range is narrow, and it states the constraint explicitly instead of shipping something that half works.
Wrap the difference once. Put the version-dependent call behind a single helper in your own code, so the rest of the plugin only ever sees your API. One small shim in one place is easy to read and easy to delete later. This is usually the right answer for one or two functions across two releases. It goes wrong when the checks spread through the codebase, so keep them contained.
Branch per Moodle release. Worth it when the differences are structural rather than a couple of function names, or when the version range is wide. Each branch stays readable, at the cost of applying every fix more than once.
Whichever you choose, put the supported range in the plugin README. The commonest cause of a broken client site is a plugin installed on a version its author never tested.
Solin develops and maintains custom Moodle and Totara plugins across version upgrades.
Contact us