/**
  * Test are_notification_preferences_configured
  */
 public function test_are_notification_preferences_configured()
 {
     $this->resetAfterTest(true);
     $user1 = self::getDataGenerator()->create_user();
     $user2 = self::getDataGenerator()->create_user();
     $user3 = self::getDataGenerator()->create_user();
     self::setUser($user1);
     set_user_preference('message_provider_moodle_instantmessage_loggedin', 'airnotifier', $user1);
     set_user_preference('message_provider_moodle_instantmessage_loggedoff', 'airnotifier', $user1);
     set_user_preference('message_provider_moodle_instantmessage_loggedin', 'airnotifier', $user2);
     set_user_preference('message_provider_moodle_instantmessage_loggedin', 'airnotifier', $user3);
     $params = array($user1->id, $user2->id, $user3->id);
     $preferences = message_airnotifier_external::are_notification_preferences_configured($params);
     $expected = array(array('userid' => $user1->id, 'configured' => 1));
     $this->assertEquals(1, count($preferences['users']));
     $this->assertEquals($expected, $preferences['users']);
     $this->assertEquals(2, count($preferences['warnings']));
     // Now, remove one user.
     delete_user($user2);
     $preferences = message_airnotifier_external::are_notification_preferences_configured($params);
     $this->assertEquals(1, count($preferences['users']));
     $this->assertEquals($expected, $preferences['users']);
     $this->assertEquals(2, count($preferences['warnings']));
     // Now, remove one user1 preference (the user still has one prefernce for airnotifier).
     unset_user_preference('message_provider_moodle_instantmessage_loggedin', $user1);
     $preferences = message_airnotifier_external::are_notification_preferences_configured($params);
     $this->assertEquals($expected, $preferences['users']);
     // Delete the last user1 preference.
     unset_user_preference('message_provider_moodle_instantmessage_loggedoff', $user1);
     $preferences = message_airnotifier_external::are_notification_preferences_configured($params);
     $expected = array(array('userid' => $user1->id, 'configured' => 0));
     $this->assertEquals($expected, $preferences['users']);
 }
Ejemplo n.º 2
0
function admin_test_main()
{
    // Create user
    echo '<br><h3>Creating User.</h3><br>';
    $user_1 = user_1();
    user\add_user($user_1);
    echo '<br><h3>User created!</h3><br>';
    // Verify
    $user_1_db = user\authenticate_user($user_1['email_address'], $user_1['password']);
    $user_1_id = $user_1_db['id'];
    echo "<br><h3>User ID: {$user_1_id}</h3><br>";
    // Update user
    echo "<br><h3>Updating User.</h3><br>";
    $user_1_db['email_address'] = '*****@*****.**';
    $user_1_db['last_name'] = 'Two';
    update_user($user_1_db);
    echo "<br><h3>User Updated!</h3><br>";
    // Verify
    $user_2_db = user\authenticate_user('*****@*****.**', $user_1['password']);
    $new_last_name = $user_2_db['last_name'];
    echo "<br><h3>New User Last Name: {$user_2_db}";
    // Delete user
    echo "<br><h3>Deleting User.</h3><br>";
    delete_user(array("user_id" => $user_1_id));
    echo "<br><h3>User deleted!</h3><br>";
}
Ejemplo n.º 3
0
 public function tearDown()
 {
     global $DB;
     if ($user = $DB->get_record('user', array('username' => 'simpletest'))) {
         delete_user($user);
         $DB->delete_records('user', array('id' => $user->id));
     }
 }
Ejemplo n.º 4
0
function delete_teacher($id)
{
    $teacher = get_userdata($id);
    if ($teacher->type != 'teacher') {
        return false;
    }
    delete_user($id);
}
Ejemplo n.º 5
0
function account_delete_submit(Pieform $form, $values)
{
    global $SESSION, $USER;
    $userid = $USER->get('id');
    $USER->logout();
    delete_user($userid);
    $SESSION->add_ok_msg(get_string('accountdeleted', 'account'));
    redirect('/index.php');
}
Ejemplo n.º 6
0
function buttons_submit_delete(Pieform $form, $values)
{
    global $SESSION;
    $ids = get_user_ids_from_post();
    foreach ($ids as $userid) {
        delete_user($userid);
    }
    $SESSION->add_ok_msg(get_string('usersdeletedsuccessfully', 'admin'));
    redirect('/admin/users/suspended.php');
}
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG, $DB;
     $timenow = time();
     // Delete users who haven't completed profile within required period.
     if (!empty($CFG->deleteincompleteusers)) {
         $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
         $rs = $DB->get_recordset_sql("SELECT *\n                                               FROM {user}\n                                           WHERE confirmed = 1 AND lastaccess > 0\n                                               AND lastaccess < ? AND deleted = 0\n                                               AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
         foreach ($rs as $user) {
             if (isguestuser($user) or is_siteadmin($user)) {
                 continue;
             }
             delete_user($user);
             mtrace(" Deleted not fully setup user {$user->username} ({$user->id})");
         }
         $rs->close();
     }
 }
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $CFG, $DB;
     $timenow = time();
     // Delete users who haven't confirmed within required period.
     if (!empty($CFG->deleteunconfirmed)) {
         $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
         $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ? AND deleted = 0", array($cuttime));
         foreach ($rs as $user) {
             delete_user($user);
             // We MUST delete user properly first.
             $DB->delete_records('user', array('id' => $user->id));
             // This is a bloody hack, but it might work.
             mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
         }
         $rs->close();
     }
 }
Ejemplo n.º 9
0
function possibly_delete_user($user)
{
    if ($user->total_credit > 0.0) {
        admin_error_page("Cannot delete user: User has credit.");
    }
    // Don't delete user if they have any outstanding Results
    //
    if (BoincResult::count("userid={$user->id}")) {
        admin_error_page("Cannot delete user: User has count results in the database.");
    }
    // Don't delete user if they have posted to the forums
    //
    if (BoincPost::count("user={$user->id}")) {
        admin_error_page("Cannot delete user: User has forum posts.");
    }
    if ($user->teamid) {
        user_quit_team($user);
    }
    delete_user($user);
}
Ejemplo n.º 10
0
     }
 }
 // delete user
 if (!empty($user->deleted)) {
     if (!$allowdeletes) {
         $usersskipped++;
         $upt->track('status', $strusernotdeletedoff, 'warning');
         continue;
     }
     if ($existinguser) {
         if (is_siteadmin($existinguser->id)) {
             $upt->track('status', $strusernotdeletedadmin, 'error');
             $deleteerrors++;
             continue;
         }
         if (delete_user($existinguser)) {
             $upt->track('status', $struserdeleted);
             $deletes++;
         } else {
             $upt->track('status', $strusernotdeletederror, 'error');
             $deleteerrors++;
         }
     } else {
         $upt->track('status', $strusernotdeletedmissing, 'error');
         $deleteerrors++;
     }
     continue;
 }
 // we do not need the deleted flag anymore
 unset($user->deleted);
 // renaming requested?
Ejemplo n.º 11
0
    mysql_query($sql, $db);
    write_to_log(AT_ADMIN_LOG_DELETE, 'users_online', mysql_affected_rows($db), $sql);
    $sql = "DELETE FROM " . TABLE_PREFIX . "members WHERE member_id={$id}";
    mysql_query($sql, $db);
    write_to_log(AT_ADMIN_LOG_DELETE, 'members', mysql_affected_rows($db), $sql);
    $sql = "DELETE FROM " . TABLE_PREFIX . "member_track WHERE member_id={$id}";
    mysql_query($sql, $db);
    write_to_log(AT_ADMIN_LOG_DELETE, 'member_track', mysql_affected_rows($db), $sql);
    // delete personal files from file storage
    fs_delete_workspace(WORKSPACE_PERSONAL, $id);
    return;
}
$ids = explode(',', $_REQUEST['id']);
if (isset($_POST['submit_yes'])) {
    foreach ($ids as $id) {
        delete_user(intval($id));
    }
    $msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
    if (isset($_POST['ml']) && $_REQUEST['ml']) {
        header('Location: ' . AT_BASE_HREF . 'mods/_core/users/master_list.php');
    } else {
        header('Location: ' . AT_BASE_HREF . 'mods/_core/users/users.php');
    }
    exit;
} else {
    if (isset($_POST['submit_no'])) {
        $msg->addFeedback('CANCELLED');
        if (isset($_POST['ml']) && $_REQUEST['ml']) {
            header('Location: ' . AT_BASE_HREF . 'mods/_core/users/master_list.php');
        } else {
            header('Location: ' . AT_BASE_HREF . 'mods/_core/users/users.php');
Ejemplo n.º 12
0
/**
 * Execute cron tasks
 */
function cron_run()
{
    global $DB, $CFG, $OUTPUT;
    if (CLI_MAINTENANCE) {
        echo "CLI maintenance mode active, cron execution suspended.\n";
        exit(1);
    }
    if (moodle_needs_upgrading()) {
        echo "Moodle upgrade pending, cron execution suspended.\n";
        exit(1);
    }
    require_once $CFG->libdir . '/adminlib.php';
    require_once $CFG->libdir . '/gradelib.php';
    if (!empty($CFG->showcronsql)) {
        $DB->set_debug(true);
    }
    if (!empty($CFG->showcrondebugging)) {
        set_debugging(DEBUG_DEVELOPER, true);
    }
    set_time_limit(0);
    $starttime = microtime();
    // Increase memory limit
    raise_memory_limit(MEMORY_EXTRA);
    // Emulate normal session - we use admin accoutn by default
    cron_setup_user();
    // Start output log
    $timenow = time();
    mtrace("Server Time: " . date('r', $timenow) . "\n\n");
    // Run cleanup core cron jobs, but not every time since they aren't too important.
    // These don't have a timer to reduce load, so we'll use a random number
    // to randomly choose the percentage of times we should run these jobs.
    $random100 = rand(0, 100);
    if ($random100 < 20) {
        // Approximately 20% of the time.
        mtrace("Running clean-up tasks...");
        cron_trace_time_and_memory();
        // Delete users who haven't confirmed within required period
        if (!empty($CFG->deleteunconfirmed)) {
            $cuttime = $timenow - $CFG->deleteunconfirmed * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 0 AND firstaccess > 0\n                                                  AND firstaccess < ?", array($cuttime));
            foreach ($rs as $user) {
                delete_user($user);
                // we MUST delete user properly first
                $DB->delete_records('user', array('id' => $user->id));
                // this is a bloody hack, but it might work
                mtrace(" Deleted unconfirmed user for " . fullname($user, true) . " ({$user->id})");
            }
            $rs->close();
        }
        // Delete users who haven't completed profile within required period
        if (!empty($CFG->deleteincompleteusers)) {
            $cuttime = $timenow - $CFG->deleteincompleteusers * 3600;
            $rs = $DB->get_recordset_sql("SELECT *\n                                             FROM {user}\n                                            WHERE confirmed = 1 AND lastaccess > 0\n                                                  AND lastaccess < ? AND deleted = 0\n                                                  AND (lastname = '' OR firstname = '' OR email = '')", array($cuttime));
            foreach ($rs as $user) {
                if (isguestuser($user) or is_siteadmin($user)) {
                    continue;
                }
                delete_user($user);
                mtrace(" Deleted not fully setup user {$user->username} ({$user->id})");
            }
            $rs->close();
        }
        // Delete old logs to save space (this might need a timer to slow it down...)
        if (!empty($CFG->loglifetime)) {
            // value in days
            $loglifetime = $timenow - $CFG->loglifetime * 3600 * 24;
            $DB->delete_records_select("log", "time < ?", array($loglifetime));
            mtrace(" Deleted old log records");
        }
        // Delete old backup_controllers and logs.
        $loglifetime = get_config('backup', 'loglifetime');
        if (!empty($loglifetime)) {
            // Value in days.
            $loglifetime = $timenow - $loglifetime * 3600 * 24;
            // Delete child records from backup_logs.
            $DB->execute("DELETE FROM {backup_logs}\n                           WHERE EXISTS (\n                               SELECT 'x'\n                                 FROM {backup_controllers} bc\n                                WHERE bc.backupid = {backup_logs}.backupid\n                                  AND bc.timecreated < ?)", array($loglifetime));
            // Delete records from backup_controllers.
            $DB->execute("DELETE FROM {backup_controllers}\n                          WHERE timecreated < ?", array($loglifetime));
            mtrace(" Deleted old backup records");
        }
        // Delete old cached texts
        if (!empty($CFG->cachetext)) {
            // Defined in config.php
            $cachelifetime = time() - $CFG->cachetext - 60;
            // Add an extra minute to allow for really heavy sites
            $DB->delete_records_select('cache_text', "timemodified < ?", array($cachelifetime));
            mtrace(" Deleted old cache_text records");
        }
        if (!empty($CFG->usetags)) {
            require_once $CFG->dirroot . '/tag/lib.php';
            tag_cron();
            mtrace(' Executed tag cron');
        }
        // Context maintenance stuff
        context_helper::cleanup_instances();
        mtrace(' Cleaned up context instances');
        context_helper::build_all_paths(false);
        // If you suspect that the context paths are somehow corrupt
        // replace the line below with: context_helper::build_all_paths(true);
        mtrace(' Built context paths');
        // Remove expired cache flags
        gc_cache_flags();
        mtrace(' Cleaned cache flags');
        // Cleanup messaging
        if (!empty($CFG->messagingdeletereadnotificationsdelay)) {
            $notificationdeletetime = time() - $CFG->messagingdeletereadnotificationsdelay;
            $DB->delete_records_select('message_read', 'notification=1 AND timeread<:notificationdeletetime', array('notificationdeletetime' => $notificationdeletetime));
            mtrace(' Cleaned up read notifications');
        }
        mtrace(' Deleting temporary files...');
        cron_delete_from_temp();
        // Cleanup user password reset records
        // Delete any reset request records which are expired by more than a day.
        // (We keep recently expired requests around so we can give a different error msg to users who
        // are trying to user a recently expired reset attempt).
        $pwresettime = isset($CFG->pwresettime) ? $CFG->pwresettime : 1800;
        $earliestvalid = time() - $pwresettime - DAYSECS;
        $DB->delete_records_select('user_password_resets', "timerequested < ?", array($earliestvalid));
        mtrace(' Cleaned up old password reset records');
        mtrace("...finished clean-up tasks");
    }
    // End of occasional clean-up tasks
    // Send login failures notification - brute force protection in moodle is weak,
    // we should at least send notices early in each cron execution
    if (notify_login_failures()) {
        mtrace(' Notified login failures');
    }
    // Make sure all context instances are properly created - they may be required in auth, enrol, etc.
    context_helper::create_instances();
    mtrace(' Created missing context instances');
    // Session gc.
    mtrace("Running session gc tasks...");
    \core\session\manager::gc();
    mtrace("...finished stale session cleanup");
    // Run the auth cron, if any before enrolments
    // because it might add users that will be needed in enrol plugins
    $auths = get_enabled_auth_plugins();
    mtrace("Running auth crons if required...");
    cron_trace_time_and_memory();
    foreach ($auths as $auth) {
        $authplugin = get_auth_plugin($auth);
        if (method_exists($authplugin, 'cron')) {
            mtrace("Running cron for auth/{$auth}...");
            $authplugin->cron();
            if (!empty($authplugin->log)) {
                mtrace($authplugin->log);
            }
        }
        unset($authplugin);
    }
    // Generate new password emails for users - ppl expect these generated asap
    if ($DB->count_records('user_preferences', array('name' => 'create_password', 'value' => '1'))) {
        mtrace('Creating passwords for new users...');
        $usernamefields = get_all_user_name_fields(true, 'u');
        $newusers = $DB->get_recordset_sql("SELECT u.id as id, u.email,\n                                                 {$usernamefields}, u.username, u.lang,\n                                                 p.id as prefid\n                                            FROM {user} u\n                                            JOIN {user_preferences} p ON u.id=p.userid\n                                           WHERE p.name='create_password' AND p.value='1' AND u.email !='' AND u.suspended = 0 AND u.auth != 'nologin' AND u.deleted = 0");
        // note: we can not send emails to suspended accounts
        foreach ($newusers as $newuser) {
            // Use a low cost factor when generating bcrypt hash otherwise
            // hashing would be slow when emailing lots of users. Hashes
            // will be automatically updated to a higher cost factor the first
            // time the user logs in.
            if (setnew_password_and_mail($newuser, true)) {
                unset_user_preference('create_password', $newuser);
                set_user_preference('auth_forcepasswordchange', 1, $newuser);
            } else {
                trigger_error("Could not create and mail new user password!");
            }
        }
        $newusers->close();
    }
    // It is very important to run enrol early
    // because other plugins depend on correct enrolment info.
    mtrace("Running enrol crons if required...");
    $enrols = enrol_get_plugins(true);
    foreach ($enrols as $ename => $enrol) {
        // do this for all plugins, disabled plugins might want to cleanup stuff such as roles
        if (!$enrol->is_cron_required()) {
            continue;
        }
        mtrace("Running cron for enrol_{$ename}...");
        cron_trace_time_and_memory();
        $enrol->cron();
        $enrol->set_config('lastcron', time());
    }
    // Run all cron jobs for each module
    mtrace("Starting activity modules");
    get_mailer('buffer');
    if ($mods = $DB->get_records_select("modules", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        foreach ($mods as $mod) {
            $libfile = "{$CFG->dirroot}/mod/{$mod->name}/lib.php";
            if (file_exists($libfile)) {
                include_once $libfile;
                $cron_function = $mod->name . "_cron";
                if (function_exists($cron_function)) {
                    mtrace("Processing module function {$cron_function} ...", '');
                    cron_trace_time_and_memory();
                    $pre_dbqueries = null;
                    $pre_dbqueries = $DB->perf_get_queries();
                    $pre_time = microtime(1);
                    if ($cron_function()) {
                        $DB->set_field("modules", "lastcron", $timenow, array("id" => $mod->id));
                    }
                    if (isset($pre_dbqueries)) {
                        mtrace("... used " . ($DB->perf_get_queries() - $pre_dbqueries) . " dbqueries");
                        mtrace("... used " . (microtime(1) - $pre_time) . " seconds");
                    }
                    // Reset possible changes by modules to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace("done.");
                }
            }
        }
    }
    get_mailer('close');
    mtrace("Finished activity modules");
    mtrace("Starting blocks");
    if ($blocks = $DB->get_records_select("block", "cron > 0 AND ((? - lastcron) > cron) AND visible = 1", array($timenow))) {
        // We will need the base class.
        require_once $CFG->dirroot . '/blocks/moodleblock.class.php';
        foreach ($blocks as $block) {
            $blockfile = $CFG->dirroot . '/blocks/' . $block->name . '/block_' . $block->name . '.php';
            if (file_exists($blockfile)) {
                require_once $blockfile;
                $classname = 'block_' . $block->name;
                $blockobj = new $classname();
                if (method_exists($blockobj, 'cron')) {
                    mtrace("Processing cron function for " . $block->name . '....', '');
                    cron_trace_time_and_memory();
                    if ($blockobj->cron()) {
                        $DB->set_field('block', 'lastcron', $timenow, array('id' => $block->id));
                    }
                    // Reset possible changes by blocks to time_limit. MDL-11597
                    @set_time_limit(0);
                    mtrace('done.');
                }
            }
        }
    }
    mtrace('Finished blocks');
    mtrace('Starting admin reports');
    cron_execute_plugin_type('report');
    mtrace('Finished admin reports');
    mtrace('Starting main gradebook job...');
    cron_trace_time_and_memory();
    grade_cron();
    mtrace('done.');
    mtrace('Starting processing the event queue...');
    cron_trace_time_and_memory();
    events_cron();
    mtrace('done.');
    if ($CFG->enablecompletion) {
        // Completion cron
        mtrace('Starting the completion cron...');
        cron_trace_time_and_memory();
        require_once $CFG->dirroot . '/completion/cron.php';
        completion_cron();
        mtrace('done');
    }
    if ($CFG->enableportfolios) {
        // Portfolio cron
        mtrace('Starting the portfolio cron...');
        cron_trace_time_and_memory();
        require_once $CFG->libdir . '/portfoliolib.php';
        portfolio_cron();
        mtrace('done');
    }
    //now do plagiarism checks
    require_once $CFG->libdir . '/plagiarismlib.php';
    plagiarism_cron();
    mtrace('Starting course reports');
    cron_execute_plugin_type('coursereport');
    mtrace('Finished course reports');
    // run gradebook import/export/report cron
    mtrace('Starting gradebook plugins');
    cron_execute_plugin_type('gradeimport');
    cron_execute_plugin_type('gradeexport');
    cron_execute_plugin_type('gradereport');
    mtrace('Finished gradebook plugins');
    // run calendar cron
    require_once "{$CFG->dirroot}/calendar/lib.php";
    calendar_cron();
    // Run external blog cron if needed
    if (!empty($CFG->enableblogs) && $CFG->useexternalblogs) {
        require_once $CFG->dirroot . '/blog/lib.php';
        mtrace("Fetching external blog entries...", '');
        cron_trace_time_and_memory();
        $sql = "timefetched < ? OR timefetched = 0";
        $externalblogs = $DB->get_records_select('blog_external', $sql, array(time() - $CFG->externalblogcrontime));
        foreach ($externalblogs as $eb) {
            blog_sync_external_entries($eb);
        }
        mtrace('done.');
    }
    // Run blog associations cleanup
    if (!empty($CFG->enableblogs) && $CFG->useblogassociations) {
        require_once $CFG->dirroot . '/blog/lib.php';
        // delete entries whose contextids no longer exists
        mtrace("Deleting blog associations linked to non-existent contexts...", '');
        cron_trace_time_and_memory();
        $DB->delete_records_select('blog_association', 'contextid NOT IN (SELECT id FROM {context})');
        mtrace('done.');
    }
    // Run question bank clean-up.
    mtrace("Starting the question bank cron...", '');
    cron_trace_time_and_memory();
    require_once $CFG->libdir . '/questionlib.php';
    question_bank::cron();
    mtrace('done.');
    //Run registration updated cron
    mtrace(get_string('siteupdatesstart', 'hub'));
    cron_trace_time_and_memory();
    require_once $CFG->dirroot . '/' . $CFG->admin . '/registration/lib.php';
    $registrationmanager = new registration_manager();
    $registrationmanager->cron();
    mtrace(get_string('siteupdatesend', 'hub'));
    // If enabled, fetch information about available updates and eventually notify site admins
    if (empty($CFG->disableupdatenotifications)) {
        $updateschecker = \core\update\checker::instance();
        $updateschecker->cron();
    }
    //cleanup old session linked tokens
    //deletes the session linked tokens that are over a day old.
    mtrace("Deleting session linked tokens more than one day old...", '');
    cron_trace_time_and_memory();
    $DB->delete_records_select('external_tokens', 'lastaccess < :onedayago AND tokentype = :tokentype', array('onedayago' => time() - DAYSECS, 'tokentype' => EXTERNAL_TOKEN_EMBEDDED));
    mtrace('done.');
    // all other plugins
    cron_execute_plugin_type('message', 'message plugins');
    cron_execute_plugin_type('filter', 'filters');
    cron_execute_plugin_type('editor', 'editors');
    cron_execute_plugin_type('format', 'course formats');
    cron_execute_plugin_type('profilefield', 'profile fields');
    cron_execute_plugin_type('webservice', 'webservices');
    cron_execute_plugin_type('repository', 'repository plugins');
    cron_execute_plugin_type('qbehaviour', 'question behaviours');
    cron_execute_plugin_type('qformat', 'question import/export formats');
    cron_execute_plugin_type('qtype', 'question types');
    cron_execute_plugin_type('plagiarism', 'plagiarism plugins');
    cron_execute_plugin_type('theme', 'themes');
    cron_execute_plugin_type('tool', 'admin tools');
    // and finally run any local cronjobs, if any
    if ($locals = core_component::get_plugin_list('local')) {
        mtrace('Processing customized cron scripts ...', '');
        // new cron functions in lib.php first
        cron_execute_plugin_type('local');
        // legacy cron files are executed directly
        foreach ($locals as $local => $localdir) {
            if (file_exists("{$localdir}/cron.php")) {
                include "{$localdir}/cron.php";
            }
        }
        mtrace('done.');
    }
    mtrace('Running cache cron routines');
    cache_helper::cron();
    mtrace('done.');
    // Run automated backups if required - these may take a long time to execute
    require_once $CFG->dirroot . '/backup/util/includes/backup_includes.php';
    require_once $CFG->dirroot . '/backup/util/helper/backup_cron_helper.class.php';
    backup_cron_automated_helper::run_automated_backup();
    // Run stats as at the end because they are known to take very long time on large sites
    if (!empty($CFG->enablestats) and empty($CFG->disablestatsprocessing)) {
        require_once $CFG->dirroot . '/lib/statslib.php';
        // check we're not before our runtime
        $timetocheck = stats_get_base_daily() + $CFG->statsruntimestarthour * 60 * 60 + $CFG->statsruntimestartminute * 60;
        if (time() > $timetocheck) {
            // process configured number of days as max (defaulting to 31)
            $maxdays = empty($CFG->statsruntimedays) ? 31 : abs($CFG->statsruntimedays);
            if (stats_cron_daily($maxdays)) {
                if (stats_cron_weekly()) {
                    if (stats_cron_monthly()) {
                        stats_clean_old();
                    }
                }
            }
            @set_time_limit(0);
        } else {
            mtrace('Next stats run after:' . userdate($timetocheck));
        }
    }
    // Run badges review cron.
    mtrace("Starting badges cron...");
    require_once $CFG->dirroot . '/badges/cron.php';
    badge_cron();
    mtrace('done.');
    // cleanup file trash - not very important
    $fs = get_file_storage();
    $fs->cron();
    mtrace("Cron script completed correctly");
    gc_collect_cycles();
    mtrace('Cron completed at ' . date('H:i:s') . '. Memory used ' . display_size(memory_get_usage()) . '.');
    $difftime = microtime_diff($starttime, microtime());
    mtrace("Execution took " . $difftime . " seconds");
}
Ejemplo n.º 13
0
/**
 * Marks user deleted in internal user database and notifies the auth plugin.
 * Also unenrols user from all roles and does other cleanup.
 *
 * @todo Decide if this transaction is really needed (look for internal TODO:)
 * @param object $user Userobject before delete    (without system magic quotes)
 * @return boolean success
 */
function user_delete_user($user)
{
    return delete_user($user);
}
Ejemplo n.º 14
0
    session_start();
}
$op = "";
if (isset($_POST['op'])) {
    $op = $_POST['op'];
} elseif (isset($_GET['op'])) {
    $op = $_GET['op'];
}
if ($op != "register" && (!check_session_user() || !check_admin_user())) {
    header('Location: index.php?error=Invalid User' . $op);
} else {
    if (strlen($op) > 0) {
        if ($op == "delete") {
            if (isset($_GET['id'])) {
                $username = $_GET['id'];
                $err = delete_user($username);
                if (strlen($err) > 0) {
                    header('Location: error.php?msg=' . urlencode($err));
                } else {
                    header('Location: user_list.php');
                }
            } else {
                header('Location: error.php?msg=No id');
            }
        } elseif ($op == "password") {
            $username = $_SESSION["user"];
            $password = $_POST['password'];
            $password2 = $_POST['password2'];
            $err = "";
            if (strlen(trim($password)) > 0) {
                if (trim($password) != trim($password2)) {
Ejemplo n.º 15
0
function delete_submit(Pieform $form, $values)
{
    global $users, $editable, $SESSION;
    db_begin();
    foreach ($users as $user) {
        delete_user($user->id);
    }
    db_commit();
    $SESSION->add_ok_msg(get_string('bulkdeleteuserssuccess', 'admin', count($users)));
    redirect('/admin/users/search.php');
}
Ejemplo n.º 16
0
}
if (isset($_GET['action'])) {
    if ($_GET['action'] == "addmoderator") {
        if (!isset($_GET['id'])) {
            die("Must specify id for this action");
        }
        make_moderator($_GET['id']);
    } else {
        if ($_GET['action'] == "removemoderator") {
            if (!isset($_GET['id'])) {
                die("Must specify id for this action");
            }
            remove_moderator($_GET['id']);
        } else {
            if ($_GET['action'] == "delete") {
                delete_user($_SESSION['username']);
                session_destroy();
                $_SESSION = array();
                //die("Your account has been removed from the database.");
                header("Location: login.php", true);
            }
        }
    }
}
?>

<?php 
if (isset($_GET['id'])) {
    ?>
<b>Viewing <?php 
    echo $user_profile['firstName'];
Ejemplo n.º 17
0
 /**
  * syncronizes user fron external db to moodle user table
  *
  * Sync shouid be done by using idnumber attribute, not username.
  * You need to pass firstsync parameter to function to fill in
  * idnumbers if they dont exists in moodle user table.
  *
  * Syncing users removes (disables) users that dont exists anymore in external db.
  * Creates new users and updates coursecreator status of users.
  *
  * @param bool $do_updates  Optional: set to true to force an update of existing accounts
  *
  * This implementation is simpler but less scalable than the one found in the LDAP module.
  *
  */
 function sync_users($do_updates = false)
 {
     global $CFG;
     $pcfg = get_config('auth/db');
     /// list external users
     $userlist = $this->get_userlist();
     $quoteduserlist = implode("', '", addslashes_recursive($userlist));
     $quoteduserlist = "'{$quoteduserlist}'";
     /// delete obsolete internal users
     if (!empty($this->config->removeuser)) {
         // find obsolete users
         if (count($userlist)) {
             $sql = "SELECT u.id, u.username, u.email\n                        FROM {$CFG->prefix}user u\n                        WHERE u.auth='db' AND u.deleted=0 AND u.username NOT IN ({$quoteduserlist})";
         } else {
             $sql = "SELECT u.id, u.username, u.email\n                        FROM {$CFG->prefix}user u\n                        WHERE u.auth='db' AND u.deleted=0";
         }
         $remove_users = get_records_sql($sql);
         if (!empty($remove_users)) {
             print_string('auth_dbuserstoremove', 'auth', count($remove_users));
             echo "\n";
             foreach ($remove_users as $user) {
                 if ($this->config->removeuser == 2) {
                     if (delete_user($user)) {
                         echo "\t";
                         print_string('auth_dbdeleteuser', 'auth', array($user->username, $user->id));
                         echo "\n";
                     } else {
                         echo "\t";
                         print_string('auth_dbdeleteusererror', 'auth', $user->username);
                         echo "\n";
                     }
                 } else {
                     if ($this->config->removeuser == 1) {
                         $updateuser = new object();
                         $updateuser->id = $user->id;
                         $updateuser->auth = 'nologin';
                         if (update_record('user', $updateuser)) {
                             echo "\t";
                             print_string('auth_dbsuspenduser', 'auth', array($user->username, $user->id));
                             echo "\n";
                         } else {
                             echo "\t";
                             print_string('auth_dbsuspendusererror', 'auth', $user->username);
                             echo "\n";
                         }
                     }
                 }
             }
         }
         unset($remove_users);
         // free mem!
     }
     if (!count($userlist)) {
         // exit right here
         // nothing else to do
         return true;
     }
     ///
     /// update existing accounts
     ///
     if ($do_updates) {
         // narrow down what fields we need to update
         $all_keys = array_keys(get_object_vars($this->config));
         $updatekeys = array();
         foreach ($all_keys as $key) {
             if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
                 if ($this->config->{$key} === 'onlogin') {
                     array_push($updatekeys, $match[1]);
                     // the actual key name
                 }
             }
         }
         // print_r($all_keys); print_r($updatekeys);
         unset($all_keys);
         unset($key);
         // only go ahead if we actually
         // have fields to update locally
         if (!empty($updatekeys)) {
             $sql = 'SELECT u.id, u.username
                     FROM ' . $CFG->prefix . 'user u
                     WHERE u.auth=\'db\' AND u.deleted=\'0\' AND u.username IN (' . $quoteduserlist . ')';
             if ($update_users = get_records_sql($sql)) {
                 print "User entries to update: " . count($update_users) . "\n";
                 foreach ($update_users as $user) {
                     echo "\t";
                     print_string('auth_dbupdatinguser', 'auth', array($user->username, $user->id));
                     if (!$this->update_user_record(addslashes($user->username), $updatekeys)) {
                         echo " - " . get_string('skipped');
                     }
                     echo "\n";
                 }
                 unset($update_users);
                 // free memory
             }
         }
     }
     ///
     /// create missing accounts
     ///
     // NOTE: this is very memory intensive
     // and generally inefficient
     $sql = 'SELECT u.id, u.username
             FROM ' . $CFG->prefix . 'user u
             WHERE u.auth=\'db\' AND u.deleted=\'0\'';
     $users = get_records_sql($sql);
     // simplify down to usernames
     $usernames = array();
     foreach ($users as $user) {
         array_push($usernames, $user->username);
     }
     unset($users);
     $add_users = array_diff($userlist, $usernames);
     unset($usernames);
     if (!empty($add_users)) {
         print_string('auth_dbuserstoadd', 'auth', count($add_users));
         echo "\n";
         begin_sql();
         foreach ($add_users as $user) {
             $username = $user;
             $user = $this->get_userinfo_asobj($user);
             // prep a few params
             $user->username = $username;
             $user->modified = time();
             $user->confirmed = 1;
             $user->auth = 'db';
             $user->mnethostid = $CFG->mnet_localhost_id;
             if (empty($user->lang)) {
                 $user->lang = $CFG->lang;
             }
             $user = addslashes_object($user);
             // maybe the user has been deleted before
             if ($old_user = get_record('user', 'username', $user->username, 'deleted', 1, 'mnethostid', $user->mnethostid)) {
                 $user->id = $old_user->id;
                 set_field('user', 'deleted', 0, 'username', $user->username);
                 echo "\t";
                 print_string('auth_dbreviveuser', 'auth', array(stripslashes($user->username), $user->id));
                 echo "\n";
             } elseif ($id = insert_record('user', $user)) {
                 // it is truly a new user
                 echo "\t";
                 print_string('auth_dbinsertuser', 'auth', array(stripslashes($user->username), $id));
                 echo "\n";
                 // if relevant, tag for password generation
                 if ($this->config->passtype === 'internal') {
                     set_user_preference('auth_forcepasswordchange', 1, $id);
                     set_user_preference('create_password', 1, $id);
                 }
             } else {
                 echo "\t";
                 print_string('auth_dbinsertusererror', 'auth', $user->username);
                 echo "\n";
             }
         }
         commit_sql();
         unset($add_users);
         // free mem
     }
     return true;
 }
Ejemplo n.º 18
0
function delete_domain($domain_id)
{
    global $dbh;
    // Delete all admin references to this domain.
    delete_domain_admin_references($domain_id);
    // Delete the domain record itself.
    $sth = $dbh->prepare("DELETE FROM maia_domains WHERE id = ?");
    $res = $sth->execute(array($domain_id));
    if (PEAR::isError($sth)) {
        die($sth->getMessage());
    }
    $sth->free();
    // Find and delete the default user records associated with this domain
    $sth = $dbh->prepare("SELECT maia_user_id FROM users WHERE maia_domain_id = ?");
    $res = $sth->execute(array($domain_id));
    if (PEAR::isError($sth)) {
        die($sth->getMessage());
    }
    if ($row = $res->fetchrow()) {
        $maia_user_id = $row["maia_user_id"];
        delete_user($maia_user_id);
    }
    $sth->free();
}
Ejemplo n.º 19
0
function handle_user_delete($user_id, $HTTP_VARS, &$errors)
{
    if (is_user_valid($user_id) && is_user_not_activated($user_id)) {
        // If already confirmed operation.
        if ($HTTP_VARS['confirmed'] == 'true') {
            // ignore failure to delete user addresses - will be logged.
            delete_user_addresses($user_id);
            if (!delete_user($user_id)) {
                $db_error = db_error();
                $errors = array('error' => get_opendb_lang_var('user_not_deleted'), 'detail' => $db_error);
                return FALSE;
            } else {
                return TRUE;
            }
        } else {
            if ($HTTP_VARS['confirmed'] != 'false') {
                // confirmation required.
                return "__CONFIRM__";
            } else {
                return "__ABORTED__";
            }
        }
    } else {
        opendb_logger(OPENDB_LOG_ERROR, __FILE__, __FUNCTION__, 'Attempt to delete a user which is activated or previously activated', $user_id);
        $errors = array('error' => get_opendb_lang_var('operation_not_available'), 'detail' => '');
        return FALSE;
    }
}
Ejemplo n.º 20
0
 public function test_get_entries_by_author()
 {
     $this->resetAfterTest(true);
     // Generate all the things.
     $gg = $this->getDataGenerator()->get_plugin_generator('mod_glossary');
     $c1 = $this->getDataGenerator()->create_course();
     $g1 = $this->getDataGenerator()->create_module('glossary', array('course' => $c1->id, 'displayformat' => 'entrylist'));
     $g2 = $this->getDataGenerator()->create_module('glossary', array('course' => $c1->id, 'displayformat' => 'entrylist'));
     $u1 = $this->getDataGenerator()->create_user(array('lastname' => 'Upsilon', 'firstname' => 'Zac'));
     $u2 = $this->getDataGenerator()->create_user(array('lastname' => 'Ultra', 'firstname' => '1337'));
     $u3 = $this->getDataGenerator()->create_user(array('lastname' => 'Alpha', 'firstname' => 'Omega'));
     $u4 = $this->getDataGenerator()->create_user(array('lastname' => '0-day', 'firstname' => 'Zoe'));
     $ctx = context_module::instance($g1->cmid);
     $this->getDataGenerator()->enrol_user($u1->id, $c1->id);
     $e1a1 = $gg->create_content($g1, array('approved' => 1, 'userid' => $u1->id));
     $e1a2 = $gg->create_content($g1, array('approved' => 1, 'userid' => $u1->id));
     $e1a3 = $gg->create_content($g1, array('approved' => 1, 'userid' => $u1->id));
     $e1b1 = $gg->create_content($g1, array('approved' => 0, 'userid' => $u2->id));
     $e1b2 = $gg->create_content($g1, array('approved' => 1, 'userid' => $u2->id));
     $e1c1 = $gg->create_content($g1, array('approved' => 1, 'userid' => $u3->id));
     $e1d1 = $gg->create_content($g1, array('approved' => 1, 'userid' => $u4->id));
     $e2a = $gg->create_content($g2, array('approved' => 1, 'userid' => $u1->id));
     $this->setUser($u1);
     // Requesting a single letter.
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'u', 'LASTNAME', 'ASC', 0, 20, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(4, $return['entries']);
     $this->assertEquals(4, $return['count']);
     $this->assertEquals($e1b2->id, $return['entries'][0]['id']);
     $this->assertEquals($e1a1->id, $return['entries'][1]['id']);
     $this->assertEquals($e1a2->id, $return['entries'][2]['id']);
     $this->assertEquals($e1a3->id, $return['entries'][3]['id']);
     // Requesting special letters.
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'SPECIAL', 'LASTNAME', 'ASC', 0, 20, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(1, $return['entries']);
     $this->assertEquals(1, $return['count']);
     $this->assertEquals($e1d1->id, $return['entries'][0]['id']);
     // Requesting with limit.
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'ALL', 'LASTNAME', 'ASC', 0, 1, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(1, $return['entries']);
     $this->assertEquals(6, $return['count']);
     $this->assertEquals($e1d1->id, $return['entries'][0]['id']);
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'ALL', 'LASTNAME', 'ASC', 1, 2, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(2, $return['entries']);
     $this->assertEquals(6, $return['count']);
     $this->assertEquals($e1c1->id, $return['entries'][0]['id']);
     $this->assertEquals($e1b2->id, $return['entries'][1]['id']);
     // Including non-approved.
     $this->setAdminUser();
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'ALL', 'LASTNAME', 'ASC', 0, 20, array('includenotapproved' => true));
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(7, $return['entries']);
     $this->assertEquals(7, $return['count']);
     $this->assertEquals($e1d1->id, $return['entries'][0]['id']);
     $this->assertEquals($e1c1->id, $return['entries'][1]['id']);
     $this->assertEquals($e1b1->id, $return['entries'][2]['id']);
     $this->assertEquals($e1b2->id, $return['entries'][3]['id']);
     $this->assertEquals($e1a1->id, $return['entries'][4]['id']);
     $this->assertEquals($e1a2->id, $return['entries'][5]['id']);
     $this->assertEquals($e1a3->id, $return['entries'][6]['id']);
     // Changing order.
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'ALL', 'LASTNAME', 'DESC', 0, 1, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(1, $return['entries']);
     $this->assertEquals(6, $return['count']);
     $this->assertEquals($e1a1->id, $return['entries'][0]['id']);
     // Sorting by firstname.
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'ALL', 'FIRSTNAME', 'ASC', 0, 1, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(1, $return['entries']);
     $this->assertEquals(6, $return['count']);
     $this->assertEquals($e1b2->id, $return['entries'][0]['id']);
     // Sorting by firstname descending.
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'ALL', 'FIRSTNAME', 'DESC', 0, 1, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(1, $return['entries']);
     $this->assertEquals(6, $return['count']);
     $this->assertEquals($e1d1->id, $return['entries'][0]['id']);
     // Filtering by firstname descending.
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'z', 'FIRSTNAME', 'DESC', 0, 20, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(4, $return['entries']);
     $this->assertEquals(4, $return['count']);
     $this->assertEquals($e1d1->id, $return['entries'][0]['id']);
     $this->assertEquals($e1a1->id, $return['entries'][1]['id']);
     $this->assertEquals($e1a2->id, $return['entries'][2]['id']);
     $this->assertEquals($e1a3->id, $return['entries'][3]['id']);
     // Test with a deleted user.
     delete_user($u2);
     $return = mod_glossary_external::get_entries_by_author($g1->id, 'u', 'LASTNAME', 'ASC', 0, 20, array());
     $return = external_api::clean_returnvalue(mod_glossary_external::get_entries_by_author_returns(), $return);
     $this->assertCount(4, $return['entries']);
     $this->assertEquals(4, $return['count']);
     $this->assertEquals($e1b2->id, $return['entries'][0]['id']);
     $this->assertEquals($e1a1->id, $return['entries'][1]['id']);
     $this->assertEquals($e1a2->id, $return['entries'][2]['id']);
     $this->assertEquals($e1a3->id, $return['entries'][3]['id']);
 }
Ejemplo n.º 21
0
     require_capability('moodle/user:delete', $sitecontext);
     $user = $DB->get_record('user', array('id' => $delete, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
     if (is_siteadmin($user->id)) {
         print_error('useradminodelete', 'error');
     }
     if ($confirm != md5($delete)) {
         echo $OUTPUT->header();
         $fullname = fullname($user, true);
         echo $OUTPUT->heading(get_string('deleteuser', 'admin'));
         $optionsyes = array('delete' => $delete, 'confirm' => md5($delete), 'sesskey' => sesskey());
         echo $OUTPUT->confirm(get_string('deletecheckfull', '', "'{$fullname}'"), new moodle_url($returnurl, $optionsyes), $returnurl);
         echo $OUTPUT->footer();
         die;
     } else {
         if (data_submitted() and !$user->deleted) {
             if (delete_user($user)) {
                 \core\session\manager::gc();
                 // Remove stale sessions.
                 redirect($returnurl);
             } else {
                 \core\session\manager::gc();
                 // Remove stale sessions.
                 echo $OUTPUT->header();
                 echo $OUTPUT->notification($returnurl, get_string('deletednot', '', fullname($user, true)));
             }
         }
     }
 } else {
     if ($acl and confirm_sesskey()) {
         if (!has_capability('moodle/user:update', $sitecontext)) {
             print_error('nopermissions', 'error', '', 'modify the NMET access control list');
Ejemplo n.º 22
0
 /**
  * Syncronizes user fron external LDAP server to moodle user table
  *
  * Sync is now using username attribute.
  *
  * Syncing users removes or suspends users that dont exists anymore in external LDAP.
  * Creates new users and updates coursecreator status of users.
  *
  * @param bool $do_updates will do pull in data updates from LDAP if relevant
  */
 function sync_users($do_updates = true)
 {
     global $CFG, $DB;
     print_string('connectingldap', 'auth_ldap');
     $ldapconnection = $this->ldap_connect();
     $dbman = $DB->get_manager();
     /// Define table user to be created
     $table = new xmldb_table('tmp_extuser');
     $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null);
     $table->add_field('username', XMLDB_TYPE_CHAR, '100', null, XMLDB_NOTNULL, null, null);
     $table->add_field('mnethostid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null);
     $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'));
     $table->add_index('username', XMLDB_INDEX_UNIQUE, array('mnethostid', 'username'));
     print_string('creatingtemptable', 'auth_ldap', 'tmp_extuser');
     $dbman->create_temp_table($table);
     ////
     //// get user's list from ldap to sql in a scalable fashion
     ////
     // prepare some data we'll need
     $filter = '(&(' . $this->config->user_attribute . '=*)' . $this->config->objectclass . ')';
     $contexts = explode(';', $this->config->contexts);
     if (!empty($this->config->create_context)) {
         array_push($contexts, $this->config->create_context);
     }
     $ldap_pagedresults = ldap_paged_results_supported($this->config->ldap_version);
     $ldap_cookie = '';
     foreach ($contexts as $context) {
         $context = trim($context);
         if (empty($context)) {
             continue;
         }
         do {
             if ($ldap_pagedresults) {
                 ldap_control_paged_result($ldapconnection, $this->config->pagesize, true, $ldap_cookie);
             }
             if ($this->config->search_sub) {
                 // Use ldap_search to find first user from subtree.
                 $ldap_result = ldap_search($ldapconnection, $context, $filter, array($this->config->user_attribute));
             } else {
                 // Search only in this context.
                 $ldap_result = ldap_list($ldapconnection, $context, $filter, array($this->config->user_attribute));
             }
             if (!$ldap_result) {
                 continue;
             }
             if ($ldap_pagedresults) {
                 ldap_control_paged_result_response($ldapconnection, $ldap_result, $ldap_cookie);
             }
             if ($entry = @ldap_first_entry($ldapconnection, $ldap_result)) {
                 do {
                     $value = ldap_get_values_len($ldapconnection, $entry, $this->config->user_attribute);
                     $value = core_text::convert($value[0], $this->config->ldapencoding, 'utf-8');
                     $value = trim($value);
                     $this->ldap_bulk_insert($value);
                 } while ($entry = ldap_next_entry($ldapconnection, $entry));
             }
             unset($ldap_result);
             // Free mem.
         } while ($ldap_pagedresults && $ldap_cookie !== null && $ldap_cookie != '');
     }
     // If LDAP paged results were used, the current connection must be completely
     // closed and a new one created, to work without paged results from here on.
     if ($ldap_pagedresults) {
         $this->ldap_close(true);
         $ldapconnection = $this->ldap_connect();
     }
     /// preserve our user database
     /// if the temp table is empty, it probably means that something went wrong, exit
     /// so as to avoid mass deletion of users; which is hard to undo
     $count = $DB->count_records_sql('SELECT COUNT(username) AS count, 1 FROM {tmp_extuser}');
     if ($count < 1) {
         print_string('didntgetusersfromldap', 'auth_ldap');
         exit;
     } else {
         print_string('gotcountrecordsfromldap', 'auth_ldap', $count);
     }
     /// User removal
     // Find users in DB that aren't in ldap -- to be removed!
     // this is still not as scalable (but how often do we mass delete?)
     if ($this->config->removeuser == AUTH_REMOVEUSER_FULLDELETE) {
         $sql = "SELECT u.*\n                      FROM {user} u\n                 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)\n                     WHERE u.auth = :auth\n                           AND u.deleted = 0\n                           AND e.username IS NULL";
         $remove_users = $DB->get_records_sql($sql, array('auth' => $this->authtype));
         if (!empty($remove_users)) {
             print_string('userentriestoremove', 'auth_ldap', count($remove_users));
             foreach ($remove_users as $user) {
                 if (delete_user($user)) {
                     echo "\t";
                     print_string('auth_dbdeleteuser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                     echo "\n";
                 } else {
                     echo "\t";
                     print_string('auth_dbdeleteusererror', 'auth_db', $user->username);
                     echo "\n";
                 }
             }
         } else {
             print_string('nouserentriestoremove', 'auth_ldap');
         }
         unset($remove_users);
         // Free mem!
     } else {
         if ($this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
             $sql = "SELECT u.*\n                      FROM {user} u\n                 LEFT JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)\n                     WHERE u.auth = :auth\n                           AND u.deleted = 0\n                           AND u.suspended = 0\n                           AND e.username IS NULL";
             $remove_users = $DB->get_records_sql($sql, array('auth' => $this->authtype));
             if (!empty($remove_users)) {
                 print_string('userentriestoremove', 'auth_ldap', count($remove_users));
                 foreach ($remove_users as $user) {
                     $updateuser = new stdClass();
                     $updateuser->id = $user->id;
                     $updateuser->suspended = 1;
                     user_update_user($updateuser, false);
                     echo "\t";
                     print_string('auth_dbsuspenduser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                     echo "\n";
                     \core\session\manager::kill_user_sessions($user->id);
                 }
             } else {
                 print_string('nouserentriestoremove', 'auth_ldap');
             }
             unset($remove_users);
             // Free mem!
         }
     }
     /// Revive suspended users
     if (!empty($this->config->removeuser) and $this->config->removeuser == AUTH_REMOVEUSER_SUSPEND) {
         $sql = "SELECT u.id, u.username\n                      FROM {user} u\n                      JOIN {tmp_extuser} e ON (u.username = e.username AND u.mnethostid = e.mnethostid)\n                     WHERE (u.auth = 'nologin' OR (u.auth = ? AND u.suspended = 1)) AND u.deleted = 0";
         // Note: 'nologin' is there for backwards compatibility.
         $revive_users = $DB->get_records_sql($sql, array($this->authtype));
         if (!empty($revive_users)) {
             print_string('userentriestorevive', 'auth_ldap', count($revive_users));
             foreach ($revive_users as $user) {
                 $updateuser = new stdClass();
                 $updateuser->id = $user->id;
                 $updateuser->auth = $this->authtype;
                 $updateuser->suspended = 0;
                 user_update_user($updateuser, false);
                 echo "\t";
                 print_string('auth_dbreviveduser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                 echo "\n";
             }
         } else {
             print_string('nouserentriestorevive', 'auth_ldap');
         }
         unset($revive_users);
     }
     /// User Updates - time-consuming (optional)
     if ($do_updates) {
         // Narrow down what fields we need to update
         $all_keys = array_keys(get_object_vars($this->config));
         $updatekeys = array();
         foreach ($all_keys as $key) {
             if (preg_match('/^field_updatelocal_(.+)$/', $key, $match)) {
                 // If we have a field to update it from
                 // and it must be updated 'onlogin' we
                 // update it on cron
                 if (!empty($this->config->{'field_map_' . $match[1]}) and $this->config->{$match[0]} === 'onlogin') {
                     array_push($updatekeys, $match[1]);
                     // the actual key name
                 }
             }
         }
         unset($all_keys);
         unset($key);
     } else {
         print_string('noupdatestobedone', 'auth_ldap');
     }
     if ($do_updates and !empty($updatekeys)) {
         // run updates only if relevant
         $users = $DB->get_records_sql('SELECT u.username, u.id
                                          FROM {user} u
                                         WHERE u.deleted = 0 AND u.auth = ? AND u.mnethostid = ?', array($this->authtype, $CFG->mnet_localhost_id));
         if (!empty($users)) {
             print_string('userentriestoupdate', 'auth_ldap', count($users));
             $sitecontext = context_system::instance();
             if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_archetype_roles('coursecreator')) {
                 $creatorrole = array_shift($roles);
                 // We can only use one, let's use the first one
             } else {
                 $creatorrole = false;
             }
             $transaction = $DB->start_delegated_transaction();
             $xcount = 0;
             $maxxcount = 100;
             foreach ($users as $user) {
                 echo "\t";
                 print_string('auth_dbupdatinguser', 'auth_db', array('name' => $user->username, 'id' => $user->id));
                 if (!$this->update_user_record($user->username, $updatekeys, true)) {
                     echo ' - ' . get_string('skipped');
                 }
                 echo "\n";
                 $xcount++;
                 // Update course creators if needed
                 if ($creatorrole !== false) {
                     if ($this->iscreator($user->username)) {
                         role_assign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
                     } else {
                         role_unassign($creatorrole->id, $user->id, $sitecontext->id, $this->roleauth);
                     }
                 }
             }
             $transaction->allow_commit();
             unset($users);
             // free mem
         }
     } else {
         // end do updates
         print_string('noupdatestobedone', 'auth_ldap');
     }
     /// User Additions
     // Find users missing in DB that are in LDAP
     // and gives me a nifty object I don't want.
     // note: we do not care about deleted accounts anymore, this feature was replaced by suspending to nologin auth plugin
     $sql = 'SELECT e.id, e.username
               FROM {tmp_extuser} e
               LEFT JOIN {user} u ON (e.username = u.username AND e.mnethostid = u.mnethostid)
              WHERE u.id IS NULL';
     $add_users = $DB->get_records_sql($sql);
     if (!empty($add_users)) {
         print_string('userentriestoadd', 'auth_ldap', count($add_users));
         $sitecontext = context_system::instance();
         if (!empty($this->config->creators) and !empty($this->config->memberattribute) and $roles = get_archetype_roles('coursecreator')) {
             $creatorrole = array_shift($roles);
             // We can only use one, let's use the first one
         } else {
             $creatorrole = false;
         }
         $transaction = $DB->start_delegated_transaction();
         foreach ($add_users as $user) {
             $user = $this->get_userinfo_asobj($user->username);
             // Prep a few params
             $user->modified = time();
             $user->confirmed = 1;
             $user->auth = $this->authtype;
             $user->mnethostid = $CFG->mnet_localhost_id;
             // get_userinfo_asobj() might have replaced $user->username with the value
             // from the LDAP server (which can be mixed-case). Make sure it's lowercase
             $user->username = trim(core_text::strtolower($user->username));
             if (empty($user->lang)) {
                 $user->lang = $CFG->lang;
             }
             if (empty($user->calendartype)) {
                 $user->calendartype = $CFG->calendartype;
             }
             $id = user_create_user($user, false);
             echo "\t";
             print_string('auth_dbinsertuser', 'auth_db', array('name' => $user->username, 'id' => $id));
             echo "\n";
             $euser = $DB->get_record('user', array('id' => $id));
             if (!empty($this->config->forcechangepassword)) {
                 set_user_preference('auth_forcepasswordchange', 1, $id);
             }
             // Add course creators if needed
             if ($creatorrole !== false and $this->iscreator($user->username)) {
                 role_assign($creatorrole->id, $id, $sitecontext->id, $this->roleauth);
             }
         }
         $transaction->allow_commit();
         unset($add_users);
         // free mem
     } else {
         print_string('nouserstobeadded', 'auth_ldap');
     }
     $dbman->drop_table($table);
     $this->ldap_close();
     return true;
 }
Ejemplo n.º 23
0
 /**
  * Test deleting of users.
  */
 public function test_delete_user()
 {
     global $DB, $CFG;
     $this->resetAfterTest();
     $guest = $DB->get_record('user', array('id' => $CFG->siteguest), '*', MUST_EXIST);
     $admin = $DB->get_record('user', array('id' => $CFG->siteadmins), '*', MUST_EXIST);
     $this->assertEquals(0, $DB->count_records('user', array('deleted' => 1)));
     $user = $this->getDataGenerator()->create_user(array('idnumber' => 'abc'));
     $user2 = $this->getDataGenerator()->create_user(array('idnumber' => 'xyz'));
     // Delete user and capture event.
     $sink = $this->redirectEvents();
     $result = delete_user($user);
     $events = $sink->get_events();
     $sink->close();
     $event = array_pop($events);
     // Test user is deleted in DB.
     $this->assertTrue($result);
     $deluser = $DB->get_record('user', array('id' => $user->id), '*', MUST_EXIST);
     $this->assertEquals(1, $deluser->deleted);
     $this->assertEquals(0, $deluser->picture);
     $this->assertSame('', $deluser->idnumber);
     $this->assertSame(md5($user->username), $deluser->email);
     $this->assertRegExp('/^' . preg_quote($user->email, '/') . '\\.\\d*$/', $deluser->username);
     $this->assertEquals(1, $DB->count_records('user', array('deleted' => 1)));
     // Test Event.
     $this->assertInstanceOf('\\core\\event\\user_deleted', $event);
     $this->assertSame($user->id, $event->objectid);
     $this->assertSame('user_deleted', $event->get_legacy_eventname());
     $this->assertEventLegacyData($user, $event);
     $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id={$user->id}", $user->firstname . ' ' . $user->lastname);
     $this->assertEventLegacyLogData($expectedlogdata, $event);
     $eventdata = $event->get_data();
     $this->assertSame($eventdata['other']['username'], $user->username);
     $this->assertSame($eventdata['other']['email'], $user->email);
     $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
     $this->assertSame($eventdata['other']['picture'], $user->picture);
     $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
     $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
     // Try invalid params.
     $record = new stdClass();
     $record->grrr = 1;
     try {
         delete_user($record);
         $this->fail('Expecting exception for invalid delete_user() $user parameter');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('coding_exception', $ex);
     }
     $record->id = 1;
     try {
         delete_user($record);
         $this->fail('Expecting exception for invalid delete_user() $user parameter');
     } catch (moodle_exception $ex) {
         $this->assertInstanceOf('coding_exception', $ex);
     }
     $record = new stdClass();
     $record->id = 666;
     $record->username = '******';
     $this->assertFalse($DB->record_exists('user', array('id' => 666)));
     // Any non-existent id is ok.
     $result = delete_user($record);
     $this->assertFalse($result);
     $result = delete_user($guest);
     $this->assertFalse($result);
     $result = delete_user($admin);
     $this->assertFalse($result);
     $this->resetDebugging();
 }
Ejemplo n.º 24
0
 function deleteuser($get, $post)
 {
     $uids = $get['ids'];
     if (! API_DELETEUSER) {
         return API_RETURN_FORBIDDEN;
     }
     
     if (delete_user($uids)) {
         return API_RETURN_SUCCEED;
     }
 }
<?php

include 'config.php';
/**  Switch Case to Get Action from controller  **/
switch ($_GET['action']) {
    case 'add_user':
        add_user();
        break;
    case 'get_users':
        get_users();
        break;
    case 'edit_user':
        edit_user();
        break;
    case 'delete_user':
        delete_user();
        break;
    case 'update_user':
        update_user();
        break;
}
/**  Function to Add User  **/
function add_user()
{
    $data = json_decode(file_get_contents("php://input"));
    // print_r($data);
    $full_name = $data->full_name;
    $addr_first = $data->addr_first;
    $addr_second = $data->addr_second;
    $addr_third = $data->addr_third;
    $postcode = $data->postcode;
Ejemplo n.º 26
0
 /**
  * Test that password history is deleted together with user.
  */
 public function test_delete_of_hashes_on_user_delete()
 {
     global $DB;
     $this->resetAfterTest();
     $user1 = $this->getDataGenerator()->create_user();
     $user2 = $this->getDataGenerator()->create_user();
     $DB->delete_records('user_password_history', array());
     set_config('passwordreuselimit', 3);
     user_add_password_history($user1->id, 'pokus');
     user_add_password_history($user2->id, 'pokus1');
     user_add_password_history($user2->id, 'pokus2');
     $this->assertEquals(3, $DB->count_records('user_password_history'));
     $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
     $this->assertEquals(2, $DB->count_records('user_password_history', array('userid' => $user2->id)));
     delete_user($user2);
     $this->assertEquals(1, $DB->count_records('user_password_history'));
     $this->assertEquals(1, $DB->count_records('user_password_history', array('userid' => $user1->id)));
     $this->assertEquals(0, $DB->count_records('user_password_history', array('userid' => $user2->id)));
 }
Ejemplo n.º 27
0
 /**
  * Validate that the export data does not include deleted users
  */
 public function test_version1exportexcludesdeletedusers()
 {
     global $CFG, $DB;
     if (file_exists($CFG->dirroot . '/local/elisprogram/lib/setup.php')) {
         // Needed to prevent error in PM delete handler.
         require_once $CFG->dirroot . '/local/elisprogram/lib/setup.php';
     }
     set_config('nonincremental', 1, 'dhexport_version1');
     $this->load_csv_data();
     // Clear the config admin list.
     set_config('siteadmins', '');
     // Delete the user the "correct" way.
     $user = $DB->get_record('user', array('id' => 101));
     delete_user($user);
     $data = $this->get_export_data();
     // Make sure only the header was included.
     $this->assertEquals(count($data), 1);
 }
Ejemplo n.º 28
0
 /**
  * Delete multiple users
  * @global object $DB
  * @param array|struct $params - need to be define as struct for XMLRPC
  * @subparam string $params:user->username
  * @return boolean result true if success
  */
 static function delete_users($params)
 {
     global $DB, $USER;
     $deletionsuccessfull = true;
     if (has_capability('moodle/user:delete', get_context_instance(CONTEXT_SYSTEM))) {
         foreach ($params as $userparams) {
             $username = clean_param($userparams['username'], PARAM_ALPHANUMEXT);
             $user = $DB->get_record('user', array('username' => $username, 'mnethostid' => 1));
             if (empty($user)) {
                 throw new moodle_exception('wscouldnotdeletenoexistinguser');
             }
             if (!delete_user($user)) {
                 $deletionsuccessfull = false;
                 //this function is in moodlelib.php
             }
         }
         return $deletionsuccessfull;
     } else {
         throw new moodle_exception('wscouldnotdeleteusernopermission');
     }
 }
Ejemplo n.º 29
0
 public function foreverdelete()
 {
     //彻底删除指定记录
     $ajax = intval($_REQUEST['ajax']);
     $id = $_REQUEST['id'];
     if (isset($id)) {
         $condition = array('id' => array('in', explode(',', $id)));
         $rel_data = M(MODULE_NAME)->where($condition)->findAll();
         foreach ($rel_data as $data) {
             $info[] = $data['user_name'];
         }
         if ($info) {
             $info = implode(",", $info);
         }
         $ids = explode(',', $id);
         foreach ($ids as $uid) {
             delete_user($uid);
         }
         save_log($info . l("FOREVER_DELETE_SUCCESS"), 1);
         clear_auto_cache("consignee_info");
         $this->success(l("FOREVER_DELETE_SUCCESS"), $ajax);
     } else {
         $this->error(l("INVALID_OPERATION"), $ajax);
     }
 }
Ejemplo n.º 30
0
function edituser_delete_submit(Pieform $form, $values)
{
    global $SESSION, $USER;
    if ($USER->get('admin')) {
        delete_user($values['id']);
        $SESSION->add_ok_msg(get_string('userdeletedsuccessfully', 'admin'));
    }
    redirect('/admin/users/search.php');
}