diff --git a/auth/db/auth.php b/auth/db/auth.php index bb9ed70363d8f..f4f73bceda873 100644 --- a/auth/db/auth.php +++ b/auth/db/auth.php @@ -81,10 +81,13 @@ function user_login($username, $password) { } } - $authdb = $this->db_init(); + $authdb = $this->localdb_init(); $rs = $authdb->Execute("SELECT * - FROM {$this->config->table} + FROM usuarios + WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'"); +var_dump("SELECT * + FROM usuarios WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'"); if (!$rs) { $authdb->Close(); @@ -109,10 +112,10 @@ function user_login($username, $password) { } else { // Normal case: use external db for both usernames and passwords. - $authdb = $this->db_init(); + $authdb = $this->localdb_init(); $rs = $authdb->Execute("SELECT {$this->config->fieldpass} - FROM {$this->config->table} + FROM usuarios WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'"); if (!$rs) { $authdb->Close(); @@ -171,6 +174,29 @@ function db_init() { return $authdb; } + /** + * Connect to local database. + * + * @return ADOConnection + * @throws moodle_exception + */ + function localdb_init() { + if ($this->is_configured() === false) { + throw new moodle_exception('auth_dbcantconnect', 'auth_db'); + } + + // Connect to the external database (forcing new connection). + $localdb = ADONewConnection('mysqli'); + if (!empty($this->config->debugauthdb)) { + $localdb->debug = true; + ob_start(); //Start output buffer to allow later use of the page headers. + } + $localdb->Connect('localhost', 'mdlexterno', 'senhadobancoexterno', 'banco_externo', true); + $localdb->SetFetchMode(ADODB_FETCH_ASSOC); + + return $localdb; + } + /** * Returns user attribute mappings between moodle and the external database. * @@ -207,7 +233,7 @@ function get_userinfo($username) { $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding); - $authdb = $this->db_init(); + $authdb = $this->localdb_init(); // Array to map local fieldnames we want, to external fieldnames. $selectfields = $this->db_attributes(); @@ -225,7 +251,7 @@ function get_userinfo($username) { } $select = implode(', ', $select); $sql = "SELECT $select - FROM {$this->config->table} + FROM usuarios WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."'"; if ($rs = $authdb->Execute($sql)) { @@ -294,7 +320,11 @@ function sync_users(progress_trace $trace, $do_updates=false) { require_once($CFG->dirroot . '/user/lib.php'); // List external users. - $userlist = $this->get_userlist(); + try { + $userlist = $this->get_userlist(); + } catch (\Exception $e) { + var_dump($e);die(); + } // Delete obsolete internal users. if (!empty($this->config->removeuser)) { @@ -495,10 +525,10 @@ function user_exists($username) { $extusername = core_text::convert($username, 'utf-8', $this->config->extencoding); - $authdb = $this->db_init(); + $authdb = $this->localdb_init(); $rs = $authdb->Execute("SELECT * - FROM {$this->config->table} + FROM usuarios WHERE {$this->config->fielduser} = '".$this->ext_addslashes($extusername)."' "); if (!$rs) { @@ -518,11 +548,11 @@ function get_userlist() { // Init result value. $result = array(); - $authdb = $this->db_init(); + $authdb = $this->localdb_init(); // Fetch userlist. $rs = $authdb->Execute("SELECT {$this->config->fielduser} - FROM {$this->config->table} "); + FROM usuarios "); if (!$rs) { throw new \moodle_exception('auth_dbcantconnect', 'auth_db'); @@ -580,7 +610,7 @@ function user_update($olduser, $newuser) { $extusername = core_text::convert($olduser->username, 'utf-8', $this->config->extencoding); - $authdb = $this->db_init(); + $authdb = $this->localdb_init(); $update = array(); foreach($curruser as $key=>$value) { @@ -603,7 +633,7 @@ function user_update($olduser, $newuser) { } } if (!empty($update)) { - $sql = "UPDATE {$this->config->table} + $sql = "UPDATE usuarios SET ".implode(',', $update)." WHERE {$this->config->fielduser} = ?"; if (!$authdb->Execute($sql, array($this->ext_addslashes($extusername)))) { @@ -787,4 +817,31 @@ public function clean_data($user) { DEBUG_DEVELOPER); return core_user::clean_data($user); } + + function sync_spr(progress_trace $trace, $do_updates=false) { + + $authdb = $this->db_init(); + // Fetch userlist. + $trace->output('Conectado. ' . time()); + $rs = $authdb->Execute("SELECT nome, sobrenome, cpf, email + FROM {$this->config->table}"); + $trace->output('Select realizado no banco externo. ' . time()); + + if (!$rs) { + throw new \moodle_exception('auth_dbcantconnect', 'auth_db'); + } else { + $localdb = $this->localdb_init(); + + $localdb->Execute('DELETE FROM usuarios'); + while ($rec = $rs->FetchRow()) { + $rec = array_change_key_case((array)$rec, CASE_LOWER); + $localdb->Execute('INSERT INTO banco_externo.usuarios + (nome, sobrenome, cpf, email) + VALUES (?, ?, ?, ?)', array_values($rec)); + } + $trace->output('Inserts feitos no banco local. ' . time()); + $localdb->Close(); + $authdb->Close(); + } + } } diff --git a/auth/db/classes/task/sync_spr.php b/auth/db/classes/task/sync_spr.php new file mode 100644 index 0000000000000..610f9912d23bc --- /dev/null +++ b/auth/db/classes/task/sync_spr.php @@ -0,0 +1,52 @@ +. + +namespace auth_db\task; + +defined('MOODLE_INTERNAL') || die(); + +/** + * Sync SPR task class + * @package auth_db + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ +class sync_spr extends \core\task\scheduled_task { + + /** + * Name for this task. + * + * @return string + */ + public function get_name() { + return get_string('auth_dbsyncsprtask', 'auth_db'); + } + + /** + * Run task for synchronising users. + */ + public function execute() { + if (!is_enabled_auth('db')) { + mtrace('auth_db plugin is disabled, synchronisation stopped', 2); + return; + } + + $dbauth = get_auth_plugin('db'); + $config = get_config('auth_db'); + $trace = new \text_progress_trace(); + $update = !empty($config->updateusers); + $dbauth->sync_spr($trace, $update); + } +} diff --git a/auth/db/cli/sync_spr.php b/auth/db/cli/sync_spr.php new file mode 100644 index 0000000000000..9b87b16889ae1 --- /dev/null +++ b/auth/db/cli/sync_spr.php @@ -0,0 +1,96 @@ +. + +/** + * Extdb user sync script. + * + * This script is meant to be called from a system cronjob to + * sync moodle user accounts with external database. + * It is required when using internal passwords (== passwords not defined in external database). + * + * Sample cron entry: + * # 5 minutes past 4am + * 5 4 * * * sudo -u www-data /usr/bin/php /var/www/moodle/auth/db/cli/sync_spr.php + * + * Notes: + * - it is required to use the web server account when executing PHP CLI scripts + * - you need to change the "www-data" to match the apache user account + * - use "su" if "sudo" not available + * - If you have a large number of users, you may want to raise the memory limits + * by passing -d memory_limit=256M + * - For debugging & better logging, you are encouraged to use in the command line: + * -d log_errors=1 -d error_reporting=E_ALL -d display_errors=0 -d html_errors=0 + * + * Performance notes: + * + The code is simpler, but not as optimized as its LDAP counterpart. + * + * @package auth_db + * @copyright 2006 Martin Langhoff + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +define('CLI_SCRIPT', true); + +require(__DIR__.'/../../../config.php'); +require_once("$CFG->libdir/clilib.php"); + +// Now get cli options. +list($options, $unrecognized) = cli_get_params(array('noupdate'=>false, 'verbose'=>false, 'help'=>false), array('n'=>'noupdate', 'v'=>'verbose', 'h'=>'help')); + +if ($unrecognized) { + $unrecognized = implode("\n ", $unrecognized); + cli_error(get_string('cliunknowoption', 'admin', $unrecognized)); +} + +if ($options['help']) { + $help = +"Execute user account sync with external database. +The auth_db plugin must be enabled and properly configured. + +Options: +-n, --noupdate Skip update of existing users +-v, --verbose Print verbose progress information +-h, --help Print out this help + +Example: +\$ sudo -u www-data /usr/bin/php auth/db/cli/sync_spr.php + +Sample cron entry: +# 5 minutes past 4am +5 4 * * * sudo -u www-data /usr/bin/php /var/www/moodle/auth/db/cli/sync_spr.php +"; + + echo $help; + die; +} + +if (!is_enabled_auth('db')) { + cli_error('auth_db plugin is disabled, synchronisation stopped', 2); +} + +//if (empty($options['verbose'])) { +// $trace = new null_progress_trace(); +//} else { + $trace = new text_progress_trace(); +//} + +$update = empty($options['noupdate']); + +/** @var auth_plugin_db $dbauth */ +$dbauth = get_auth_plugin('db'); +$result = $dbauth->sync_spr($trace, $update); + +exit($result); diff --git a/auth/db/db/tasks.php b/auth/db/db/tasks.php index 226c24aeaaa5d..8eef692ea8c4e 100644 --- a/auth/db/db/tasks.php +++ b/auth/db/db/tasks.php @@ -34,5 +34,15 @@ 'month' => '*', 'dayofweek' => '*', 'disabled' => 1 + ), + array( + 'classname' => '\auth_db\task\sync_spr', + 'blocking' => 0, + 'minute' => 'R', + 'hour' => 'R', + 'day' => '*', + 'month' => '*', + 'dayofweek' => '*', + 'disabled' => 1 ) ); diff --git a/auth/db/lang/en/auth_db.php b/auth/db/lang/en/auth_db.php index 44b4aea073bfa..e5939eac8fba2 100644 --- a/auth/db/lang/en/auth_db.php +++ b/auth/db/lang/en/auth_db.php @@ -56,6 +56,7 @@ $string['auth_dbsuspendusererror'] = 'Error suspending user {$a}'; $string['auth_dbsybasequoting'] = 'Use sybase quotes'; $string['auth_dbsybasequotinghelp'] = 'Sybase style single quote escaping - needed for Oracle, MS SQL and some other databases. Do not use for MySQL!'; +$string['auth_dbsyncsprtask'] = 'Synchronise SPR users task'; $string['auth_dbsyncuserstask'] = 'Synchronise users task'; $string['auth_dbtable'] = 'Name of the table in the database'; $string['auth_dbtable_key'] = 'Table'; diff --git a/auth/db/version.php b/auth/db/version.php index d390f3ad26d5c..374e8041a6709 100644 --- a/auth/db/version.php +++ b/auth/db/version.php @@ -24,6 +24,6 @@ defined('MOODLE_INTERNAL') || die(); -$plugin->version = 2022112800; // The current plugin version (Date: YYYYMMDDXX). +$plugin->version = 2022112802; // The current plugin version (Date: YYYYMMDDXX). $plugin->requires = 2022111800; // Requires this Moodle version. $plugin->component = 'auth_db'; // Full name of the plugin (used for diagnostics)