Files
formations-app/ops/provision-ws.php
T
2026-06-10 21:05:09 +02:00

56 lines
2.1 KiB
PHP

<?php
// Idempotent provisioning of a read-only web-service user for the app BFF.
// Run: docker cp ops/provision-ws.php moodle:/tmp/ &&
// docker exec -e WSREADER_PASSWORD=... moodle php /tmp/provision-ws.php
define('CLI_SCRIPT', true);
require('/var/www/html/config.php');
require_once($CFG->dirroot.'/user/lib.php');
require_once($CFG->dirroot.'/lib/enrollib.php');
// 1) Enable web services + REST + built-in mobile service
// (mobile service already includes core_course_get_contents & file serving)
set_config('enablewebservices', 1);
set_config('enablemobilewebservice', 1);
$protocols = (string)get_config('core', 'webserviceprotocols');
if (strpos($protocols, 'rest') === false) {
set_config('webserviceprotocols', trim($protocols === '' ? 'rest' : $protocols . ',rest', ','));
}
// 2) Service user
$username = 'wsreader';
$password = getenv('WSREADER_PASSWORD');
if (!$password) { fwrite(STDERR, "WSREADER_PASSWORD required\n"); exit(1); }
$user = core_user::get_user_by_username($username);
if (!$user) {
$u = new stdClass();
$u->username = $username;
$u->password = $password;
$u->firstname = 'WS';
$u->lastname = 'Reader';
$u->email = 'wsreader@saillant.cc';
$u->confirmed = 1;
$u->mnethostid = $CFG->mnet_localhost_id;
$uid = user_create_user($u, true, false);
$user = core_user::get_user($uid);
echo "user created: {$user->id}\n";
} else {
echo "user exists: {$user->id}\n";
}
// 3) Enrol as student in every real course (id > 1) so get_contents works
$student = $DB->get_record('role', ['shortname' => 'student'], '*', MUST_EXIST);
$manual = enrol_get_plugin('manual');
foreach ($DB->get_records_select('course', 'id > 1') as $course) {
$minstance = null;
foreach (enrol_get_instances($course->id, false) as $i) {
if ($i->enrol === 'manual') { $minstance = $i; break; }
}
if (!$minstance) {
$id = $manual->add_instance($course);
$minstance = $DB->get_record('enrol', ['id' => $id], '*', MUST_EXIST);
}
$manual->enrol_user($minstance, $user->id, $student->id);
echo "enrolled: {$course->shortname}\n";
}
echo "OK\n";