Moodle cohort_add_cohort错误

I'm developing a custom Moodle authentification plugin for Moodle 2.7.

When a user is authenticated I want them to be added to a specific cohort. If that cohort does not exist I need it to be created automatically. I use the user_authenticated_hook() function in my authentification plugin to achieve this.

My code for creating the cohort is this

$data = new stdClass();
$data->name = 'Name string';
$data->idnumber = 'ID string';
$data->description = 'Description string';
$cohortId = cohort_add_cohort($data);

I have included cohort/lib.php in the auth.php file and I have declared the global variables $DB, $CFG and $SESSION at the first line of the user_authenticated_hook() function.

The authentification works without the part about cohorts. But with the cohort part in place authentication fails and I am redirected to the login page.

The page title is changed to "Error" but that is the only error message I get.

What Am I doing wrong? I hope somebody will be able to help me create cohorts and add members.

It might be because the global $USER object doesn't exist yet or hasn't been populated.

Do you have debug switched on in your config.php?

$CFG->debug = 32767;
$CFG->debugdisplay = 1;

It might be better to respond to the user_created event. So if a user is created by another method, they will still be added to the cohort. eg:

Create a local plugin eg:

/local/add_cohorts

Create an events.php

/local/add_cohorts/db/events.php

Which has something like this

$handlers = array (
    'user_created' => array (
        'handlerfile'      => '/local/add_cohorts/lib.php',
        'handlerfunction'  => 'local_add_cohorts_user_created',
        'schedule'         => 'instant',
        'internal'         => 1,
    ),
);

Then in /local/add_cohorts/lib.php have

function local_add_cohorts_user_created($user) {
    // Do your cohort processing here and add the user
    // Use $user->id to add to the cohort members
}

Then create a version.php and install the plugin, then the event handler will be registered.

Events api - https://docs.moodle.org/dev/Events_API