How to rebuild context paths

From MoodleDocs


Sometimes, if something has gone wrong in your database, you will get an error like:

PHP Notice:  Context id 113 does not have valid path, please use context_helper::build_all_paths()

or like:

Can't find data record in database table context.
Debug info: SELECT * FROM {context} WHERE id = ?[array (0 => '1030367',)]
Error code: invalidrecord

This page explains how to follow the instruction to "please use context_helper::build_all_paths()".

Before you start

This error should never happen, so the fact that it has may be a symptom of something more serious being wrong. If you are paranoid, you may wish to check your database for corruption before running the repair script below.

On the other hand, sometimes these things happen when a course/category delete fails, or is done incorrectly, so you could just run the task as described below to fix the error:

Step A: Verify the \core\task\context_cleanup_task scheduled task is running, and run it manually, if needed

Go to Site administration -> Server -> Scheduled tasks and look for the Cleanup contexts (\core\task\context_cleanup_task) task. If it has not run recently, run it via the "Run Now" link, or via the CLI with:

php admin/tool/task/cli/schedule_task.php --execute='\core\task\context_cleanup_task' --showdebugging

Once that is done, check if the error has gone away. If it has, you are done! If it has not, please move to Step B

Step B: Edit lib/classes/task/context_cleanup_task.php to fix corrupt context paths

In your favorite editor, open lib/classes/task/context_cleanup_task.php and edit the line that reads

\context_helper::build_all_paths(false); 

and change it to

\context_helper::build_all_paths(true); 

to force the task to rebuild the context paths. Run the \core\task\context_cleanup_task scheduled task again, as you did in Step A. Your errors should now be gone.

You can then change

\context_helper::build_all_paths(true); 

back to

\context_helper::build_all_paths(false); 

so the \core\task\context_cleanup_task scheduled task works as intended