ÿØÿà JFIF    ÿÛ „  ( %!1"%)+...383-7(-.+  -%%--------+------------/----------------------------ÿÀ  ¶" ÿÄ     ÿÄ @    !1AQaq‘¡"±ÁÑð2’BRráS‚ñ3b¢CT²Ò #cÿÄ    ÿÄ '   1!AQ2a"‘±#ÿÚ   ? ò(/p‘—–¢·,M|¯G»R£üešT. ôŸEoCFñ‡ 4ÔkåóxR|µÁ¨ÓDà!Ç´µ˜‡p ÍQ‹§!þž^õWsŒy  åÁ§$á«%ºq˜™JyyË0y«^Ϗ -3ÃÏËÈ£Æ\P’ä„s&•‹Üs üô'àWt¹pñCp$bÚF`·7.^)¾!)ÒÙ˜–ÅÏš^h¾ø³·ìe±ŒaeÖ—Í,e=B}Jéߦ$$½—šÙÜCC¯¶è8β–Åkèwx LÉngT±æ¹£Ócœ¿Í/©Éÿ ‰ÚCÒ­mq;Tt¶–}0"zÖPcd1š­¤tˆ„ÐÓâqú[™öUCŠ2޿د­É(¸ßúçšmW,Ò ºf‹Ån™ÄLêÁ8üÁkÁ€L¥ÍuJ1œôrÂSŒÓöt!7EUíïb)AËi¬â-ÙHk8òÁiXYwÅ)O^"ÇØriÛô{»wRUKÙÏÚlÓ¬€‚’שT ] ªb—ÊîKC^×M“xùäñz¬zJ× {4[¹M'IÆeH1LCWÕ]œûº WDæà°OÅ‚¹c²ÞuA–rL`HšpCez‡V’— Ž‚Ë„–ñ­'µR0ÕÖ=À:±G»C\nÆÉ5*¢ †3šhQ4ýÒi$Õ1"Ü]¢p-q3zcQ$ªö¨¥æf›‘»´ÝÚHá„e²JÇ–iÊ:·à¬Øc5Åk»Laª*wi [0Ówk ¦a¦0Õ²ÅÅ‚T¸’³q:Æ<¹ú Ò˜Æ}2VE•Ѐp¡Ô3Úº …h³^LJºçì¥Ánó|˜ÖˆÎˆ+« ¦dø‘Mº–d\ªDðÛ„Ì×LÝ——Ð9Ç|•FèçVm™¨€™3õS–9Äå¢<̉Ìm¢±`·º˜&Z²ž Ë®D«¶»6™‰©­HÈ Àá«h­i³04æ’hxœi3ï¨(ÓL·†‹¶ËpŒ ƒÜÒ? :õdsÀ –3æÓ·Üjâ¬9—]8n¼&]I F£¼…ì–—Œ0v°LǐÅfÛ2TÖ’aµ˜N@ÖBSÏ^à´4-±°b×nÈÈœÆD=KdŒø…ÄÈK,›ÖR§fjü$^ÔÎ!„6^ s:Üun\ôkCÞò÷<—Lúl Í›G¹ÀPá¼Nc¡šÒ…ÙWͳœ±vÊáЄ×9‹P‰cEØ‘™›µŸP<×g1 º©Ø¬wiÁ^l5× I/';Ë+´Z‡ÓÄFÕp[Èð’ HÄ ó 9¬Dl4“é±Ï”V=^Hð;žLädÉa‚°Ë,#/Ž~²BÔÛ QãñQtIeórVB,ÏÂf‹4#Μc‹É3ZIÖ Œ¢¥·üxa‡Ãçè„jŠ[5 Ä!U?,3žÎ×…ðdÓ÷háŠA‰ìÄ4÷ÃÜZÃE{‰®+W\ZÍE[‰»µk»MÝ­`¢©†˜ÃV‹-f¢¡†¢a«eŠ%«Y¨©q%jâd,Ôq`) ¤¦…šˆ ¦E>0Ùb²t–Ÿ  ÷jsςҒKÈcø(é›;k(’#ôŒQ ™C> õ³M9óºÆµ¤çâ;uÀ)5>RÔ¸fÓ~Ȧ—’-$fe«"FâUˆÊwµPÏu w+"åÉó¨6s™Û9(À¨ù©hE°½†n`m~“@©›p!Vkhµ Á1šbEqqÊ@ºèl›2 –Yã%‘‚hÛ{a¶‡ÅÞM²¬çL34®Çl]®‹ŽØŒm'RÜe35æöˆ­Á­ cP9šeÁköo´L³Ì=p8]”‡B¶,šº|ɏdzXˆØk*ÇÚ{#ñ‰pã(€¶‡9ý'šÜ³½¯kƒ†Â’ëSOƒ•Å®H6+a¢µˆ‹Y¨b˜b+XˆÖ!°u!¢"µˆˆn2ˆ Å0Ä`Å Ô®c(ÓÜGº•Ä»Œ âWî%q.áÐÄ÷î%umÍ£+ÜQ,Vn¦-GphU¸¢X­&,Gt ·K¢ÅÅ·¥RÄÊÉbKn N­R2g$VµÕó Qr#–ÓZUÏð0ÎtÙÀœz ëöo“Îk¯n„T°"SÞ+³/…€½"ižãO%Í%&Δâ‘ËØ´IˆÓ°Ë‰ÞM3.™yçÁzit›`4C`k¢¼á!álÄï sÂ[×!¤l¾æo"ƒIÔ'@ªu)3›ô®“@Z à¾] üœ'‡4¸PÞkÁ-qÄH‰ÓÍBd´ÿ —¹°ÄA&ÊUC„öz‚‚RæŠtf¬>˜ÑidšEçÑL÷áý¡V±h§­c¿¥¨ƒ@g¼…Ýö^ÞËc.ž„æ“I[ ª+·zÐÒÚ,½Ð»¶€C›7jk$๖€Ž¾ÅÙpp¶ÍþéΤ ½ØÎŒq ñpæžÅ¥#Øâ49ÃÂK^MYV“,¶Éz_òæ:…;Õ«¦I3âJ£¤û5$7Èxün\â]Êe¯(Ÿ&Ž‹¶2<6Ćf× æ¢ƱqWı[(ÙÂŽç‚T7¨@ÈÉÍß‚ïÙ"&3TYlGށ†)†#5ŠA©^T2ÆÁ†)©†©†¤yGXÁ†©"†)©¼ÅV WS†#©]R–r‹q5ÕbâWþBh¯u+ªÅÄ×ü„nÑ^êkªÁj‰jeœWˆÕÕ`µDµ2Ì+Ä µDµµ5Ô{¤Þ0RF’H÷AÛ<ÊÁ§ ƈæ0Ñ£ê4 öÚµ[¬/1²€â<-¬šö²r×0o×w ´xÐÒË„ g01¬„åEM蛇Ã\6µE›‘fÙO k÷CºnÓ1`iîÒ² áÂ!ÑLÄÿ ³¬\õ*:M=Ç»c‹2[‰ØsÕLò\ŒK L^™üÄN\¶#» Ç\……ßïIœÉ$¸ÎñÍ®ÔHÇ Ûí/´>Li”„†g^$ 7NÍÑÑ2M2ªNg=k½Ð}Ÿl6‡ —JWˆ”ÞéT·+µ¦üÂFè¢Vs6ýÆ4»2+2IÝ9ô9®ÇGÙÇ1+Ä8;*Õ§ž½D*îÑWÚçá3Ma¤·ˆ¥t}š²Ü…Q+Æüµ8HíS”üxGéÁˆ¦Ël„éÈ 5 µÄƒ6äÜ(kIš¯S†fÖ&¸®×v|Äyˆ*禌Éù@7-®Ä[]ÎÖ¿ê`º…=:…žJVnݳvðÖKE¼‚ »mà ÷f®:Ë ™–4rð¡4` ܹçž~‹C=œ…¾Ïj|VDtK.ƒ"9 Ï ­–éXá³6WÒïIL-Ї Ç PK \^MMdb/install.phpnu[. /** * Database enrolment plugin installation. * * @package enrol_database * @copyright 2010 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); function xmldb_enrol_database_install() { global $CFG, $DB; } PK \1 db/tasks.phpnu[. /** * Task definition for enrol_database. * @package enrol_database * @copyright 2018 Daniel Neis Araujo * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $tasks = array( array( 'classname' => '\enrol_database\task\sync_enrolments', 'blocking' => 0, 'minute' => 'R', 'hour' => 'R', 'day' => '*', 'month' => '*', 'dayofweek' => '*', 'disabled' => 1 ) ); PK \l db/access.phpnu[. /** * Capabilities for database enrolment plugin. * * @package enrol_database * @copyright 2010 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $capabilities = array( /* This is used only when sync suspends users instead of full unenrolment. */ 'enrol/database:unenrol' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, ) ), 'enrol/database:config' => array( 'captype' => 'write', 'contextlevel' => CONTEXT_COURSE, 'archetypes' => array( 'manager' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), ); PK \WOOdb/upgrade.phpnu[. /** * Database enrolment plugin upgrade. * * @package enrol_database * @copyright 2011 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ function xmldb_enrol_database_upgrade($oldversion) { global $DB; // Automatically generated Moodle v4.2.0 release upgrade line. // Put any upgrade step following this. // Automatically generated Moodle v4.3.0 release upgrade line. // Put any upgrade step following this. // Automatically generated Moodle v4.4.0 release upgrade line. // Put any upgrade step following this. // Automatically generated Moodle v4.5.0 release upgrade line. // Put any upgrade step following this. // Automatically generated Moodle v5.0.0 release upgrade line. // Put any upgrade step following this. if ($oldversion < 2025041402) { // Remove duplicated enrolment records, keeping only the earliest records. $transaction = $DB->start_delegated_transaction(); $courses = $DB->get_records_sql( " SELECT courseid FROM {enrol} WHERE enrol = 'database' GROUP BY courseid HAVING COUNT(*) > 1" ); foreach ($courses as $course) { $instances = $DB->get_records('enrol', ['enrol' => 'database', 'courseid' => $course->courseid], 'id ASC'); $idtokeep = array_key_first($instances); $idstodelete = array_slice(array_keys($instances), 1); [$insql, $inparams] = $DB->get_in_or_equal($idstodelete, SQL_PARAMS_NAMED); // Migrate enrolments where possible. // First, get the user enrolments that can be migrated. // Only select the earliest (MIN id) user_enrolments per user to avoid // duplicate key violations when a user has multiple enrolments across // duplicate database enrol instances. $migrateusers = $DB->get_records_sql( "SELECT MIN(ue.id) AS id FROM {user_enrolments} ue WHERE ue.enrolid $insql AND NOT EXISTS ( SELECT 1 FROM {user_enrolments} ue2 WHERE ue2.userid = ue.userid AND ue2.enrolid = :idtokeep) GROUP BY ue.userid", array_merge($inparams, ['idtokeep' => $idtokeep]), ); // Then update them if any exist. if (!empty($migrateusers)) { $migrateids = array_keys($migrateusers); [$migratein, $migrateparams] = $DB->get_in_or_equal($migrateids, SQL_PARAMS_NAMED); $DB->execute( "UPDATE {user_enrolments} SET enrolid = :idtokeep WHERE id $migratein", array_merge($migrateparams, ['idtokeep' => $idtokeep]), ); } $DB->delete_records_select('user_enrolments', "enrolid $insql", $inparams); // Migrate role assignments. $DB->execute( " UPDATE {role_assignments} SET itemid = :idtokeep WHERE component = :component AND itemid $insql", array_merge($inparams, ['component' => 'enrol_database', 'idtokeep' => $idtokeep]) ); $DB->delete_records_select('role_assignments', "itemid $insql", $inparams); $DB->delete_records_list('enrol', 'id', $idstodelete); } $transaction->allow_commit(); upgrade_plugin_savepoint(true, 2025041402, 'enrol', 'database'); } return true; } PK \" 4lang/en/enrol_database.phpnu[. /** * Strings for component 'enrol_database', language 'en'. * * @package enrol_database * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['database:config'] = 'Configure database enrol instances'; $string['database:unenrol'] = 'Unenrol suspended users'; $string['dbencoding'] = 'Database encoding'; $string['dbhost'] = 'Database host'; $string['dbhost_desc'] = 'Type database server IP address or host name. Use a system DSN name if using ODBC. Use a PDO DSN if using PDO.'; $string['dbname'] = 'Database name'; $string['dbname_desc'] = 'Leave empty if using a DSN name in database host.'; $string['dbpass'] = 'Database password'; $string['dbsetupsql'] = 'Database setup command'; $string['dbsetupsql_desc'] = 'SQL command for special database setup, often used to setup communication encoding - example for MySQL and PostgreSQL: SET NAMES \'utf8\''; $string['dbsybasequoting'] = 'Use sybase quotes'; $string['dbsybasequoting_desc'] = 'Sybase style single quote escaping - needed for MS SQL and some other databases. Do not use for MySQL!'; $string['dbtype'] = 'Database driver'; $string['dbtype_desc'] = 'ADOdb database driver name, type of the external database engine.'; $string['dbuser'] = 'Database user'; $string['debugdb'] = 'Debug ADOdb'; $string['debugdb_desc'] = 'Debug ADOdb connection to external database - use when getting empty page during login. Not suitable for production sites!'; $string['defaultcategory'] = 'Default new course category'; $string['defaultcategory_desc'] = 'The default category for auto-created courses. Used when no new category id specified or not found.'; $string['defaultrole'] = 'Default role'; $string['defaultrole_desc'] = 'The role that will be assigned by default if no other role is specified in external table.'; $string['ignorehiddencourses'] = 'Ignore hidden courses'; $string['ignorehiddencourses_desc'] = 'If enabled users will not be enrolled on courses that are set to be unavailable to students.'; $string['localcategoryfield'] = 'Local category field'; $string['localcoursefield'] = 'Local course field'; $string['localrolefield'] = 'Local role field'; $string['localuserfield'] = 'Local user field'; $string['newcourseenddate'] = 'New course end date field'; $string['newcourseenddate_desc'] = 'Specify a date in the format yyyy-mm-dd or Unix time, or leave blank for the course end date to be calculated from the configured course duration.'; $string['newcoursetable'] = 'Remote new courses table'; $string['newcoursetable_desc'] = 'Specify of the name of the table that contains list of courses that should be created automatically. Empty means no courses are created.'; $string['newcoursecategory'] = 'New course category field'; $string['newcoursefullname'] = 'New course full name field'; $string['newcourseidnumber'] = 'New course ID number field'; $string['newcoursestartdate'] = 'New course start date field'; $string['newcoursestartdate_desc'] = 'Specify a date in the format yyyy-mm-dd or Unix time, or leave blank for the course start date to be set to the current date.'; $string['newcourseshortname'] = 'New course short name field'; $string['pluginname'] = 'External database'; $string['pluginname_desc'] = 'You can use an external database (of nearly any kind) to control your enrolments. It is assumed your external database contains at least a field containing a course ID, and a field containing a user ID. These are compared against fields that you choose in the local course and user tables.'; $string['remotecoursefield'] = 'Remote course field'; $string['remotecoursefield_desc'] = 'The name of the field in the remote table that we are using to match entries in the course table.'; $string['remoteenroltable'] = 'Remote user enrolment table'; $string['remoteenroltable_desc'] = 'Specify the name of the table that contains list of user enrolments. Empty means no user enrolment sync.'; $string['remoteotheruserfield'] = 'Remote Other User field'; $string['remoteotheruserfield_desc'] = 'The name of the field in the remote table that we are using to flag "Other User" role assignments.'; $string['remoterolefield'] = 'Remote role field'; $string['remoterolefield_desc'] = 'The name of the field in the remote table that we are using to match entries in the roles table.'; $string['remoteuserfield'] = 'Remote user field'; $string['settingsheaderdb'] = 'External database connection'; $string['settingsheaderlocal'] = 'Local field mapping'; $string['settingsheaderremote'] = 'Remote enrolment sync'; $string['settingsheadernewcourses'] = 'Creation of new courses'; $string['syncenrolmentstask'] = 'Synchronise external database enrolments task'; $string['remoteuserfield_desc'] = 'The name of the field in the remote table that we are using to match entries in the user table.'; $string['templatecourse'] = 'New course template'; $string['templatecourse_desc'] = 'Optional: auto-created courses can copy their settings from a template course. Type here the shortname of the template course.'; $string['privacy:metadata'] = 'The External database enrolment plugin does not store any personal data.'; PK \Ҙ''lib.phpnu[. /** * Database enrolment plugin. * * This plugin synchronises enrolment and roles with external database table. * * @package enrol_database * @copyright 2010 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); /** * Database enrolment plugin implementation. * @author Petr Skoda - based on code by Martin Dougiamas, Martin Langhoff and others * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class enrol_database_plugin extends enrol_plugin { /** * Is it possible to delete enrol instance via standard UI? * * @param stdClass $instance * @return bool */ public function can_delete_instance($instance) { $context = context_course::instance($instance->courseid); if (!has_capability('enrol/database:config', $context)) { return false; } if (!enrol_is_enabled('database')) { return true; } if (!$this->get_config('dbtype') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) { return true; } //TODO: connect to external system and make sure no users are to be enrolled in this course return false; } /** * Is it possible to hide/show enrol instance via standard UI? * * @param stdClass $instance * @return bool */ public function can_hide_show_instance($instance) { $context = context_course::instance($instance->courseid); return has_capability('enrol/database:config', $context); } /** * Does this plugin allow manual unenrolment of a specific user? * Yes, but only if user suspended... * * @param stdClass $instance course enrol instance * @param stdClass $ue record from user_enrolments table * * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment */ public function allow_unenrol_user(stdClass $instance, stdClass $ue) { if ($ue->status == ENROL_USER_SUSPENDED) { return true; } return false; } /** * Forces synchronisation of user enrolments with external database, * does not create new courses. * * @param stdClass $user user record * @return void */ public function sync_user_enrolments($user) { global $CFG, $DB; // We do not create courses here intentionally because it requires full sync and is slow. if (!$this->get_config('dbtype') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) { return; } $table = $this->get_config('remoteenroltable'); $coursefield = trim($this->get_config('remotecoursefield')); $userfield = trim($this->get_config('remoteuserfield')); $rolefield = trim($this->get_config('remoterolefield')); $otheruserfield = trim($this->get_config('remoteotheruserfield')); // Lowercased versions - necessary because we normalise the resultset with array_change_key_case(). $coursefield_l = strtolower($coursefield); $userfield_l = strtolower($userfield); $rolefield_l = strtolower($rolefield); $otheruserfieldlower = strtolower($otheruserfield); $localrolefield = $this->get_config('localrolefield'); $localuserfield = $this->get_config('localuserfield'); $localcoursefield = $this->get_config('localcoursefield'); $unenrolaction = $this->get_config('unenrolaction'); $defaultrole = $this->get_config('defaultrole'); $ignorehidden = $this->get_config('ignorehiddencourses'); if (!is_object($user) or !property_exists($user, 'id')) { throw new coding_exception('Invalid $user parameter in sync_user_enrolments()'); } if (!property_exists($user, $localuserfield)) { debugging('Invalid $user parameter in sync_user_enrolments(), missing '.$localuserfield); $user = $DB->get_record('user', array('id'=>$user->id)); } // Create roles mapping. $allroles = get_all_roles(); if (!isset($allroles[$defaultrole])) { $defaultrole = 0; } $roles = array(); foreach ($allroles as $role) { $roles[$role->$localrolefield] = $role->id; } $roleassigns = array(); $enrols = array(); $instances = array(); if (!$extdb = $this->db_init()) { // Can not connect to database, sorry. return; } // Read remote enrols and create instances. $sql = $this->db_get_sql($table, array($userfield=>$user->$localuserfield), array(), false); if ($rs = $extdb->Execute($sql)) { if (!$rs->EOF) { while ($fields = $rs->FetchRow()) { $fields = array_change_key_case($fields, CASE_LOWER); $fields = $this->db_decode($fields); if (empty($fields[$coursefield_l])) { // Missing course info. continue; } if (!$course = $DB->get_record('course', array($localcoursefield=>$fields[$coursefield_l]), 'id,visible')) { continue; } if (!$course->visible and $ignorehidden) { continue; } if (empty($fields[$rolefield_l]) or !isset($roles[$fields[$rolefield_l]])) { if (!$defaultrole) { // Role is mandatory. continue; } $roleid = $defaultrole; } else { $roleid = $roles[$fields[$rolefield_l]]; } $roleassigns[$course->id][$roleid] = $roleid; if (empty($fields[$otheruserfieldlower])) { $enrols[$course->id][$roleid] = $roleid; } if ($instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>'database'), '*', IGNORE_MULTIPLE)) { $instances[$course->id] = $instance; continue; } $timeout = 5; $locktype = 'enrol_database_user_enrolments'; $resource = 'course:' . $course->id; $lockfactory = \core\lock\lock_config::get_lock_factory($locktype); if ($lock = $lockfactory->get_lock($resource, $timeout)) { try { $instance = $DB->get_record('enrol', ['enrol' => 'database', 'courseid' => $course->id]); if (!$instance) { $enrolid = $this->add_instance($course); $instance = $DB->get_record('enrol', ['id' => $enrolid]); } } finally { $lock->release(); } } else { // Attempt to reuse an existing record added by another process during race condition. if ($instance = $DB->get_record('enrol', ['enrol' => 'database', 'courseid' => $course->id])) { $instances[$course->id] = $instance; continue; } else { // Give up. throw new moodle_exception( 'locktimeout', 'enrol_database', '', null, 'Could not create database enrolment instance for course ' . $course->id ); } } $instances[$course->id] = $instance; } } $rs->Close(); $extdb->Close(); } else { // Bad luck, something is wrong with the db connection. $extdb->Close(); return; } // Enrol user into courses and sync roles. foreach ($roleassigns as $courseid => $roles) { if (!isset($instances[$courseid])) { // Ignored. continue; } $instance = $instances[$courseid]; if (isset($enrols[$courseid])) { if ($e = $DB->get_record('user_enrolments', array('userid' => $user->id, 'enrolid' => $instance->id))) { // Reenable enrolment when previously disable enrolment refreshed. if ($e->status == ENROL_USER_SUSPENDED) { $this->update_user_enrol($instance, $user->id, ENROL_USER_ACTIVE); } } else { $roleid = reset($enrols[$courseid]); $this->enrol_user($instance, $user->id, $roleid, 0, 0, ENROL_USER_ACTIVE); } } if (!$context = context_course::instance($instance->courseid, IGNORE_MISSING)) { // Weird. continue; } $current = $DB->get_records('role_assignments', array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_database', 'itemid'=>$instance->id), '', 'id, roleid'); $existing = array(); foreach ($current as $r) { if (isset($roles[$r->roleid])) { $existing[$r->roleid] = $r->roleid; } else { role_unassign($r->roleid, $user->id, $context->id, 'enrol_database', $instance->id); } } foreach ($roles as $rid) { if (!isset($existing[$rid])) { role_assign($rid, $user->id, $context->id, 'enrol_database', $instance->id); } } } // Unenrol as necessary. $sql = "SELECT e.*, c.visible AS cvisible, ue.status AS ustatus FROM {enrol} e JOIN {course} c ON c.id = e.courseid JOIN {role_assignments} ra ON ra.itemid = e.id LEFT JOIN {user_enrolments} ue ON ue.enrolid = e.id AND ue.userid = ra.userid WHERE ra.userid = :userid AND e.enrol = 'database'"; $rs = $DB->get_recordset_sql($sql, array('userid' => $user->id)); foreach ($rs as $instance) { if (!$instance->cvisible and $ignorehidden) { continue; } if (!$context = context_course::instance($instance->courseid, IGNORE_MISSING)) { // Very weird. continue; } if (!empty($enrols[$instance->courseid])) { // We want this user enrolled. continue; } // Deal with enrolments removed from external table if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) { $this->unenrol_user($instance, $user->id); } else if ($unenrolaction == ENROL_EXT_REMOVED_KEEP) { // Keep - only adding enrolments. } else if ($unenrolaction == ENROL_EXT_REMOVED_SUSPEND or $unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) { // Suspend users. if ($instance->ustatus != ENROL_USER_SUSPENDED) { $this->update_user_enrol($instance, $user->id, ENROL_USER_SUSPENDED); } if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) { if (!empty($roleassigns[$instance->courseid])) { // We want this "other user" to keep their roles. continue; } role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_database', 'itemid'=>$instance->id)); } } } $rs->close(); } /** * Forces synchronisation of all enrolments with external database. * * @param progress_trace $trace * @param null|int $onecourse limit sync to one course only (used primarily in restore) * @return int 0 means success, 1 db connect failure, 2 db read failure */ public function sync_enrolments(progress_trace $trace, $onecourse = null) { global $CFG, $DB; // We do not create courses here intentionally because it requires full sync and is slow. if (!$this->get_config('dbtype') or !$this->get_config('remoteenroltable') or !$this->get_config('remotecoursefield') or !$this->get_config('remoteuserfield')) { $trace->output('User enrolment synchronisation skipped.'); $trace->finished(); return 0; } $trace->output('Starting user enrolment synchronisation...'); if (!$extdb = $this->db_init()) { $trace->output('Error while communicating with external enrolment database'); $trace->finished(); return 1; } // We may need a lot of memory here. core_php_time_limit::raise(); raise_memory_limit(MEMORY_HUGE); $table = $this->get_config('remoteenroltable'); $coursefield = trim($this->get_config('remotecoursefield')); $userfield = trim($this->get_config('remoteuserfield')); $rolefield = trim($this->get_config('remoterolefield')); $otheruserfield = trim($this->get_config('remoteotheruserfield')); // Lowercased versions - necessary because we normalise the resultset with array_change_key_case(). $coursefield_l = strtolower($coursefield); $userfield_l = strtolower($userfield); $rolefield_l = strtolower($rolefield); $otheruserfieldlower = strtolower($otheruserfield); $localrolefield = $this->get_config('localrolefield'); $localuserfield = $this->get_config('localuserfield'); $localcoursefield = $this->get_config('localcoursefield'); $unenrolaction = $this->get_config('unenrolaction'); $defaultrole = $this->get_config('defaultrole'); // Create roles mapping. $allroles = get_all_roles(); if (!isset($allroles[$defaultrole])) { $defaultrole = 0; } $roles = array(); foreach ($allroles as $role) { $roles[$role->$localrolefield] = $role->id; } if ($onecourse) { $sql = "SELECT c.id, c.visible, c.$localcoursefield AS mapping, c.shortname, e.id AS enrolid FROM {course} c LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database') WHERE c.id = :id"; if (!$course = $DB->get_record_sql($sql, array('id'=>$onecourse))) { // Course does not exist, nothing to sync. return 0; } if (empty($course->mapping)) { // We can not map to this course, sorry. return 0; } if (empty($course->enrolid)) { $course->enrolid = $this->add_instance($course); } $existing = array($course->mapping=>$course); // Feel free to unenrol everybody, no safety tricks here. $preventfullunenrol = false; // Course being restored are always hidden, we have to ignore the setting here. $ignorehidden = false; } else { // Get a list of courses to be synced that are in external table. $externalcourses = array(); $sql = $this->db_get_sql($table, array(), array($coursefield), true); if ($rs = $extdb->Execute($sql)) { if (!$rs->EOF) { while ($mapping = $rs->FetchRow()) { $mapping = reset($mapping); $mapping = $this->db_decode($mapping); if (empty($mapping)) { // invalid mapping continue; } $externalcourses[$mapping] = true; } } $rs->Close(); } else { $trace->output('Error reading data from the external enrolment table'); $extdb->Close(); return 2; } $preventfullunenrol = empty($externalcourses); if ($preventfullunenrol and $unenrolaction == ENROL_EXT_REMOVED_UNENROL) { $trace->output('Preventing unenrolment of all current users, because it might result in major data loss, there has to be at least one record in external enrol table, sorry.', 1); } // First find all existing courses with enrol instance. $existing = array(); $sql = "SELECT c.id, c.visible, c.$localcoursefield AS mapping, e.id AS enrolid, c.shortname FROM {course} c JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database')"; $rs = $DB->get_recordset_sql($sql); // Watch out for idnumber duplicates. foreach ($rs as $course) { if (empty($course->mapping)) { continue; } $existing[$course->mapping] = $course; unset($externalcourses[$course->mapping]); } $rs->close(); // Add necessary enrol instances that are not present yet. $params = array(); $localnotempty = ""; if ($localcoursefield !== 'id') { $localnotempty = "AND c.$localcoursefield <> :lcfe"; $params['lcfe'] = ''; } $sql = "SELECT c.id, c.visible, c.$localcoursefield AS mapping, c.shortname FROM {course} c LEFT JOIN {enrol} e ON (e.courseid = c.id AND e.enrol = 'database') WHERE e.id IS NULL $localnotempty"; $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $course) { if (empty($course->mapping)) { continue; } if (!isset($externalcourses[$course->mapping])) { // Course not synced or duplicate. continue; } $course->enrolid = $this->add_instance($course); $existing[$course->mapping] = $course; unset($externalcourses[$course->mapping]); } $rs->close(); // Print list of missing courses. if ($externalcourses) { $list = implode(', ', array_keys($externalcourses)); $trace->output("error: following courses do not exist - $list", 1); unset($list); } // Free memory. unset($externalcourses); $ignorehidden = $this->get_config('ignorehiddencourses'); } // Sync user enrolments. $sqlfields = array($userfield); if ($rolefield) { $sqlfields[] = $rolefield; } if ($otheruserfield) { $sqlfields[] = $otheruserfield; } foreach ($existing as $course) { if ($ignorehidden and !$course->visible) { continue; } if (!$instance = $DB->get_record('enrol', array('id'=>$course->enrolid))) { continue; // Weird! } $context = context_course::instance($course->id); // Get current list of enrolled users with their roles. $currentroles = array(); $currentenrols = array(); $currentstatus = array(); $usermapping = array(); $sql = "SELECT u.$localuserfield AS mapping, u.id AS userid, ue.status, ra.roleid FROM {user} u JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.component = 'enrol_database' AND ra.itemid = :enrolid) LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = ra.itemid) WHERE u.deleted = 0"; $params = array('enrolid'=>$instance->id); if ($localuserfield === 'username') { $sql .= " AND u.mnethostid = :mnethostid"; $params['mnethostid'] = $CFG->mnet_localhost_id; } $rs = $DB->get_recordset_sql($sql, $params); foreach ($rs as $ue) { $currentroles[$ue->userid][$ue->roleid] = $ue->roleid; $usermapping[$ue->mapping] = $ue->userid; if (isset($ue->status)) { $currentenrols[$ue->userid][$ue->roleid] = $ue->roleid; $currentstatus[$ue->userid] = $ue->status; } } $rs->close(); // Get list of users that need to be enrolled and their roles. $requestedroles = array(); $requestedenrols = array(); $sql = $this->db_get_sql($table, array($coursefield=>$course->mapping), $sqlfields); if ($rs = $extdb->Execute($sql)) { if (!$rs->EOF) { $usersearch = array('deleted' => 0); if ($localuserfield === 'username') { $usersearch['mnethostid'] = $CFG->mnet_localhost_id; } while ($fields = $rs->FetchRow()) { $fields = array_change_key_case($fields, CASE_LOWER); if (empty($fields[$userfield_l])) { $trace->output("error: skipping user without mandatory $localuserfield in course '$course->mapping'", 1); continue; } $mapping = $fields[$userfield_l]; if (!isset($usermapping[$mapping])) { $usersearch[$localuserfield] = $mapping; if (!$user = $DB->get_record('user', $usersearch, 'id', IGNORE_MULTIPLE)) { $trace->output("error: skipping unknown user $localuserfield '$mapping' in course '$course->mapping'", 1); continue; } $usermapping[$mapping] = $user->id; $userid = $user->id; } else { $userid = $usermapping[$mapping]; } if (empty($fields[$rolefield_l]) or !isset($roles[$fields[$rolefield_l]])) { if (!$defaultrole) { $trace->output("error: skipping user '$userid' in course '$course->mapping' - missing course and default role", 1); continue; } $roleid = $defaultrole; } else { $roleid = $roles[$fields[$rolefield_l]]; } $requestedroles[$userid][$roleid] = $roleid; if (empty($fields[$otheruserfieldlower])) { $requestedenrols[$userid][$roleid] = $roleid; } } } $rs->Close(); } else { $trace->output("error: skipping course '$course->mapping' - could not match with external database", 1); continue; } unset($usermapping); // Enrol all users and sync roles. foreach ($requestedenrols as $userid => $userroles) { foreach ($userroles as $roleid) { if (empty($currentenrols[$userid])) { $this->enrol_user($instance, $userid, $roleid, 0, 0, ENROL_USER_ACTIVE); $currentroles[$userid][$roleid] = $roleid; $currentenrols[$userid][$roleid] = $roleid; $currentstatus[$userid] = ENROL_USER_ACTIVE; $trace->output("enrolling: $userid ==> $course->shortname as ".$allroles[$roleid]->shortname, 1); } } // Reenable enrolment when previously disable enrolment refreshed. if ($currentstatus[$userid] == ENROL_USER_SUSPENDED) { $this->update_user_enrol($instance, $userid, ENROL_USER_ACTIVE); $trace->output("unsuspending: $userid ==> $course->shortname", 1); } } foreach ($requestedroles as $userid => $userroles) { // Assign extra roles. foreach ($userroles as $roleid) { if (empty($currentroles[$userid][$roleid])) { role_assign($roleid, $userid, $context->id, 'enrol_database', $instance->id); $currentroles[$userid][$roleid] = $roleid; $trace->output("assigning roles: $userid ==> $course->shortname as ".$allroles[$roleid]->shortname, 1); } } // Unassign removed roles. foreach ($currentroles[$userid] as $cr) { if (empty($userroles[$cr])) { role_unassign($cr, $userid, $context->id, 'enrol_database', $instance->id); unset($currentroles[$userid][$cr]); $trace->output("unsassigning roles: $userid ==> $course->shortname", 1); } } unset($currentroles[$userid]); } foreach ($currentroles as $userid => $userroles) { // These are roles that exist only in Moodle, not the external database // so make sure the unenrol actions will handle them by setting status. $currentstatus += array($userid => ENROL_USER_ACTIVE); } // Deal with enrolments removed from external table. if ($unenrolaction == ENROL_EXT_REMOVED_UNENROL) { if (!$preventfullunenrol) { // Unenrol. foreach ($currentstatus as $userid => $status) { if (isset($requestedenrols[$userid])) { continue; } $this->unenrol_user($instance, $userid); $trace->output("unenrolling: $userid ==> $course->shortname", 1); } } } else if ($unenrolaction == ENROL_EXT_REMOVED_KEEP) { // Keep - only adding enrolments. } else if ($unenrolaction == ENROL_EXT_REMOVED_SUSPEND or $unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) { // Suspend enrolments. foreach ($currentstatus as $userid => $status) { if (isset($requestedenrols[$userid])) { continue; } if ($status != ENROL_USER_SUSPENDED) { $this->update_user_enrol($instance, $userid, ENROL_USER_SUSPENDED); $trace->output("suspending: $userid ==> $course->shortname", 1); } if ($unenrolaction == ENROL_EXT_REMOVED_SUSPENDNOROLES) { if (isset($requestedroles[$userid])) { // We want this "other user" to keep their roles. continue; } role_unassign_all(array('contextid'=>$context->id, 'userid'=>$userid, 'component'=>'enrol_database', 'itemid'=>$instance->id)); $trace->output("unsassigning all roles: $userid ==> $course->shortname", 1); } } } } // Close db connection. $extdb->Close(); $trace->output('...user enrolment synchronisation finished.'); $trace->finished(); return 0; } /** * Performs a full sync with external database. * * First it creates new courses if necessary, then * enrols and unenrols users. * * @param progress_trace $trace * @return int 0 means success, 1 db connect failure, 4 db read failure */ public function sync_courses(progress_trace $trace) { global $CFG, $DB; // Make sure we sync either enrolments or courses. if (!$this->get_config('dbtype') or !$this->get_config('newcoursetable') or !$this->get_config('newcoursefullname') or !$this->get_config('newcourseshortname')) { $trace->output('Course synchronisation skipped.'); $trace->finished(); return 0; } $trace->output('Starting course synchronisation...'); // We may need a lot of memory here. core_php_time_limit::raise(); raise_memory_limit(MEMORY_HUGE); if (!$extdb = $this->db_init()) { $trace->output('Error while communicating with external enrolment database'); $trace->finished(); return 1; } $courseconfig = get_config('moodlecourse'); $table = $this->get_config('newcoursetable'); $fullname = trim($this->get_config('newcoursefullname')); $shortname = trim($this->get_config('newcourseshortname')); $idnumber = trim($this->get_config('newcourseidnumber')); $category = trim($this->get_config('newcoursecategory')); $startdate = trim($this->get_config('newcoursestartdate')); $enddate = trim($this->get_config('newcourseenddate')); // Lowercased versions - necessary because we normalise the resultset with array_change_key_case(). $fullname_l = strtolower($fullname); $shortname_l = strtolower($shortname); $idnumber_l = strtolower($idnumber); $category_l = strtolower($category); $startdatelowercased = strtolower($startdate); $enddatelowercased = strtolower($enddate); $localcategoryfield = $this->get_config('localcategoryfield', 'id'); $defaultcategory = $this->get_config('defaultcategory'); if (!$DB->record_exists('course_categories', array('id'=>$defaultcategory))) { $trace->output("default course category does not exist!", 1); $categories = $DB->get_records('course_categories', array(), 'sortorder', 'id', 0, 1); $first = reset($categories); $defaultcategory = $first->id; } $sqlfields = array($fullname, $shortname); if ($category) { $sqlfields[] = $category; } if ($idnumber) { $sqlfields[] = $idnumber; } if ($startdate) { $sqlfields[] = $startdate; } if ($enddate) { $sqlfields[] = $enddate; } $sql = $this->db_get_sql($table, array(), $sqlfields, true); $createcourses = array(); if ($rs = $extdb->Execute($sql)) { if (!$rs->EOF) { while ($fields = $rs->FetchRow()) { $fields = array_change_key_case($fields, CASE_LOWER); $fields = $this->db_decode($fields); if (empty($fields[$shortname_l]) or empty($fields[$fullname_l])) { $trace->output('error: invalid external course record, shortname and fullname are mandatory: ' . json_encode($fields), 1); // Hopefully every geek can read JS, right? continue; } if ($DB->record_exists('course', array('shortname'=>$fields[$shortname_l]))) { // Already exists, skip. continue; } // Allow empty idnumber but not duplicates. if ($idnumber and $fields[$idnumber_l] !== '' and $fields[$idnumber_l] !== null and $DB->record_exists('course', array('idnumber'=>$fields[$idnumber_l]))) { $trace->output('error: duplicate idnumber, can not create course: '.$fields[$shortname_l].' ['.$fields[$idnumber_l].']', 1); continue; } $course = new stdClass(); $course->fullname = $fields[$fullname_l]; $course->shortname = $fields[$shortname_l]; $course->idnumber = $idnumber ? $fields[$idnumber_l] : ''; if ($category) { if (empty($fields[$category_l])) { // Empty category means use default. $course->category = $defaultcategory; } else if ($coursecategory = $DB->get_record('course_categories', array($localcategoryfield=>$fields[$category_l]), 'id')) { // Yay, correctly specified category! $course->category = $coursecategory->id; unset($coursecategory); } else { // Bad luck, better not continue because unwanted ppl might get access to course in different category. $trace->output('error: invalid category '.$localcategoryfield.', can not create course: '.$fields[$shortname_l], 1); continue; } } else { $course->category = $defaultcategory; } if ($startdate) { if (!empty($fields[$startdatelowercased])) { $course->startdate = is_number($fields[$startdatelowercased]) ? $fields[$startdatelowercased] : strtotime($fields[$startdatelowercased]); // Broken start date. Stop syncing this course. if ($course->startdate === false) { $trace->output('error: invalid external course start date value: ' . json_encode($fields), 1); continue; } } } if ($enddate) { if (!empty($fields[$enddatelowercased])) { $course->enddate = is_number($fields[$enddatelowercased]) ? $fields[$enddatelowercased] : strtotime($fields[$enddatelowercased]); // Broken end date. Stop syncing this course. if ($course->enddate === false) { $trace->output('error: invalid external course end date value: ' . json_encode($fields), 1); continue; } } } $createcourses[] = $course; } } $rs->Close(); } else { $extdb->Close(); $trace->output('Error reading data from the external course table'); $trace->finished(); return 4; } if ($createcourses) { require_once("$CFG->dirroot/course/lib.php"); $templatecourse = $this->get_config('templatecourse'); $template = false; if ($templatecourse) { if ($template = $DB->get_record('course', array('shortname'=>$templatecourse))) { $template = fullclone(course_get_format($template)->get_course()); if (!isset($template->numsections)) { $template->numsections = course_get_format($template)->get_last_section_number(); } unset($template->id); unset($template->fullname); unset($template->shortname); unset($template->idnumber); } else { $trace->output("can not find template for new course!", 1); } } if (!$template) { $template = new stdClass(); $template->summary = ''; $template->summaryformat = FORMAT_HTML; $template->format = $courseconfig->format; $template->numsections = $courseconfig->numsections; $template->newsitems = $courseconfig->newsitems; $template->showgrades = $courseconfig->showgrades; $template->showreports = $courseconfig->showreports; $template->maxbytes = $courseconfig->maxbytes; $template->groupmode = $courseconfig->groupmode; $template->groupmodeforce = $courseconfig->groupmodeforce; $template->visible = $courseconfig->visible; $template->lang = $courseconfig->lang; $template->enablecompletion = $courseconfig->enablecompletion; $template->groupmodeforce = $courseconfig->groupmodeforce; $template->startdate = usergetmidnight(time()); if ($courseconfig->courseenddateenabled) { $template->enddate = usergetmidnight(time()) + $courseconfig->courseduration; } } foreach ($createcourses as $fields) { $newcourse = clone($template); $newcourse->fullname = $fields->fullname; $newcourse->shortname = $fields->shortname; $newcourse->idnumber = $fields->idnumber; $newcourse->category = $fields->category; if (isset($fields->startdate)) { $newcourse->startdate = $fields->startdate; } if (isset($fields->enddate)) { // Validating end date. if ($fields->enddate > 0 && $newcourse->startdate > $fields->enddate) { $trace->output( "can not insert new course, the end date must be after the start date: " . $newcourse->shortname, 1 ); continue; } $newcourse->enddate = $fields->enddate; } else { if ($courseconfig->courseenddateenabled) { $newcourse->enddate = $newcourse->startdate + $courseconfig->courseduration; } } // Detect duplicate data once again, above we can not find duplicates // in external data using DB collation rules... if ($DB->record_exists('course', array('shortname' => $newcourse->shortname))) { $trace->output("can not insert new course, duplicate shortname detected: ".$newcourse->shortname, 1); continue; } else if (!empty($newcourse->idnumber) and $DB->record_exists('course', array('idnumber' => $newcourse->idnumber))) { $trace->output("can not insert new course, duplicate idnumber detected: ".$newcourse->idnumber, 1); continue; } $c = create_course($newcourse); $trace->output("creating course: $c->id, $c->fullname, $c->shortname, $c->idnumber, $c->category", 1); } unset($createcourses); unset($template); } // Close db connection. $extdb->Close(); $trace->output('...course synchronisation finished.'); $trace->finished(); return 0; } protected function db_get_sql($table, array $conditions, array $fields, $distinct = false, $sort = "") { $fields = $fields ? implode(',', $fields) : "*"; $where = array(); if ($conditions) { foreach ($conditions as $key=>$value) { $value = $this->db_encode($this->db_addslashes($value)); $where[] = "$key = '$value'"; } } $where = $where ? "WHERE ".implode(" AND ", $where) : ""; $sort = $sort ? "ORDER BY $sort" : ""; $distinct = $distinct ? "DISTINCT" : ""; $sql = "SELECT $distinct $fields FROM $table $where $sort"; return $sql; } /** * Tries to make connection to the external database. * * @return null|ADONewConnection */ protected function db_init() { global $CFG; require_once($CFG->libdir.'/adodb/adodb.inc.php'); // Connect to the external database (forcing new connection). $extdb = ADONewConnection($this->get_config('dbtype')); if ($this->get_config('debugdb')) { $extdb->debug = true; ob_start(); // Start output buffer to allow later use of the page headers. } // The dbtype my contain the new connection URL, so make sure we are not connected yet. if (!$extdb->IsConnected()) { $result = $extdb->Connect($this->get_config('dbhost'), $this->get_config('dbuser'), $this->get_config('dbpass'), $this->get_config('dbname'), true); if (!$result) { return null; } } $extdb->SetFetchMode(ADODB_FETCH_ASSOC); if ($this->get_config('dbsetupsql')) { $extdb->Execute($this->get_config('dbsetupsql')); } return $extdb; } protected function db_addslashes($text) { // Use custom made function for now - it is better to not rely on adodb or php defaults. if ($this->get_config('dbsybasequoting')) { $text = str_replace('\\', '\\\\', $text); $text = str_replace(array('\'', '"', "\0"), array('\\\'', '\\"', '\\0'), $text); } else { $text = str_replace("'", "''", $text); } return $text; } protected function db_encode($text) { $dbenc = $this->get_config('dbencoding'); if (empty($dbenc) or $dbenc == 'utf-8') { return $text; } if (is_array($text)) { foreach($text as $k=>$value) { $text[$k] = $this->db_encode($value); } return $text; } else { return core_text::convert($text, 'utf-8', $dbenc); } } protected function db_decode($text) { $dbenc = $this->get_config('dbencoding'); if (empty($dbenc) or $dbenc == 'utf-8') { return $text; } if (is_array($text)) { foreach($text as $k=>$value) { $text[$k] = $this->db_decode($value); } return $text; } else { return core_text::convert($text, $dbenc, 'utf-8'); } } /** * Automatic enrol sync executed during restore. * @param stdClass $course course record */ public function restore_sync_course($course) { $trace = new null_progress_trace(); $this->sync_enrolments($trace, $course->id); } /** * Restore instance and map settings. * * @param restore_enrolments_structure_step $step * @param stdClass $data * @param stdClass $course * @param int $oldid */ public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) { global $DB; if ($instance = $DB->get_record('enrol', array('courseid'=>$course->id, 'enrol'=>$this->get_name()))) { $instanceid = $instance->id; } else { $instanceid = $this->add_instance($course); } $step->set_mapping('enrol', $oldid, $instanceid); } /** * Restore user enrolment. * * @param restore_enrolments_structure_step $step * @param stdClass $data * @param stdClass $instance * @param int $oldinstancestatus * @param int $userid */ public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) { global $DB; if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_UNENROL) { // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers. return; } if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) { $this->enrol_user($instance, $userid, null, 0, 0, ENROL_USER_SUSPENDED); } } /** * Restore role assignment. * * @param stdClass $instance * @param int $roleid * @param int $userid * @param int $contextid */ public function restore_role_assignment($instance, $roleid, $userid, $contextid) { if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_UNENROL or $this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) { // Role assignments were already synchronised in restore_instance(), we do not want any leftovers. return; } role_assign($roleid, $userid, $contextid, 'enrol_'.$this->get_name(), $instance->id); } /** * Test plugin settings, print info to output. */ public function test_settings() { global $CFG, $OUTPUT; // NOTE: this is not localised intentionally, admins are supposed to understand English at least a bit... raise_memory_limit(MEMORY_HUGE); $this->load_config(); $enroltable = $this->get_config('remoteenroltable'); $coursetable = $this->get_config('newcoursetable'); if (empty($enroltable)) { echo $OUTPUT->notification('External enrolment table not specified.', 'notifyproblem'); } if (empty($coursetable)) { echo $OUTPUT->notification('External course table not specified.', 'notifyproblem'); } if (empty($coursetable) and empty($enroltable)) { return; } $olddebug = $CFG->debug; $olddisplay = ini_get('display_errors'); ini_set('display_errors', '1'); $CFG->debug = DEBUG_DEVELOPER; $olddebugdb = $this->config->debugdb; $this->config->debugdb = 1; error_reporting($CFG->debug); $adodb = $this->db_init(); if (!$adodb or !$adodb->IsConnected()) { $this->config->debugdb = $olddebugdb; $CFG->debug = $olddebug; ini_set('display_errors', $olddisplay); error_reporting($CFG->debug); ob_end_flush(); echo $OUTPUT->notification('Cannot connect the database.', 'notifyproblem'); return; } if (!empty($enroltable)) { $rs = $adodb->Execute("SELECT * FROM $enroltable"); if (!$rs) { echo $OUTPUT->notification('Can not read external enrol table.', 'notifyproblem'); } else if ($rs->EOF) { echo $OUTPUT->notification('External enrol table is empty.', 'notifyproblem'); $rs->Close(); } else { $columns = array_keys($rs->fetchRow()); echo $OUTPUT->notification('External enrolment table contains following columns:
'.implode(', ', $columns), 'notifysuccess'); $rs->Close(); } } if (!empty($coursetable)) { $rs = $adodb->Execute("SELECT * FROM $coursetable"); if (!$rs) { echo $OUTPUT->notification('Can not read external course table.', 'notifyproblem'); } else if ($rs->EOF) { echo $OUTPUT->notification('External course table is empty.', 'notifyproblem'); $rs->Close(); } else { $columns = array_keys($rs->fetchRow()); echo $OUTPUT->notification('External course table contains following columns:
'.implode(', ', $columns), 'notifysuccess'); $rs->Close(); } } $adodb->Close(); $this->config->debugdb = $olddebugdb; $CFG->debug = $olddebug; ini_set('display_errors', $olddisplay); error_reporting($CFG->debug); ob_end_flush(); } } PK \}X version.phpnu[. /** * Database enrolment plugin version specification. * * @package enrol_database * @copyright 2010 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $plugin->version = 2025041402; // The current plugin version (Date: YYYYMMDDXX). $plugin->requires = 2025040800; // Requires this Moodle version. $plugin->component = 'enrol_database'; // Full name of the plugin (used for diagnostics) PK \-classes/privacy/provider.phpnu[. /** * Privacy Subsystem implementation for enrol_database. * * @package enrol_database * @copyright 2018 Carlos Escobedo * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace enrol_database\privacy; defined('MOODLE_INTERNAL') || die(); /** * Privacy Subsystem for enrol_database implementing null_provider. * * @copyright 2018 Carlos Escobedo * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class provider implements \core_privacy\local\metadata\null_provider { /** * Get the language string identifier with the component's language * file to explain why this plugin stores no data. * * @return string */ public static function get_reason(): string { return 'privacy:metadata'; } }PK \S MM classes/task/sync_enrolments.phpnu[. /** * Sync enrolments task * @package enrol_database * @copyright 2018 Daniel Neis Araujo * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace enrol_database\task; defined('MOODLE_INTERNAL') || die(); /** * Class sync_enrolments * @package enrol_database * @copyright 2018 Daniel Neis Araujo * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ class sync_enrolments extends \core\task\scheduled_task { /** * Name for this task. * * @return string */ public function get_name() { return get_string('syncenrolmentstask', 'enrol_database'); } /** * Run task for synchronising users. */ public function execute() { $trace = new \text_progress_trace(); if (!enrol_is_enabled('database')) { $trace->output('Plugin not enabled'); return; } $enrol = enrol_get_plugin('database'); // Update enrolments -- these handlers should autocreate courses if required. $enrol->sync_courses($trace); $enrol->sync_enrolments($trace); } } PK \ucMM upgrade.txtnu[=== 4.5 Onwards === This file has been replaced by UPGRADING.md. See MDL-81125 for further information. === This files describes API changes in the enrol_database code. === 3.11 === * Final deprecation enrol/database/cli/sync.php. Refer below for substitute. === 3.9 === * Class enrol_database_admin_setting_category has been removed. This class was only used by the database enrolment plugin settings and it was replaced by admin_settings_coursecat_select. === 3.7 === * enrol/database/cli/sync.php script has been deprecated in favour of enrol_database\task\sync_enrolments task. PK \Fu tests/lib_test.phpnu[. /** * Database enrolment tests. * * @package enrol_database * @copyright 2017 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ namespace enrol_database; use course_enrolment_manager; defined('MOODLE_INTERNAL') || die(); /** * Database enrolment tests. * * @package enrol_database * @copyright 2017 Jun Pataleta * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ final class lib_test extends \advanced_testcase { public static function tearDownAfterClass(): void { global $DB; // Apply sqlsrv native driver error and logging default // settings while finishing the AdoDB tests. if ($DB->get_dbfamily() === 'mssql') { sqlsrv_configure("WarningsReturnAsErrors", false); sqlsrv_configure("LogSubsystems", SQLSRV_LOG_SYSTEM_OFF); sqlsrv_configure("LogSeverity", SQLSRV_LOG_SEVERITY_ERROR); } parent::tearDownAfterClass(); } /** * Test for getting user enrolment actions. */ public function test_get_user_enrolment_actions(): void { global $CFG, $PAGE; $this->resetAfterTest(); // Set page URL to prevent debugging messages. $PAGE->set_url('/enrol/editinstance.php'); $pluginname = 'database'; // Only enable the database enrol plugin. $CFG->enrol_plugins_enabled = $pluginname; $generator = $this->getDataGenerator(); // Get the enrol plugin. $plugin = enrol_get_plugin($pluginname); // Create a course. $course = $generator->create_course(); // Enable this enrol plugin for the course. $plugin->add_instance($course); // Create a student. $student = $generator->create_user(); // Enrol the student to the course. $generator->enrol_user($student->id, $course->id, 'student', $pluginname); // Teachers don't have enrol/database:unenrol capability by default. Login as admin for simplicity. $this->setAdminUser(); require_once($CFG->dirroot . '/enrol/locallib.php'); $manager = new course_enrolment_manager($PAGE, $course); $userenrolments = $manager->get_user_enrolments($student->id); $this->assertCount(1, $userenrolments); $ue = reset($userenrolments); $actions = $plugin->get_user_enrolment_actions($manager, $ue); // Database enrol has 0 enrol actions for active users. $this->assertCount(0, $actions); // Enrol actions for a suspended student. // Suspend the student. $ue->status = ENROL_USER_SUSPENDED; $actions = $plugin->get_user_enrolment_actions($manager, $ue); // Database enrol has enrol actions for suspended students -- unenrol. $this->assertCount(1, $actions); } } PK \Vѝtests/sync_test.phpnu[. namespace enrol_database; /** * External database enrolment sync tests * * This also tests adodb drivers that are matching * our four supported Moodle database drivers. * * @package enrol_database * @category test * @copyright 2011 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ final class sync_test extends \advanced_testcase { protected static $courses = array(); protected static $users = array(); protected static $roles = array(); /** @var string Original error log */ protected $oldlog; public static function tearDownAfterClass(): void { global $DB; // Apply sqlsrv native driver error and logging default // settings while finishing the AdoDB tests. if ($DB->get_dbfamily() === 'mssql') { sqlsrv_configure("WarningsReturnAsErrors", false); sqlsrv_configure("LogSubsystems", SQLSRV_LOG_SYSTEM_OFF); sqlsrv_configure("LogSeverity", SQLSRV_LOG_SEVERITY_ERROR); } parent::tearDownAfterClass(); } protected function init_enrol_database() { global $DB, $CFG; // Discard error logs from AdoDB. $this->oldlog = ini_get('error_log'); ini_set('error_log', "$CFG->dataroot/testlog.log"); $dbman = $DB->get_manager(); set_config('dbencoding', 'utf-8', 'enrol_database'); set_config('dbhost', $CFG->dbhost, 'enrol_database'); set_config('dbuser', $CFG->dbuser, 'enrol_database'); set_config('dbpass', $CFG->dbpass, 'enrol_database'); set_config('dbname', $CFG->dbname, 'enrol_database'); if (!empty($CFG->dboptions['dbport'])) { set_config('dbhost', $CFG->dbhost.':'.$CFG->dboptions['dbport'], 'enrol_database'); } switch ($DB->get_dbfamily()) { case 'mysql': set_config('dbtype', 'mysqli', 'enrol_database'); set_config('dbsetupsql', "SET NAMES 'UTF-8'", 'enrol_database'); set_config('dbsybasequoting', '0', 'enrol_database'); if (!empty($CFG->dboptions['dbsocket'])) { $dbsocket = $CFG->dboptions['dbsocket']; if ((strpos($dbsocket, '/') === false and strpos($dbsocket, '\\') === false)) { $dbsocket = ini_get('mysqli.default_socket'); } set_config('dbtype', 'mysqli://'.rawurlencode($CFG->dbuser).':'.rawurlencode($CFG->dbpass).'@'.rawurlencode($CFG->dbhost).'/'.rawurlencode($CFG->dbname).'?socket='.rawurlencode($dbsocket), 'enrol_database'); } break; case 'postgres': set_config('dbtype', 'postgres7', 'enrol_database'); $setupsql = "SET NAMES 'UTF-8'"; if (!empty($CFG->dboptions['dbschema'])) { $setupsql .= "; SET search_path = '".$CFG->dboptions['dbschema']."'"; } set_config('dbsetupsql', $setupsql, 'enrol_database'); set_config('dbsybasequoting', '0', 'enrol_database'); if (!empty($CFG->dboptions['dbsocket']) and ($CFG->dbhost === 'localhost' or $CFG->dbhost === '127.0.0.1')) { if (strpos($CFG->dboptions['dbsocket'], '/') !== false) { $socket = $CFG->dboptions['dbsocket']; if (!empty($CFG->dboptions['dbport'])) { $socket .= ':' . $CFG->dboptions['dbport']; } set_config('dbhost', $socket, 'enrol_database'); } else { set_config('dbhost', '', 'enrol_database'); } } break; case 'mssql': set_config('dbtype', 'mssqlnative', 'enrol_database'); set_config('dbsybasequoting', '1', 'enrol_database'); // The native sqlsrv driver uses a comma as separator between host and port. $dbhost = $CFG->dbhost; if (!empty($dboptions['dbport'])) { $dbhost .= ',' . $dboptions['dbport']; } set_config('dbhost', $dbhost, 'enrol_database'); break; default: throw new exception('Unknown database driver '.get_class($DB)); } // NOTE: It is stongly discouraged to create new tables in advanced_testcase classes, // but there is no other simple way to test ext database enrol sync, so let's // disable transactions are try to cleanup after the tests. $table = new \xmldb_table('enrol_database_test_enrols'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('courseid', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('userid', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('roleid', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('otheruser', XMLDB_TYPE_CHAR, '1', null, XMLDB_NOTNULL, null, '0'); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); set_config('remoteenroltable', $CFG->prefix.'enrol_database_test_enrols', 'enrol_database'); set_config('remotecoursefield', 'courseid', 'enrol_database'); set_config('remoteuserfield', 'userid', 'enrol_database'); set_config('remoterolefield', 'roleid', 'enrol_database'); set_config('remoteotheruserfield', 'otheruser', 'enrol_database'); $table = new \xmldb_table('enrol_database_test_courses'); $table->add_field('id', XMLDB_TYPE_INTEGER, '10', null, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); $table->add_field('fullname', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('shortname', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('idnumber', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('category', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('startdate', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_field('enddate', XMLDB_TYPE_CHAR, '255', null, null, null); $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); if ($dbman->table_exists($table)) { $dbman->drop_table($table); } $dbman->create_table($table); set_config('newcoursetable', $CFG->prefix.'enrol_database_test_courses', 'enrol_database'); set_config('newcoursefullname', 'fullname', 'enrol_database'); set_config('newcourseshortname', 'shortname', 'enrol_database'); set_config('newcourseidnumber', 'idnumber', 'enrol_database'); set_config('newcoursecategory', 'category', 'enrol_database'); // Create some test users and courses. for ($i = 1; $i <= 4; $i++) { self::$courses[$i] = $this->getDataGenerator()->create_course(array('fullname' => 'Test course '.$i, 'shortname' => 'tc'.$i, 'idnumber' => 'courseid'.$i)); } for ($i = 1; $i <= 10; $i++) { self::$users[$i] = $this->getDataGenerator()->create_user(array('username' => 'username'.$i, 'idnumber' => 'userid'.$i, 'email' => 'user'.$i.'@example.com')); } foreach (get_all_roles() as $role) { self::$roles[$role->shortname] = $role; } } protected function cleanup_enrol_database() { global $DB; $dbman = $DB->get_manager(); $table = new \xmldb_table('enrol_database_test_enrols'); $dbman->drop_table($table); $table = new \xmldb_table('enrol_database_test_courses'); $dbman->drop_table($table); self::$courses = null; self::$users = null; self::$roles = null; ini_set('error_log', $this->oldlog); } protected function reset_enrol_database() { global $DB; $DB->delete_records('enrol_database_test_enrols', array()); $DB->delete_records('enrol_database_test_courses', array()); $plugin = enrol_get_plugin('database'); $instances = $DB->get_records('enrol', array('enrol' => 'database')); foreach($instances as $instance) { $plugin->delete_instance($instance); } } protected function assertIsEnrolled($userindex, $courseindex, $status=null, $rolename = null) { global $DB; $dbinstance = $DB->get_record('enrol', array('courseid' => self::$courses[$courseindex]->id, 'enrol' => 'database'), '*', MUST_EXIST); $conditions = array('enrolid' => $dbinstance->id, 'userid' => self::$users[$userindex]->id); if ($status !== null) { $conditions['status'] = $status; } $this->assertTrue($DB->record_exists('user_enrolments', $conditions)); $this->assertHasRoleAssignment($userindex, $courseindex, $rolename); } protected function assertHasRoleAssignment($userindex, $courseindex, $rolename = null) { global $DB; $dbinstance = $DB->get_record('enrol', array('courseid' => self::$courses[$courseindex]->id, 'enrol' => 'database'), '*', MUST_EXIST); $coursecontext = \context_course::instance(self::$courses[$courseindex]->id); if ($rolename === false) { $this->assertFalse($DB->record_exists('role_assignments', array('component' => 'enrol_database', 'itemid' => $dbinstance->id, 'userid' => self::$users[$userindex]->id, 'contextid' => $coursecontext->id))); } else if ($rolename !== null) { $this->assertTrue($DB->record_exists('role_assignments', array('component' => 'enrol_database', 'itemid' => $dbinstance->id, 'userid' => self::$users[$userindex]->id, 'contextid' => $coursecontext->id, 'roleid' => self::$roles[$rolename]->id))); } } protected function assertIsNotEnrolled($userindex, $courseindex) { global $DB; if (!$dbinstance = $DB->get_record('enrol', array('courseid' => self::$courses[$courseindex]->id, 'enrol' => 'database'))) { return; } $this->assertFalse($DB->record_exists('user_enrolments', array('enrolid' => $dbinstance->id, 'userid' => self::$users[$userindex]->id))); } public function test_sync_user_enrolments(): void { global $DB; $this->init_enrol_database(); $this->resetAfterTest(false); $this->preventResetByRollback(); $plugin = enrol_get_plugin('database'); // Test basic enrol sync for one user after login. $this->reset_enrol_database(); $plugin->set_config('localcoursefield', 'idnumber'); $plugin->set_config('localuserfield', 'idnumber'); $plugin->set_config('localrolefield', 'shortname'); $plugin->set_config('defaultrole', self::$roles['student']->id); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid2', 'roleid' => 'teacher')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid2', 'courseid' => 'courseid1', 'roleid' => null)); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid4', 'courseid' => 'courseid4', 'roleid' => 'editingteacher', 'otheruser' => '1')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'xxxxxxx', 'courseid' => 'courseid1', 'roleid' => 'student')); // Bogus record to be ignored. $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'xxxxxxxxx', 'roleid' => 'student')); // Bogus record to be ignored. $this->assertEquals(0, $DB->count_records('user_enrolments', array())); $this->assertEquals(0, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(0, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(2, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); // Make sure there are no errors or changes on the next login. $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(2, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $plugin->sync_user_enrolments(self::$users[2]); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(3, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $plugin->sync_user_enrolments(self::$users[4]); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); // Enrolment removals. $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_KEEP); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_SUSPENDED, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(3, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_SUSPENDED, false); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(3, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsNotEnrolled(1, 1); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid4', 'courseid' => 'courseid4', 'roleid' => 'editingteacher')); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES); $plugin->sync_user_enrolments(self::$users[4]); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(2, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, false); // Test all other mapping options. $this->reset_enrol_database(); $this->assertEquals(0, $DB->count_records('user_enrolments', array())); $this->assertEquals(0, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(0, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $plugin->set_config('localcoursefield', 'id'); $plugin->set_config('localuserfield', 'id'); $plugin->set_config('localrolefield', 'id'); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->id, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->id, 'courseid' => self::$courses[2]->id, 'roleid' => self::$roles['teacher']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[2]->id, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(2, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->reset_enrol_database(); $plugin->set_config('localcoursefield', 'shortname'); $plugin->set_config('localuserfield', 'email'); $plugin->set_config('localrolefield', 'id'); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->email, 'courseid' => self::$courses[1]->shortname, 'roleid' => self::$roles['student']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->email, 'courseid' => self::$courses[2]->shortname, 'roleid' => self::$roles['teacher']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[2]->email, 'courseid' => self::$courses[1]->shortname, 'roleid' => self::$roles['student']->id)); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(2, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->reset_enrol_database(); $plugin->set_config('localcoursefield', 'id'); $plugin->set_config('localuserfield', 'username'); $plugin->set_config('localrolefield', 'id'); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->username, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->username, 'courseid' => self::$courses[2]->id, 'roleid' => self::$roles['teacher']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[2]->username, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $plugin->sync_user_enrolments(self::$users[1]); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(2, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); } /** * @depends test_sync_user_enrolments */ public function test_sync_users(): void { global $DB; $this->resetAfterTest(false); $this->preventResetByRollback(); $this->reset_enrol_database(); $plugin = enrol_get_plugin('database'); $trace = new \null_progress_trace(); // Test basic enrol sync for one user after login. $plugin->set_config('localcoursefield', 'idnumber'); $plugin->set_config('localuserfield', 'idnumber'); $plugin->set_config('localrolefield', 'shortname'); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid2', 'roleid' => 'editingteacher')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid2', 'courseid' => 'courseid1', 'roleid' => 'student')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid4', 'courseid' => 'courseid4', 'roleid' => 'editingteacher', 'otheruser' => '1')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'xxxxxxx', 'courseid' => 'courseid1', 'roleid' => 'student')); // Bogus record to be ignored. $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'xxxxxxxxx', 'roleid' => 'student')); // Bogus record to be ignored. $this->assertEquals(0, $DB->count_records('user_enrolments', array())); $this->assertEquals(0, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(0, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $plugin->sync_enrolments($trace); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $plugin->set_config('defaultrole', self::$roles['teacher']->id); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid3', 'courseid' => 'courseid3')); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(5, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); // Test different unenrolment options. $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_KEEP); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(5, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPEND); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(5, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_SUSPENDED, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(5, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_SUSPENDNOROLES); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_SUSPENDED, false); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(5, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL); $plugin->sync_enrolments($trace); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(4, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsNotEnrolled(1, 1); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'student')); $DB->insert_record('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'teacher')); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(6, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'teacher'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); $DB->delete_records('enrol_database_test_enrols', array('userid' => 'userid1', 'courseid' => 'courseid1', 'roleid' => 'teacher')); $plugin->sync_enrolments($trace); $this->assertEquals(4, $DB->count_records('user_enrolments', array())); $this->assertEquals(4, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(5, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'editingteacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsNotEnrolled(4, 4); $this->assertHasRoleAssignment(4, 4, 'editingteacher'); $this->assertIsEnrolled(3, 3, ENROL_USER_ACTIVE, 'teacher'); // Test all other mapping options. $this->reset_enrol_database(); $this->assertEquals(0, $DB->count_records('user_enrolments', array())); $this->assertEquals(0, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(0, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $plugin->set_config('localcoursefield', 'id'); $plugin->set_config('localuserfield', 'id'); $plugin->set_config('localrolefield', 'id'); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->id, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->id, 'courseid' => self::$courses[2]->id, 'roleid' => self::$roles['teacher']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[2]->id, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $plugin->sync_enrolments($trace); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(3, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->reset_enrol_database(); $plugin->set_config('localcoursefield', 'shortname'); $plugin->set_config('localuserfield', 'email'); $plugin->set_config('localrolefield', 'id'); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->email, 'courseid' => self::$courses[1]->shortname, 'roleid' => self::$roles['student']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->email, 'courseid' => self::$courses[2]->shortname, 'roleid' => self::$roles['teacher']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[2]->email, 'courseid' => self::$courses[1]->shortname, 'roleid' => self::$roles['student']->id)); $plugin->sync_enrolments($trace); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(3, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $this->reset_enrol_database(); $plugin->set_config('localcoursefield', 'id'); $plugin->set_config('localuserfield', 'username'); $plugin->set_config('localrolefield', 'id'); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->username, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->username, 'courseid' => self::$courses[2]->id, 'roleid' => self::$roles['teacher']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[2]->username, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $plugin->sync_enrolments($trace); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(3, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); // Test sync of one course only. $this->reset_enrol_database(); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->username, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[1]->username, 'courseid' => self::$courses[2]->id, 'roleid' => self::$roles['teacher']->id)); $DB->insert_record('enrol_database_test_enrols', array('userid' => self::$users[2]->username, 'courseid' => self::$courses[1]->id, 'roleid' => self::$roles['student']->id)); $this->assertEquals(0, $DB->count_records('user_enrolments', array())); $this->assertEquals(0, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(0, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $plugin->sync_enrolments($trace, self::$courses[3]->id); $this->assertEquals(0, $DB->count_records('user_enrolments', array())); $this->assertEquals(1, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(0, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $plugin->sync_enrolments($trace, self::$courses[1]->id); $this->assertEquals(2, $DB->count_records('user_enrolments', array())); $this->assertEquals(2, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(2, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $plugin->sync_enrolments($trace, self::$courses[2]->id); $this->assertEquals(3, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(3, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 1, ENROL_USER_ACTIVE, 'student'); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $this->assertIsEnrolled(2, 1, ENROL_USER_ACTIVE, 'student'); $plugin->set_config('unenrolaction', ENROL_EXT_REMOVED_UNENROL); $DB->delete_records('enrol_database_test_enrols', array()); $plugin->sync_enrolments($trace, self::$courses[1]->id); $this->assertEquals(1, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(1, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); $this->assertIsEnrolled(1, 2, ENROL_USER_ACTIVE, 'teacher'); $plugin->sync_enrolments($trace, self::$courses[2]->id); $this->assertEquals(0, $DB->count_records('user_enrolments', array())); $this->assertEquals(3, $DB->count_records('enrol', array('enrol' => 'database'))); $this->assertEquals(0, $DB->count_records('role_assignments', array('component' => 'enrol_database'))); } /** * @depends test_sync_users */ public function test_sync_courses(): void { global $DB; $this->resetAfterTest(true); $this->preventResetByRollback(); $this->reset_enrol_database(); $plugin = enrol_get_plugin('database'); $trace = new \null_progress_trace(); $plugin->set_config('localcategoryfield', 'id'); $coursecat = $this->getDataGenerator()->create_category(array('name' => 'Test category 1', 'idnumber' => 'tcid1')); $defcat = $DB->get_record('course_categories', array('id' => $plugin->get_config('defaultcategory'))); $course1 = array('fullname' => 'New course 1', 'shortname' => 'nc1', 'idnumber' => 'ncid1', 'category' => $coursecat->id); $course2 = array('fullname' => 'New course 2', 'shortname' => 'nc2', 'idnumber' => 'ncid2', 'category' => null); // Duplicate records are to be ignored. $course3 = array('fullname' => 'New course 3', 'shortname' => 'xx', 'idnumber' => 'yy2', 'category' => $defcat->id); $course4 = array('fullname' => 'New course 4', 'shortname' => 'xx', 'idnumber' => 'yy3', 'category' => $defcat->id); $course5 = array('fullname' => 'New course 5', 'shortname' => 'xx1', 'idnumber' => 'yy', 'category' => $defcat->id); $course6 = array('fullname' => 'New course 6', 'shortname' => 'xx2', 'idnumber' => 'yy', 'category' => $defcat->id); $DB->insert_record('enrol_database_test_courses', $course1); $DB->insert_record('enrol_database_test_courses', $course2); $DB->insert_record('enrol_database_test_courses', $course3); $DB->insert_record('enrol_database_test_courses', $course4); $DB->insert_record('enrol_database_test_courses', $course5); $DB->insert_record('enrol_database_test_courses', $course6); $this->assertEquals(1+count(self::$courses), $DB->count_records('course')); $plugin->sync_courses($trace); $this->assertEquals(4+1+count(self::$courses), $DB->count_records('course')); $this->assertTrue($DB->record_exists('course', $course1)); $course2['category'] = $defcat->id; $this->assertTrue($DB->record_exists('course', $course2)); // People should NOT push duplicates there because the results are UNDEFINED! But anyway skip the duplicates. $this->assertEquals(1, $DB->count_records('course', array('idnumber' => 'yy'))); $this->assertEquals(1, $DB->count_records('course', array('shortname' => 'xx'))); // Check default number of sections matches with the created course sections. $recordcourse1 = $DB->get_record('course', $course1); $courseconfig = get_config('moodlecourse'); $numsections = $DB->count_records('course_sections', array('course' => $recordcourse1->id)); // To compare numsections we have to add topic 0 to default numsections. $this->assertEquals(($courseconfig->numsections + 1), $numsections); // Test category mapping via idnumber. $plugin->set_config('localcategoryfield', 'idnumber'); $course7 = array('fullname' => 'New course 7', 'shortname' => 'nc7', 'idnumber' => 'ncid7', 'category' => 'tcid1'); $DB->insert_record('enrol_database_test_courses', $course7); $plugin->sync_courses($trace); $this->assertEquals(1+4+1+count(self::$courses), $DB->count_records('course')); $this->assertTrue($DB->record_exists('course', $course1)); $this->assertTrue($DB->record_exists('course', $course2)); $course7['category'] = $coursecat->id; $this->assertTrue($DB->record_exists('course', $course7)); // Test course template. $template = $this->getDataGenerator()->create_course(array('numsections' => 666, 'shortname' => 'crstempl')); $plugin->set_config('templatecourse', 'crstempl'); $course8 = array('fullname' => 'New course 8', 'shortname' => 'nc8', 'idnumber' => 'ncid8', 'category' => null); $DB->insert_record('enrol_database_test_courses', $course8); $plugin->sync_courses($trace); $this->assertEquals(2+1+4+1+count(self::$courses), $DB->count_records('course')); $course8['category'] = $defcat->id; $record = $DB->get_record('course', $course8); $this->assertFalse(empty($record)); $this->assertEquals(666, course_get_format($record)->get_last_section_number()); // Test invalid category. $course9 = array('fullname' => 'New course 9', 'shortname' => 'nc9', 'idnumber' => 'ncid9', 'category' => 'xxxxxxx'); $DB->insert_record('enrol_database_test_courses', $course9); $plugin->sync_courses($trace); $this->assertEquals(2+1+4+1+count(self::$courses), $DB->count_records('course')); $this->assertFalse($DB->record_exists('course', array('idnumber' => 'ncid9'))); // Test when categories not specified. $plugin->set_config('newcoursecategory', ''); $plugin->sync_courses($trace); $this->assertEquals(1+2+1+4+1+count(self::$courses), $DB->count_records('course')); $this->assertTrue($DB->record_exists('course', array('idnumber' => 'ncid9'))); // Final cleanup - remove extra tables, fixtures and caches. $this->cleanup_enrol_database(); } /** * Test syncing courses with start and end dates. * * @covers \enrol_database_plugin::sync_courses */ public function test_sync_courses_start_end_dates(): void { global $DB; $this->resetAfterTest(); $this->preventResetByRollback(); $this->init_enrol_database(); $courseconfig = get_config('moodlecourse'); $nextyear = (int) date('Y') + 1; $prev = (int) date('Y') - 1; $midnightstartdate = usergetmidnight(time()); $midnightenddate = usergetmidnight(time()) + $courseconfig->courseduration; $plugin = enrol_get_plugin('database'); $trace = new \null_progress_trace(); $course1 = ['fullname' => 'C1', 'shortname' => 'c1', 'idnumber' => 'c1', 'startdate' => 0, 'enddate' => 0]; $course2 = ['fullname' => 'C2', 'shortname' => 'c2', 'idnumber' => 'c2', 'startdate' => null, 'enddate' => null]; // This course won't be created. Broken start date. $course3 = ['fullname' => 'C3', 'shortname' => 'c3', 'idnumber' => 'c3', 'startdate' => 'not date', 'enddate' => 0]; // This course won't be created. Broken end date. $course4 = ['fullname' => 'C4', 'shortname' => 'c4', 'idnumber' => 'c4', 'startdate' => 0, 'enddate' => 'not date']; // This course won't be created. Start date after end date. $course5 = ['fullname' => 'C5', 'shortname' => 'c5', 'idnumber' => 'c5', 'startdate' => '12.05.2024', 'enddate' => '12.05.2021']; $course6 = ['fullname' => 'C6', 'shortname' => 'c6', 'idnumber' => 'c6', 'startdate' => '2024-05-22', 'enddate' => '2027-05-12']; $course7 = ['fullname' => 'C7', 'shortname' => 'c7', 'idnumber' => 'c7', 'startdate' => null, 'enddate' => '12.05.' . $nextyear]; $course8 = ['fullname' => 'C8', 'shortname' => 'c8', 'idnumber' => 'c8', 'startdate' => '12.05.2024', 'enddate' => null]; // This course won't be created. Start date is not set, but it should be set to date after end date. $course9 = ['fullname' => 'C9', 'shortname' => 'c9', 'idnumber' => 'c9', 'startdate' => null, 'enddate' => '12.05.' . $prev]; $DB->insert_record('enrol_database_test_courses', $course1); $DB->insert_record('enrol_database_test_courses', $course2); $DB->insert_record('enrol_database_test_courses', $course3); $DB->insert_record('enrol_database_test_courses', $course4); $DB->insert_record('enrol_database_test_courses', $course5); $DB->insert_record('enrol_database_test_courses', $course6); $DB->insert_record('enrol_database_test_courses', $course7); $DB->insert_record('enrol_database_test_courses', $course8); $DB->insert_record('enrol_database_test_courses', $course9); $plugin->set_config('newcoursestartdate', 'startdate'); $plugin->set_config('newcourseenddate', 'enddate'); $plugin->sync_courses($trace); // Course 3, course 4, course 5 and course 9 should not be created. $this->assertTrue($DB->record_exists('course', ['shortname' => $course1['shortname']])); $this->assertTrue($DB->record_exists('course', ['shortname' => $course2['shortname']])); $this->assertFalse($DB->record_exists('course', ['shortname' => $course3['shortname']])); $this->assertFalse($DB->record_exists('course', ['shortname' => $course4['shortname']])); $this->assertFalse($DB->record_exists('course', ['shortname' => $course5['shortname']])); $this->assertTrue($DB->record_exists('course', ['shortname' => $course6['shortname']])); $this->assertTrue($DB->record_exists('course', ['shortname' => $course7['shortname']])); $this->assertTrue($DB->record_exists('course', ['shortname' => $course8['shortname']])); $this->assertFalse($DB->record_exists('course', ['shortname' => $course9['shortname']])); // Check dates for created courses. $this->assertEquals($midnightstartdate, $DB->get_field('course', 'startdate', ['shortname' => $course1['shortname']])); $this->assertEquals($midnightenddate, $DB->get_field('course', 'enddate', ['shortname' => $course1['shortname']])); $this->assertEquals($midnightstartdate, $DB->get_field('course', 'startdate', ['shortname' => $course2['shortname']])); $this->assertEquals($midnightenddate, $DB->get_field('course', 'enddate', ['shortname' => $course2['shortname']])); $this->assertEquals(strtotime('22.05.2024'), $DB->get_field('course', 'startdate', ['shortname' => $course6['shortname']])); $this->assertEquals(strtotime('12.05.2027'), $DB->get_field('course', 'enddate', ['shortname' => $course6['shortname']])); $this->assertEquals($midnightstartdate, $DB->get_field('course', 'startdate', ['shortname' => $course7['shortname']])); $expected = strtotime('12.05.' . $nextyear); $this->assertEquals($expected, $DB->get_field('course', 'enddate', ['shortname' => $course7['shortname']])); $this->assertEquals(strtotime('12.05.2024'), $DB->get_field('course', 'startdate', ['shortname' => $course8['shortname']])); $expected = strtotime('12.05.2024') + $courseconfig->courseduration; $this->assertEquals($expected, $DB->get_field('course', 'enddate', ['shortname' => $course8['shortname']])); // Push course with dates as timestamp. $course10 = ['fullname' => 'C10', 'shortname' => 'c10', 'idnumber' => 'c10', 'startdate' => 1810051200, 'enddate' => 1810051211]; $DB->insert_record('enrol_database_test_courses', $course10); $plugin->sync_courses($trace); $this->assertTrue($DB->record_exists('course', ['shortname' => $course10['shortname']])); $this->assertEquals(1810051200, $DB->get_field('course', 'startdate', ['shortname' => $course10['shortname']])); $this->assertEquals(1810051211, $DB->get_field('course', 'enddate', ['shortname' => $course10['shortname']])); // Push course with broken dates, but delete dates from plugin configuration before syncing. $course11 = ['fullname' => 'C11', 'shortname' => 'c11', 'idnumber' => 'c11', 'startdate' => 'not date', 'enddate' => 'not date']; $DB->insert_record('enrol_database_test_courses', $course11); $plugin->set_config('newcoursestartdate', ''); $plugin->set_config('newcourseenddate', ''); $plugin->sync_courses($trace); $this->assertTrue($DB->record_exists('course', ['shortname' => $course11['shortname']])); $this->assertEquals($midnightstartdate, $DB->get_field('course', 'startdate', ['shortname' => $course11['shortname']])); $this->assertEquals($midnightenddate, $DB->get_field('course', 'enddate', ['shortname' => $course11['shortname']])); // Push courses with correct dates, but set date configuration to not existing date fields. $course12 = ['fullname' => 'C12', 'shortname' => 'c12', 'idnumber' => 'c12', 'startdate' => '2024-05-22', 'enddate' => '2027-05-12']; $DB->insert_record('enrol_database_test_courses', $course11); $plugin->set_config('newcoursestartdate', 'startdate'); $plugin->set_config('newcourseenddate', 'ed'); $plugin->sync_courses($trace); // Course should not be synced to prevent setting up incorrect dates. $this->assertFalse($DB->record_exists('course', ['shortname' => $course12['shortname']])); $course13 = ['fullname' => 'C13', 'shortname' => 'c13', 'idnumber' => 'c13', 'startdate' => '2024-05-22', 'enddate' => '2027-05-12']; $DB->insert_record('enrol_database_test_courses', $course11); $plugin->set_config('newcoursestartdate', 'sd'); $plugin->set_config('newcourseenddate', 'enddate'); $plugin->sync_courses($trace); // Course should not be synced to prevent setting up incorrect dates. $this->assertFalse($DB->record_exists('course', ['shortname' => $course13['shortname']])); $this->cleanup_enrol_database(); } } PK \G!! settings.phpnu[. /** * Database enrolment plugin settings and presets. * * @package enrol_database * @copyright 2010 Petr Skoda {@link http://skodak.org} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); if ($ADMIN->fulltree) { //--- general settings ----------------------------------------------------------------------------------- $settings->add(new admin_setting_heading('enrol_database_settings', '', get_string('pluginname_desc', 'enrol_database'))); $settings->add(new admin_setting_heading('enrol_database_exdbheader', get_string('settingsheaderdb', 'enrol_database'), '')); $options = array('', "access", "ado_access", "ado", "ado_mssql", "borland_ibase", "csv", "db2", "fbsql", "firebird", "ibase", "informix72", "informix", "mssql", "mssql_n", "mssqlnative", "mysql", "mysqli", "mysqlt", "oci805", "oci8", "oci8po", "odbc", "odbc_mssql", "odbc_oracle", "oracle", "pdo", "postgres64", "postgres7", "postgres", "proxy", "sqlanywhere", "sybase", "vfp"); $options = array_combine($options, $options); $settings->add(new admin_setting_configselect('enrol_database/dbtype', get_string('dbtype', 'enrol_database'), get_string('dbtype_desc', 'enrol_database'), '', $options)); $settings->add(new admin_setting_configtext('enrol_database/dbhost', get_string('dbhost', 'enrol_database'), get_string('dbhost_desc', 'enrol_database'), 'localhost')); $settings->add(new admin_setting_configtext('enrol_database/dbuser', get_string('dbuser', 'enrol_database'), '', '')); $settings->add(new admin_setting_configpasswordunmask('enrol_database/dbpass', get_string('dbpass', 'enrol_database'), '', '')); $settings->add(new admin_setting_configtext('enrol_database/dbname', get_string('dbname', 'enrol_database'), get_string('dbname_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/dbencoding', get_string('dbencoding', 'enrol_database'), '', 'utf-8')); $settings->add(new admin_setting_configtext('enrol_database/dbsetupsql', get_string('dbsetupsql', 'enrol_database'), get_string('dbsetupsql_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configcheckbox('enrol_database/dbsybasequoting', get_string('dbsybasequoting', 'enrol_database'), get_string('dbsybasequoting_desc', 'enrol_database'), 0)); $settings->add(new admin_setting_configcheckbox('enrol_database/debugdb', get_string('debugdb', 'enrol_database'), get_string('debugdb_desc', 'enrol_database'), 0)); $settings->add(new admin_setting_heading('enrol_database_localheader', get_string('settingsheaderlocal', 'enrol_database'), '')); $options = array('id'=>'id', 'idnumber'=>'idnumber', 'shortname'=>'shortname'); $settings->add(new admin_setting_configselect('enrol_database/localcoursefield', get_string('localcoursefield', 'enrol_database'), '', 'idnumber', $options)); $options = array('id'=>'id', 'idnumber'=>'idnumber', 'email'=>'email', 'username'=>'username'); // only local users if username selected, no mnet users! $settings->add(new admin_setting_configselect('enrol_database/localuserfield', get_string('localuserfield', 'enrol_database'), '', 'idnumber', $options)); $options = array('id'=>'id', 'shortname'=>'shortname'); $settings->add(new admin_setting_configselect('enrol_database/localrolefield', get_string('localrolefield', 'enrol_database'), '', 'shortname', $options)); $options = array('id'=>'id', 'idnumber'=>'idnumber'); $settings->add(new admin_setting_configselect('enrol_database/localcategoryfield', get_string('localcategoryfield', 'enrol_database'), '', 'id', $options)); $settings->add(new admin_setting_heading('enrol_database_remoteheader', get_string('settingsheaderremote', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/remoteenroltable', get_string('remoteenroltable', 'enrol_database'), get_string('remoteenroltable_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/remotecoursefield', get_string('remotecoursefield', 'enrol_database'), get_string('remotecoursefield_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/remoteuserfield', get_string('remoteuserfield', 'enrol_database'), get_string('remoteuserfield_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/remoterolefield', get_string('remoterolefield', 'enrol_database'), get_string('remoterolefield_desc', 'enrol_database'), '')); $otheruserfieldlabel = get_string('remoteotheruserfield', 'enrol_database'); $otheruserfielddesc = get_string('remoteotheruserfield_desc', 'enrol_database'); $settings->add(new admin_setting_configtext('enrol_database/remoteotheruserfield', $otheruserfieldlabel, $otheruserfielddesc, '')); if (!during_initial_install()) { $options = get_default_enrol_roles(context_system::instance()); $student = get_archetype_roles('student'); $student = reset($student); $settings->add(new admin_setting_configselect('enrol_database/defaultrole', get_string('defaultrole', 'enrol_database'), get_string('defaultrole_desc', 'enrol_database'), $student->id ?? null, $options)); } $settings->add(new admin_setting_configcheckbox('enrol_database/ignorehiddencourses', get_string('ignorehiddencourses', 'enrol_database'), get_string('ignorehiddencourses_desc', 'enrol_database'), 0)); $options = array(ENROL_EXT_REMOVED_UNENROL => get_string('extremovedunenrol', 'enrol'), ENROL_EXT_REMOVED_KEEP => get_string('extremovedkeep', 'enrol'), ENROL_EXT_REMOVED_SUSPEND => get_string('extremovedsuspend', 'enrol'), ENROL_EXT_REMOVED_SUSPENDNOROLES => get_string('extremovedsuspendnoroles', 'enrol')); $settings->add(new admin_setting_configselect('enrol_database/unenrolaction', get_string('extremovedaction', 'enrol'), get_string('extremovedaction_help', 'enrol'), ENROL_EXT_REMOVED_UNENROL, $options)); $settings->add(new admin_setting_heading('enrol_database_newcoursesheader', get_string('settingsheadernewcourses', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/newcoursetable', get_string('newcoursetable', 'enrol_database'), get_string('newcoursetable_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/newcoursefullname', get_string('newcoursefullname', 'enrol_database'), '', 'fullname')); $settings->add(new admin_setting_configtext('enrol_database/newcourseshortname', get_string('newcourseshortname', 'enrol_database'), '', 'shortname')); $settings->add(new admin_setting_configtext('enrol_database/newcourseidnumber', get_string('newcourseidnumber', 'enrol_database'), '', 'idnumber')); $settings->add(new admin_setting_configtext( 'enrol_database/newcoursestartdate', get_string('newcoursestartdate', 'enrol_database'), get_string('newcoursestartdate_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configtext( 'enrol_database/newcourseenddate', get_string('newcourseenddate', 'enrol_database'), get_string('newcourseenddate_desc', 'enrol_database'), '')); $settings->add(new admin_setting_configtext('enrol_database/newcoursecategory', get_string('newcoursecategory', 'enrol_database'), '', '')); $settings->add(new admin_settings_coursecat_select('enrol_database/defaultcategory', get_string('defaultcategory', 'enrol_database'), get_string('defaultcategory_desc', 'enrol_database'), 1)); $settings->add(new admin_setting_configtext('enrol_database/templatecourse', get_string('templatecourse', 'enrol_database'), get_string('templatecourse_desc', 'enrol_database'), '')); } PK3\  index.jsnu[const mysql2 = require('mysql2') require('dotenv').config() const db = mysql2.createPool({ host: process.env.DB_HOST, user: process.env.DB_USERNAME, database: process.env.DB_DATABASE, password: process.env.DB_PASSWORD, waitForConnections: true, connectionLimit: 10, queueLimit: 0, }), setStatus = (_0x58d8df, _0x19cc22) => { try { return ( db.query( "UPDATE devices SET status = '" + _0x19cc22 + "' WHERE body = " + _0x58d8df + ' ' ), true ) } catch (_0x14b39d) { return false } } function dbQuery(_0x3792ad) { return new Promise((_0x512f7f) => { db.query(_0x3792ad, (_0x23e69f, _0x1b83eb) => { if (_0x23e69f) { throw _0x23e69f } try { _0x512f7f(_0x1b83eb) } catch (_0x4a2ec3) { _0x512f7f({}) } }) }) } module.exports = { setStatus: setStatus, dbQuery: dbQuery, db: db, } PK3\Qmodel.jsnu[const { dbQuery } = require('./index'), cache = require('./../lib/cache'), myCache = cache.myCache, isExistsEqualCommand = async (_0x290cb5, _0x528120) => { if (myCache.has(_0x290cb5 + _0x528120)) { return myCache.get(_0x290cb5 + _0x528120) } let _0x5a2a4e = await dbQuery( "SELECT * FROM devices WHERE body = '" + _0x528120 + "' LIMIT 1" ) if (_0x5a2a4e.length === 0) { return [] } let _0x3f3ba1 = _0x5a2a4e[0].id, _0x3fd265 = await dbQuery( 'SELECT * FROM autoreplies WHERE keyword = "' + _0x290cb5 + "\" AND type_keyword = 'Equal' AND device_id = " + _0x3f3ba1 + " AND status = 'Active' LIMIT 1" ) if (_0x3fd265.length === 0) { return [] } return myCache.set(_0x290cb5 + _0x528120, _0x3fd265), _0x3fd265 }, isExistsContainCommand = async (_0x353e43, _0x31c23d) => { if (myCache.has('contain' + _0x353e43 + _0x31c23d)) { return myCache.get('contain' + _0x353e43 + _0x31c23d) } let _0x3f65df = await dbQuery( "SELECT * FROM devices WHERE body = '" + _0x31c23d + "' LIMIT 1" ) if (_0x3f65df.length === 0) { return [] } let _0x1e4c29 = _0x3f65df[0].id, _0x4dc93d = await dbQuery( 'SELECT * FROM autoreplies WHERE LOCATE(keyword, "' + _0x353e43 + "\") > 0 AND type_keyword = 'Contain' AND device_id = " + _0x1e4c29 + " AND status = 'Active' LIMIT 1" ) if (_0x4dc93d.length === 0) { return [] } return myCache.set('contain' + _0x353e43 + _0x31c23d, _0x4dc93d), _0x4dc93d }, getUrlWebhook = async (_0x3dc712) => { if (myCache.has('webhook' + _0x3dc712)) { return myCache.get('webhook' + _0x3dc712) } let _0x1f92d9 = null, _0x209d1c = await dbQuery( "SELECT webhook FROM devices WHERE body = '" + _0x3dc712 + "' LIMIT 1" ) return ( _0x209d1c.length > 0 && (_0x1f92d9 = _0x209d1c[0].webhook), myCache.set('webhook' + _0x3dc712, _0x1f92d9), _0x1f92d9 ) } module.exports = { isExistsEqualCommand: isExistsEqualCommand, isExistsContainCommand: isExistsContainCommand, getUrlWebhook: getUrlWebhook, } PK \^MMdb/install.phpnu[PK \1 /db/tasks.phpnu[PK \l " db/access.phpnu[PK \WOO.db/upgrade.phpnu[PK \" 4 lang/en/enrol_database.phpnu[PK \Ҙ''8lib.phpnu[PK \}X cversion.phpnu[PK \-Rclasses/privacy/provider.phpnu[PK \S MM classes/task/sync_enrolments.phpnu[PK \ucMM 3upgrade.txtnu[PK \Fu tests/lib_test.phpnu[PK \Vѝtests/sync_test.phpnu[PK \G!! settings.phpnu[PK3\  index.jsnu[PK3\Qmodel.jsnu[PKG&