General developer forum

"require_login" and cron executions

Picture of Alan Zaitchik
"require_login" and cron executions

I have a plugin with a cli cron endpoint that does some backup and restore operations. It's failing on a call to require_login that is getting executed in validate_context(), which gets called from course/externallib.php's duplicate_course (and elsewhere).

I notice that if I call this entry point in the plugin from moodlecron there is not problem. it's just when I schedule it independently as its own cron script that we see this problem.

Any suggestion how to get around this? how do you get a cli cron script to be logged in?



Average of ratings: -
Picture of Iñaki Arenaza
Re: "require_login" and cron executions
Core developersDocumentation writersParticularly helpful MoodlersPlugin developers

Hi Alan,

duplicating a course means having backup and restore capabilities. Those capabilities are tied to role assignments, which in turn are tied (assigned) to users. So the duplicate_course() function is checking which user is executing the action (via require_login()).

When you run your cli cron endpoint from moodlecron, Moodle is setting up some user (probably admin user, but I'm not really sure about this) before executing your endpoint. When you schedule it independently as it own script, nothing is setting up that user and thus require_login() fails.

You can check for this by having a look at the $USER global variable in your cron endpoint. You could use something similar to the following code in your cron endpoint to make it work in both scenarios:

if (empty($USER) || empty($USER->id)) {
    $USER = $DB->get_record('user', array('username'=>'some-user-with-the-right-roles', 'deleted'=>0));

You need to add this piece of code before calling duplicate_course().



Average of ratings: -