Esempio n. 1
1
/**
 * Adds module specific settings to the settings block.
 *
 * @param settings_navigation $settings The settings navigation object
 * @param stdClass $context The node context
 */
function local_loginas_extends_settings_navigation(settings_navigation $settings, $context)
{
    global $DB, $CFG, $PAGE, $USER;
    // Course id and context.
    $courseid = !empty($PAGE->course->id) ? $PAGE->course->id : SITEID;
    $coursecontext = context_course::instance($courseid);
    // Must have the loginas capability.
    if (!has_capability('moodle/user:loginas', $coursecontext)) {
        return;
    }
    // Set the settings category.
    $loginas = $settings->add(get_string('loginas'));
    // Login as list by admin setting.
    if (is_siteadmin($USER)) {
        // Admin settings page.
        $url = new moodle_url('/admin/settings.php', array('section' => 'localsettingloginas'));
        $loginas->add(get_string('settings'), $url, $settings::TYPE_SETTING);
        // Users list.
        $loginasusers = array();
        // Since 2.6, use all the required fields.
        $ufields = 'id, ' . get_all_user_name_fields(true);
        // Get users by id.
        if ($configuserids = get_config('local_loginas', 'loginasusers')) {
            $userids = explode(',', $configuserids);
            if ($users = $DB->get_records_list('user', 'id', $userids, '', $ufields)) {
                $loginasusers = $users;
            }
        }
        // Get users by username.
        if ($configusernames = get_config('local_loginas', 'loginasusernames')) {
            $usernames = explode(',', $configusernames);
            if ($users = $DB->get_records_list('user', 'username', $usernames, '', $ufields)) {
                $loginasusers = $loginasusers + $users;
            }
        }
        // Add action links for specified users.
        if ($loginasusers) {
            $params = array('id' => $courseid, 'sesskey' => sesskey());
            foreach ($loginasusers as $userid => $lauser) {
                $url = new moodle_url('/course/loginas.php', $params);
                $url->param('user', $userid);
                $loginas->add(fullname($lauser, true), $url, $settings::TYPE_SETTING);
            }
        }
    }
    // Course users login as.
    if (!($configcourseusers = get_config('local_loginas', 'courseusers'))) {
        return;
    }
    $loggedinas = \core\session\manager::is_loggedinas();
    if (!$loggedinas) {
        // Ajax link.
        $node = $loginas->add(get_string('courseusers', 'local_loginas'), 'javascript:void();', $settings::TYPE_SETTING);
        $node->add_class('local_loginas_setting_link');
        local_loginas_require_js($PAGE);
    }
}
 /**
  * Constructor.
  *
  * @param string $uniqueid Unique ID.
  * @param int $courseid Course ID.
  * @param int $groupid Group ID.
  */
 public function __construct($uniqueid, $courseid, $groupid)
 {
     parent::__construct($uniqueid);
     $this->courseid = $courseid;
     // Define columns.
     $this->define_columns(array('time', 'fullname', 'xp', 'eventname'));
     $this->define_headers(array(get_string('eventtime', 'block_xp'), get_string('fullname'), get_string('xp', 'block_xp'), get_string('eventname', 'block_xp')));
     // Define SQL.
     $sqlfrom = '';
     $sqlparams = array();
     if ($groupid) {
         $sqlfrom = '{block_xp_log} x
                  JOIN {groups_members} gm
                    ON gm.groupid = :groupid
                   AND gm.userid = x.userid
             LEFT JOIN {user} u
                    ON x.userid = u.id';
         $sqlparams = array('groupid' => $groupid);
     } else {
         $sqlfrom = '{block_xp_log} x LEFT JOIN {user} u ON x.userid = u.id';
     }
     // Define SQL.
     $this->sql = new stdClass();
     $this->sql->fields = 'x.*, ' . get_all_user_name_fields(true, 'u');
     $this->sql->from = $sqlfrom;
     $this->sql->where = 'courseid = :courseid';
     $this->sql->params = array_merge(array('courseid' => $courseid), $sqlparams);
     // Define various table settings.
     $this->sortable(true, 'time', SORT_DESC);
     $this->collapsible(false);
 }
Esempio n. 3
0
 /**
  * Return comments by pages
  *
  * @global moodle_database $DB
  * @param int $page
  * @return array An array of comments
  */
 function get_comments($page)
 {
     global $DB;
     if ($page == 0) {
         $start = 0;
     } else {
         $start = $page * $this->perpage;
     }
     $comments = array();
     $usernamefields = get_all_user_name_fields(true, 'u');
     $sql = "SELECT c.id, c.contextid, c.itemid, c.component, c.commentarea, c.userid, c.content, {$usernamefields}, c.timecreated\n                  FROM {comments} c\n                  JOIN {user} u\n                       ON u.id=c.userid\n              ORDER BY c.timecreated ASC";
     $rs = $DB->get_recordset_sql($sql, null, $start, $this->perpage);
     $formatoptions = array('overflowdiv' => true);
     foreach ($rs as $item) {
         // Set calculated fields
         $item->fullname = fullname($item);
         $item->time = userdate($item->timecreated);
         $item->content = format_text($item->content, FORMAT_MOODLE, $formatoptions);
         // Unset fields not related to the comment
         foreach (get_all_user_name_fields() as $namefield) {
             unset($item->{$namefield});
         }
         unset($item->timecreated);
         // Record the comment
         $comments[] = $item;
     }
     $rs->close();
     return $comments;
 }
Esempio n. 4
0
/**
 * Runs and exports, through email, the report instance specified by the
 * provided report schedule
 *
 * @param   stdClass  $report_schedule  The PHP report schedule containing the information
 *                                      about the specific report to be exported
 *
 * @return  boolean                     true on success, otherwise false
 */
function php_report_schedule_export_instance($report_schedule, $now = 0) {
    global $CFG, $USER;

    if ($now == 0) {
        $now = time();
    }

    $data = unserialize($report_schedule->config);

    // Create report to be emailed to recipient
    $shortname = $report_schedule->report;
    $format = $data['format'];
    // Initialize a temp path name
    $tmppath = '/temp';
    // Create a unique temporary filename to use for this schedule
    $filename = tempnam($CFG->dataroot.$tmppath, 'php_report_');

    $parameterdata = $data['parameters'];

    // Generate the report file
    $result = php_report::export_default_instance($shortname, $format, $filename, $parameterdata, $report_schedule->userid, php_report::EXECUTION_MODE_SCHEDULED);

    if (!$result) {
        //handle failure case
        unlink($filename);
        return false;
    }

    // Attach filename to an email - so get recipient...
    $recipients_array = explode(',',$data['recipients']);
    $from = get_string('noreplyname');
    $subject = get_string('email_subject','local_elisreports').$data['label'];
    $messagetext = html_to_text($data['message']);
    $messagehtml = $data['message'];
    $start = strlen($CFG->dataroot);
    $attachment = substr($filename,$start);
    $attachname = $report_schedule->report.$now.'.'.$data['format'];

    // $user->id & all other fields now required by Moodle 2.6+ email_to_user() API which also calls fullname($user)
    $user = new stdClass;
    $allfields = get_all_user_name_fields();
    foreach ($allfields as $field) {
        $user->$field = null;
    }
    $user->id = $USER->id; // let's just use this user as default (TBD)
    $user->mailformat = 1;

    // Attach the file to the recipients
    foreach ($recipients_array as $recipient) {
        $user->email = trim($recipient);
        email_to_user($user, $from, $subject, $messagetext, $messagehtml, $attachment, $attachname);
    }

    // Remove the file that was created for this report
    unlink($filename);

    return true;
}
 public function get_required_fields()
 {
     $allnames = get_all_user_name_fields();
     $requiredfields = array();
     foreach ($allnames as $allname) {
         $requiredfields[] = 'um.' . $allname . ' AS modifier' . $allname;
     }
     return $requiredfields;
 }
Esempio n. 6
0
 public function get_required_fields()
 {
     $allnames = get_all_user_name_fields();
     $requiredfields = array();
     foreach ($allnames as $allname) {
         $requiredfields[] = 'uc.' . $allname . ' AS creator' . $allname;
     }
     $requiredfields[] = 'q.timecreated';
     return $requiredfields;
 }
Esempio n. 7
0
 /**
  * Constructor.
  *
  * @param int $currentuserid The current user we are wanting to view messages for
  * @param int $otheruserid The other user we are wanting to view messages for
  * @param array $messages
  */
 public function __construct($currentuserid, $otheruserid, $messages)
 {
     $ufields = 'id, ' . get_all_user_name_fields(true) . ', lastaccess';
     $this->currentuserid = $currentuserid;
     if ($otheruserid) {
         $this->otheruserid = $otheruserid;
         $this->otheruser = \core_user::get_user($otheruserid, $ufields, MUST_EXIST);
     }
     $this->messages = $messages;
 }
Esempio n. 8
0
/**
 * Construct an object to supply to email_to_user()
 *
 * @param string $email the required email address
 * @param string $firstname The desired user first name
 * @return stdClass An object that can be supplied to email_to_user()
 */
function local_hub_create_contact_user($email, $firstname)
{
    $contactuser = new stdClass();
    // Need an id, can't use id=0. would rather not use id=1, lets fool the api while we're still trying to use a fake user to send to.
    $contactuser->id = 2;
    // Used to retrieve the mailcharset user preference which defaults to 0.
    $contactuser->email = $email;
    $contactuser->firstname = $firstname;
    $contactuser->lastname = '';
    foreach (get_all_user_name_fields() as $namefield) {
        if (!isset($contactuser->{$namefield})) {
            $contactuser->{$namefield} = '';
        }
    }
    return $contactuser;
}
 /**
  * Constructor.
  *
  * @param string $uniqueid Unique ID.
  */
 public function __construct($uniqueid, $courseid)
 {
     parent::__construct($uniqueid);
     $this->courseid = $courseid;
     // Define columns.
     $this->define_columns(array('time', 'fullname', 'xp', 'eventname', 'actions'));
     $this->define_headers(array(get_string('eventtime', 'block_xp'), get_string('fullname'), get_string('xp', 'block_xp'), get_string('eventname', 'block_xp'), ''));
     // Define SQL.
     $this->sql = new stdClass();
     $this->sql->fields = 'x.*, ' . get_all_user_name_fields(true, 'u');
     $this->sql->from = '{block_xp_log} x LEFT JOIN {user} u ON x.userid = u.id';
     $this->sql->where = 'courseid = :courseid';
     $this->sql->params = array('courseid' => $courseid);
     // Define various table settings.
     $this->sortable(true, 'time', SORT_DESC);
     $this->collapsible(false);
 }
Esempio n. 10
0
 function get_content()
 {
     global $CFG, $USER, $DB;
     if ($this->content !== NULL) {
         return $this->content;
     }
     $this->content = new stdClass();
     // get all the mentees, i.e. users you have a direct assignment to
     $allusernames = get_all_user_name_fields(true, 'u');
     if ($usercontexts = $DB->get_records_sql("SELECT c.instanceid, c.instanceid, {$allusernames}\n                                                    FROM {role_assignments} ra, {context} c, {user} u\n                                                   WHERE ra.userid = ?\n                                                         AND ra.contextid = c.id\n                                                         AND c.instanceid = u.id\n                                                         AND c.contextlevel = " . CONTEXT_USER, array($USER->id))) {
         $this->content->text = '<ul>';
         foreach ($usercontexts as $usercontext) {
             $this->content->text .= '<li><a href="' . $CFG->wwwroot . '/user/view.php?id=' . $usercontext->instanceid . '&amp;course=' . SITEID . '">' . fullname($usercontext) . '</a></li>';
         }
         $this->content->text .= '</ul>';
     }
     $this->content->footer = '';
     return $this->content;
 }
 public function definition()
 {
     global $COURSE;
     $context = context_course::instance($COURSE->id);
     $namefields = get_all_user_name_fields(true, 'u');
     $students = get_enrolled_users($context, 'mod/attendance:canbelisted', 0, 'u.id,' . $namefields . ',u.email', 'u.lastname, u.firstname', 0, 0, true);
     $partarray = array();
     foreach ($students as $student) {
         $partarray[$student->id] = fullname($student) . ' (' . $student->email . ')';
     }
     $mform = $this->_form;
     $description = $this->_customdata['description'];
     $mform->addElement('hidden', 'id', 0);
     $mform->setType('id', PARAM_INT);
     $mform->addElement('hidden', 'userid', 0);
     $mform->setType('userid', PARAM_INT);
     $mform->addElement('header', 'attheader', get_string('tempusermerge', 'attendance'));
     $mform->addElement('static', 'description', get_string('tempuser', 'attendance'), $description);
     $mform->addElement('select', 'participant', get_string('participant', 'attendance'), $partarray);
     $mform->addElement('static', 'requiredentries', '', get_string('requiredentries', 'attendance'));
     $mform->addHelpButton('requiredentries', 'requiredentry', 'attendance');
     $this->add_action_buttons(true, get_string('mergeuser', 'attendance'));
 }
 /**
  * Do the job.
  * Throw exceptions on errors (the job will be retried).
  */
 public function execute()
 {
     global $DB;
     // 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, u.auth, u.deleted,\n                                                     u.suspended, u.emailstop, u.mnethostid, u.mailformat,\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\n                                                     u.email !='' AND u.suspended = 0 AND\n                                                     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();
     }
 }
Esempio n. 13
0
/**
 * Gets all the users assigned this role in this context or higher
 *
 * @param int $roleid (can also be an array of ints!)
 * @param context $context
 * @param bool $parent if true, get list of users assigned in higher context too
 * @param string $fields fields from user (u.) , role assignment (ra) or role (r.)
 * @param string $sort sort from user (u.) , role assignment (ra.) or role (r.).
 *      null => use default sort from users_order_by_sql.
 * @param bool $all true means all, false means limit to enrolled users
 * @param string $group defaults to ''
 * @param mixed $limitfrom defaults to ''
 * @param mixed $limitnum defaults to ''
 * @param string $extrawheretest defaults to ''
 * @param array $whereorsortparams any paramter values used by $sort or $extrawheretest.
 * @return array
 */
function get_role_users($roleid, context $context, $parent = false, $fields = '',
        $sort = null, $all = true, $group = '',
        $limitfrom = '', $limitnum = '', $extrawheretest = '', $whereorsortparams = array()) {
    global $DB;

    if (empty($fields)) {
        $allnames = get_all_user_name_fields(true, 'u');
        $fields = 'u.id, u.confirmed, u.username, '. $allnames . ', ' .
                  'u.maildisplay, u.mailformat, u.maildigest, u.email, u.emailstop, u.city, '.
                  'u.country, u.picture, u.idnumber, u.department, u.institution, '.
                  'u.lang, u.timezone, u.lastaccess, u.mnethostid, r.name AS rolename, r.sortorder, '.
                  'r.shortname AS roleshortname, rn.name AS rolecoursealias';
    }

    $parentcontexts = '';
    if ($parent) {
        $parentcontexts = substr($context->path, 1); // kill leading slash
        $parentcontexts = str_replace('/', ',', $parentcontexts);
        if ($parentcontexts !== '') {
            $parentcontexts = ' OR ra.contextid IN ('.$parentcontexts.' )';
        }
    }

    if ($roleid) {
        list($rids, $params) = $DB->get_in_or_equal($roleid, SQL_PARAMS_NAMED, 'r');
        $roleselect = "AND ra.roleid $rids";
    } else {
        $params = array();
        $roleselect = '';
    }

    if ($coursecontext = $context->get_course_context(false)) {
        $params['coursecontext'] = $coursecontext->id;
    } else {
        $params['coursecontext'] = 0;
    }

    if ($group) {
        $groupjoin   = "JOIN {groups_members} gm ON gm.userid = u.id";
        $groupselect = " AND gm.groupid = :groupid ";
        $params['groupid'] = $group;
    } else {
        $groupjoin   = '';
        $groupselect = '';
    }

    $params['contextid'] = $context->id;

    if ($extrawheretest) {
        $extrawheretest = ' AND ' . $extrawheretest;
    }

    if ($whereorsortparams) {
        $params = array_merge($params, $whereorsortparams);
    }

    if (!$sort) {
        list($sort, $sortparams) = users_order_by_sql('u');
        $params = array_merge($params, $sortparams);
    }

    if ($all === null) {
        // Previously null was used to indicate that parameter was not used.
        $all = true;
    }
    if (!$all and $coursecontext) {
        // Do not use get_enrolled_sql() here for performance reasons.
        $ejoin = "JOIN {user_enrolments} ue ON ue.userid = u.id
                  JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :ecourseid)";
        $params['ecourseid'] = $coursecontext->instanceid;
    } else {
        $ejoin = "";
    }

    $sql = "SELECT DISTINCT $fields, ra.roleid
              FROM {role_assignments} ra
              JOIN {user} u ON u.id = ra.userid
              JOIN {role} r ON ra.roleid = r.id
            $ejoin
         LEFT JOIN {role_names} rn ON (rn.contextid = :coursecontext AND rn.roleid = r.id)
        $groupjoin
             WHERE (ra.contextid = :contextid $parentcontexts)
                   $roleselect
                   $groupselect
                   $extrawheretest
          ORDER BY $sort";                  // join now so that we can just use fullname() later

    return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
}
 protected static function tempuser_to_user($tempuser)
 {
     $ret = (object) array('id' => $tempuser->studentid, 'firstname' => $tempuser->fullname, 'email' => $tempuser->email, 'username' => '', 'enrolmentstatus' => 0, 'enrolmentstart' => 0, 'enrolmentend' => 0, 'picture' => 0, 'type' => 'temporary');
     foreach (get_all_user_name_fields() as $namefield) {
         if (!isset($ret->{$namefield})) {
             $ret->{$namefield} = '';
         }
     }
     return $ret;
 }
Esempio n. 15
0
/**
 * Returns all forum posts since a given time in specified forum.
 *
 * @todo Document this functions args
 * @global object
 * @global object
 * @global object
 * @global object
 */
function forum_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid = 0, $groupid = 0)
{
    global $CFG, $COURSE, $USER, $DB;
    if ($COURSE->id == $courseid) {
        $course = $COURSE;
    } else {
        $course = $DB->get_record('course', array('id' => $courseid));
    }
    $modinfo = get_fast_modinfo($course);
    $cm = $modinfo->cms[$cmid];
    $params = array($timestart, $cm->instance);
    if ($userid) {
        $userselect = "AND u.id = ?";
        $params[] = $userid;
    } else {
        $userselect = "";
    }
    if ($groupid) {
        $groupselect = "AND d.groupid = ?";
        $params[] = $groupid;
    } else {
        $groupselect = "";
    }
    $allnames = get_all_user_name_fields(true, 'u');
    if (!($posts = $DB->get_records_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,\n                                              d.timestart, d.timeend, d.userid AS duserid,\n                                              {$allnames}, u.email, u.picture, u.imagealt, u.email\n                                         FROM {forum_posts} p\n                                              JOIN {forum_discussions} d ON d.id = p.discussion\n                                              JOIN {forum} f             ON f.id = d.forum\n                                              JOIN {user} u              ON u.id = p.userid\n                                        WHERE p.created > ? AND f.id = ?\n                                              {$userselect} {$groupselect}\n                                     ORDER BY p.id ASC", $params))) {
        // order by initial posting date
        return;
    }
    $groupmode = groups_get_activity_groupmode($cm, $course);
    $cm_context = context_module::instance($cm->id);
    $viewhiddentimed = has_capability('mod/forum:viewhiddentimedposts', $cm_context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
    $printposts = array();
    foreach ($posts as $post) {
        if (!empty($CFG->forum_enabletimedposts) and $USER->id != $post->duserid and ($post->timestart > 0 and $post->timestart > time() or $post->timeend > 0 and $post->timeend < time())) {
            if (!$viewhiddentimed) {
                continue;
            }
        }
        if ($groupmode) {
            if ($post->groupid == -1 or $groupmode == VISIBLEGROUPS or $accessallgroups) {
                // oki (Open discussions have groupid -1)
            } else {
                // separate mode
                if (isguestuser()) {
                    // shortcut
                    continue;
                }
                if (!in_array($post->groupid, $modinfo->get_groups($cm->groupingid))) {
                    continue;
                }
            }
        }
        $printposts[] = $post;
    }
    if (!$printposts) {
        return;
    }
    $aname = format_string($cm->name, true);
    foreach ($printposts as $post) {
        $tmpactivity = new stdClass();
        $tmpactivity->type = 'forum';
        $tmpactivity->cmid = $cm->id;
        $tmpactivity->name = $aname;
        $tmpactivity->sectionnum = $cm->sectionnum;
        $tmpactivity->timestamp = $post->modified;
        $tmpactivity->content = new stdClass();
        $tmpactivity->content->id = $post->id;
        $tmpactivity->content->discussion = $post->discussion;
        $tmpactivity->content->subject = format_string($post->subject);
        $tmpactivity->content->parent = $post->parent;
        $tmpactivity->user = new stdClass();
        $additionalfields = array('id' => 'userid', 'picture', 'imagealt', 'email');
        $additionalfields = explode(',', user_picture::fields());
        $tmpactivity->user = username_load_fields_from_object($tmpactivity->user, $post, null, $additionalfields);
        $tmpactivity->user->id = $post->userid;
        $activities[$index++] = $tmpactivity;
    }
    return;
}
Esempio n. 16
0
}
//UAIOPEN - tiene los permisos necesarios para ver todos los grupos
if (has_capability('moodle/site:accessallgroups', $context)) {
    echo '<p><input type="submit" name="act_showautocreategroupsform" id="showautocreategroupsform" value="' . get_string('autocreategroups', 'group') . '" /></p>' . "\n";
    echo '<p><input type="submit" name="act_showimportgroups" id="showimportgroups" value="' . get_string('importgroups', 'core_group') . '" /></p>' . "\n";
}
echo '</td>' . "\n";
echo '<td>' . "\n";
echo '<p><label for="members"><span id="memberslabel">' . get_string('membersofselectedgroup', 'group') . ' </span><span id="thegroup">' . $selectedname . '</span></label></p>' . "\n";
//NOTE: the SELECT was, multiple="multiple" name="user[]" - not used and breaks onclick.
echo '<select name="user" id="members" size="15" class="select"' . "\n";
echo ' onclick="window.status=this.options[this.selectedIndex].title;" onmouseout="window.status=\'\';">' . "\n";
$member_names = array();
$atleastonemember = false;
if ($singlegroup) {
    if ($groupmemberroles = groups_get_members_by_role($groupids[0], $courseid, 'u.id, ' . get_all_user_name_fields(true, 'u'))) {
        foreach ($groupmemberroles as $roleid => $roledata) {
            echo '<optgroup label="' . s($roledata->name) . '">';
            foreach ($roledata->users as $member) {
                echo '<option value="' . $member->id . '">' . fullname($member, true) . '</option>';
                $atleastonemember = true;
            }
            echo '</optgroup>';
        }
    }
}
if (!$atleastonemember) {
    // Print an empty option to avoid the XHTML error of having an empty select element
    echo '<option>&nbsp;</option>';
}
echo '</select>' . "\n";
Esempio n. 17
0
$PAGE->navbar->add(get_string('pluginname', 'local_help_desk'));
$PAGE->navbar->add(get_string('accounts', 'local_help_desk'));
$PAGE->set_heading($SITE->fullname);
$renderer = $PAGE->get_renderer('local_help_desk');
$lib_help_desk = new help_desk();
$hierarchy = new hierarchy();
$ufiltering = new user_filtering_accounts();
//Tab tree (current tab)
$tab = 'accounts';
$serialkey_form = new accounts_serialkey_form(NULL, array('skid' => $skid));
echo $OUTPUT->header();
$lib_help_desk->createtabview($tab);
//Tab tree
$extracolumns = get_extra_user_fields($systemcontext);
$ufiltering = new user_filtering_accounts();
$allusernamefields = get_all_user_name_fields(false, null, null, null, true);
$columns = array_merge($allusernamefields, $extracolumns, array('city', 'country', 'lastaccess'));
foreach ($columns as $column) {
    $string[$column] = get_user_field_name($column);
    if ($sort != $column) {
        $columnicon = "";
        if ($column == "lastaccess") {
            $columndir = "DESC";
        } else {
            $columndir = "ASC";
        }
    } else {
        $columndir = $dir == "ASC" ? "DESC" : "ASC";
        if ($column == "lastaccess") {
            $columnicon = $dir == "ASC" ? "sort_desc" : "sort_asc";
        } else {
 public function test_get_all_user_name_fields()
 {
     $this->resetAfterTest();
     // Additional names in an array.
     $testarray = array('firstnamephonetic' => 'firstnamephonetic', 'lastnamephonetic' => 'lastnamephonetic', 'middlename' => 'middlename', 'alternatename' => 'alternatename', 'firstname' => 'firstname', 'lastname' => 'lastname');
     $this->assertEquals($testarray, get_all_user_name_fields());
     // Additional names as a string.
     $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
     $this->assertEquals($teststring, get_all_user_name_fields(true));
     // Additional names as a string with an alias.
     $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
     $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
     // Additional name fields with a prefix - object.
     $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic', 'lastnamephonetic' => 'authorlastnamephonetic', 'middlename' => 'authormiddlename', 'alternatename' => 'authoralternatename', 'firstname' => 'authorfirstname', 'lastname' => 'authorlastname');
     $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
     // Additional name fields with an alias and a title - string.
     $teststring = 'u.firstnamephonetic AS authorfirstnamephonetic,u.lastnamephonetic AS authorlastnamephonetic,u.middlename AS authormiddlename,u.alternatename AS authoralternatename,u.firstname AS authorfirstname,u.lastname AS authorlastname';
     $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
 }
Esempio n. 19
0
 /**
  * Get a list of graders.
  *
  * @param int $courseid Id of course for which we need to fetch graders.
  *
  * @return array list of graders.
  */
 public static function get_graders($courseid)
 {
     global $DB;
     $ufields = get_all_user_name_fields(true, 'u');
     $sql = "SELECT u.id, {$ufields}\n                  FROM {user} u\n                  JOIN {grade_grades_history} ggh ON ggh.usermodified = u.id\n                  JOIN {grade_items} gi ON gi.id = ggh.itemid\n                 WHERE gi.courseid = :courseid\n              GROUP BY u.id, {$ufields}\n              ORDER BY u.lastname ASC, u.firstname ASC";
     $graders = $DB->get_records_sql($sql, array('courseid' => $courseid));
     $return = array(0 => get_string('allgraders', 'gradereport_history'));
     foreach ($graders as $grader) {
         $return[$grader->id] = fullname($grader);
     }
     return $return;
 }
Esempio n. 20
0
/**
 * Generate any blog RSS feed via one function
 *
 * @param stdClass $context The context of the blog for which the feed it being generated
 * @param array    $args    An array of arguements needed to build the feed (contextid, token, componentname, type, id, tagid)
 */
function blog_rss_get_feed($context, $args)
{
    global $CFG, $SITE, $DB;
    if (empty($CFG->enableblogs)) {
        debugging('Blogging disabled on this site, RSS feeds are not available');
        return null;
    }
    if (empty($CFG->enablerssfeeds)) {
        debugging('Sorry, RSS feeds are disabled on this site');
        return '';
    }
    if ($CFG->bloglevel == BLOG_SITE_LEVEL) {
        if (isguestuser()) {
            debugging(get_string('nopermissiontoshow', 'error'));
            return '';
        }
    }
    $sitecontext = context_system::instance();
    if (!has_capability('moodle/blog:view', $sitecontext)) {
        return null;
    }
    $type = clean_param($args[3], PARAM_ALPHA);
    $id = clean_param($args[4], PARAM_INT);
    // Could be groupid / courseid  / userid  depending on $type.
    $tagid = 0;
    if ($args[5] != 'rss.xml') {
        $tagid = clean_param($args[5], PARAM_INT);
    } else {
        $tagid = 0;
    }
    $filename = blog_rss_file_name($type, $id, $tagid);
    if (file_exists($filename)) {
        if (filemtime($filename) + 3600 > time()) {
            return $filename;
            // It's already done so we return cached version.
        }
    }
    $courseid = $groupid = $userid = null;
    switch ($type) {
        case 'site':
            break;
        case 'course':
            $courseid = $id;
            break;
        case 'group':
            $groupid = $id;
            break;
        case 'user':
            $userid = $id;
            break;
    }
    // Get all the entries from the database.
    require_once $CFG->dirroot . '/blog/locallib.php';
    $blogheaders = blog_get_headers($courseid, $groupid, $userid, $tagid);
    $bloglisting = new blog_listing($blogheaders['filters']);
    $blogentries = $bloglisting->get_entries();
    // Now generate an array of RSS items.
    if ($blogentries) {
        $items = array();
        foreach ($blogentries as $blogentry) {
            $item = new stdClass();
            $item->author = fullname($DB->get_record('user', array('id' => $blogentry->userid)));
            // TODO: this is slow.
            $item->title = $blogentry->subject;
            $item->pubdate = $blogentry->lastmodified;
            $item->link = $CFG->wwwroot . '/blog/index.php?entryid=' . $blogentry->id;
            $summary = file_rewrite_pluginfile_urls($blogentry->summary, 'pluginfile.php', $sitecontext->id, 'blog', 'post', $blogentry->id);
            $item->description = format_text($summary, $blogentry->format);
            if ($blogtags = core_tag_tag::get_item_tags_array('core', 'post', $blogentry->id)) {
                $item->tags = $blogtags;
                $item->tagscheme = $CFG->wwwroot . '/tag';
            }
            $items[] = $item;
        }
        $articles = rss_add_items($items);
        // Change structure to XML.
    } else {
        $articles = '';
    }
    // Get header and footer information.
    switch ($type) {
        case 'user':
            $info = fullname($DB->get_record('user', array('id' => $id), get_all_user_name_fields(true)));
            break;
        case 'course':
            $info = $DB->get_field('course', 'fullname', array('id' => $id));
            $info = format_string($info, true, array('context' => context_course::instance($id)));
            break;
        case 'site':
            $info = format_string($SITE->fullname, true, array('context' => context_course::instance(SITEID)));
            break;
        case 'group':
            $group = groups_get_group($id);
            $info = $group->name;
            // TODO: $DB->get_field('groups', 'name', array('id' => $id)).
            break;
        default:
            $info = '';
            break;
    }
    if ($tagid) {
        $info .= ': ' . $DB->get_field('tags', 'text', array('id' => $tagid));
    }
    $header = rss_standard_header(get_string($type . 'blog', 'blog', $info), $CFG->wwwroot . '/blog/index.php', get_string('intro', 'blog'));
    $footer = rss_standard_footer();
    // Save the XML contents to file.
    $rssdata = $header . $articles . $footer;
    if (blog_rss_save_file($type, $id, $tagid, $rssdata)) {
        return $filename;
    } else {
        return false;
        // Couldn't find it or make it.
    }
}
 /**
  * Return all the fields to be used for users in questionnaire sql.
  *
  * @author: Guy Thomas
  * @return array|string
  */
 protected function user_fields()
 {
     $userfieldsarr = get_all_user_name_fields();
     $userfieldsarr = array_merge($userfieldsarr, ['username', 'department', 'institution']);
     return $userfieldsarr;
 }
Esempio n. 22
0
 /**
  * @param string $u the table alias for the user table in the query being
  *      built. May be ''.
  * @return string fragment of SQL to go in the select list of the query.
  */
 protected function required_fields_sql($u)
 {
     // Raw list of fields.
     $fields = array('id');
     // Add additional name fields
     $fields = array_merge($fields, get_all_user_name_fields(), $this->extrafields);
     // Prepend the table alias.
     if ($u) {
         foreach ($fields as &$field) {
             $field = $u . '.' . $field;
         }
     }
     return implode(',', $fields);
 }
 /**
  * Called to define this moodle form
  *
  * @return void
  */
 public function definition()
 {
     global $USER, $DB, $PAGE;
     $mform =& $this->_form;
     $course = $this->_customdata['course'];
     $cm = $this->_customdata['cm'];
     $modcontext = $this->_customdata['modcontext'];
     $mform->addElement('header', 'general', get_string('export', 'attendance'));
     $groupmode = groups_get_activity_groupmode($cm, $course);
     $groups = groups_get_activity_allowed_groups($cm, $USER->id);
     if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
         $grouplist[0] = get_string('allparticipants');
     }
     if ($groups) {
         foreach ($groups as $group) {
             $grouplist[$group->id] = $group->name;
         }
     }
     $mform->addElement('select', 'group', get_string('group'), $grouplist);
     // Restrict the export to the selected users.
     $namefields = get_all_user_name_fields(true, 'u');
     $allusers = get_enrolled_users($modcontext, 'mod/attendance:canbelisted', 0, 'u.id,' . $namefields);
     $userlist = array();
     foreach ($allusers as $user) {
         $userlist[$user->id] = fullname($user);
     }
     unset($allusers);
     $tempusers = $DB->get_records('attendance_tempusers', array('courseid' => $course->id), 'studentid, fullname');
     foreach ($tempusers as $user) {
         $userlist[$user->studentid] = $user->fullname;
     }
     list($gsql, $gparams) = $DB->get_in_or_equal(array_keys($grouplist), SQL_PARAMS_NAMED);
     list($usql, $uparams) = $DB->get_in_or_equal(array_keys($userlist), SQL_PARAMS_NAMED);
     $params = array_merge($gparams, $uparams);
     $groupmembers = $DB->get_recordset_select('groups_members', "groupid {$gsql} AND userid {$usql}", $params, '', 'groupid, userid');
     $groupmappings = array();
     foreach ($groupmembers as $groupmember) {
         if (!isset($groupmappings[$groupmember->groupid])) {
             $groupmappings[$groupmember->groupid] = array();
         }
         $groupmappings[$groupmember->groupid][$groupmember->userid] = $userlist[$groupmember->userid];
     }
     if (isset($grouplist[0])) {
         $groupmappings[0] = $userlist;
     }
     $mform->addElement('selectyesno', 'selectedusers', get_string('onlyselectedusers', 'mod_attendance'));
     $sel = $mform->addElement('select', 'users', get_string('users', 'mod_attendance'), $userlist, array('size' => 12));
     $sel->setMultiple(true);
     $mform->disabledIf('users', 'selectedusers', 'eq', 0);
     $opts = array('groupmappings' => $groupmappings);
     $PAGE->requires->yui_module('moodle-mod_attendance-groupfilter', 'M.mod_attendance.groupfilter.init', array($opts));
     $ident = array();
     $ident[] =& $mform->createElement('checkbox', 'id', '', get_string('studentid', 'attendance'));
     $ident[] =& $mform->createElement('checkbox', 'uname', '', get_string('username'));
     $optional = array('idnumber', 'institution', 'department');
     foreach ($optional as $opt) {
         $ident[] =& $mform->createElement('checkbox', $opt, '', get_string($opt));
         $mform->setType($opt, PARAM_NOTAGS);
     }
     $mform->addGroup($ident, 'ident', get_string('identifyby', 'attendance'), array('<br />'), true);
     $mform->setDefaults(array('ident[id]' => true, 'ident[uname]' => true));
     $mform->setType('id', PARAM_INT);
     $mform->setType('uname', PARAM_INT);
     $mform->addElement('checkbox', 'includeallsessions', get_string('includeall', 'attendance'), get_string('yes'));
     $mform->setDefault('includeallsessions', true);
     $mform->addElement('checkbox', 'includenottaken', get_string('includenottaken', 'attendance'), get_string('yes'));
     $mform->addElement('checkbox', 'includeremarks', get_string('includeremarks', 'attendance'), get_string('yes'));
     $mform->addElement('date_selector', 'sessionstartdate', get_string('startofperiod', 'attendance'));
     $mform->setDefault('sessionstartdate', $course->startdate);
     $mform->disabledIf('sessionstartdate', 'includeallsessions', 'checked');
     $mform->addElement('date_selector', 'sessionenddate', get_string('endofperiod', 'attendance'));
     $mform->disabledIf('sessionenddate', 'includeallsessions', 'checked');
     $mform->addElement('select', 'format', get_string('format'), array('excel' => get_string('downloadexcel', 'attendance'), 'ooo' => get_string('downloadooo', 'attendance'), 'text' => get_string('downloadtext', 'attendance')));
     $submitstring = get_string('ok');
     $this->add_action_buttons(false, $submitstring);
     $mform->addElement('hidden', 'id', $cm->id);
 }
Esempio n. 24
0
 /**
  * Load all of the uses who have the capability into choice array
  *
  * @return bool Always returns true
  */
 function load_choices()
 {
     if (is_array($this->choices)) {
         return true;
     }
     list($sort, $sortparams) = users_order_by_sql('u');
     if (!empty($sortparams)) {
         throw new coding_exception('users_order_by_sql returned some query parameters. ' . 'This is unexpected, and a problem because there is no way to pass these ' . 'parameters to get_users_by_capability. See MDL-34657.');
     }
     $userfields = 'u.id, u.username, ' . get_all_user_name_fields(true, 'u');
     $users = get_users_by_capability(context_system::instance(), $this->capability, $userfields, $sort);
     $this->choices = array('$@NONE@$' => get_string('nobody'), '$@ALL@$' => get_string('everyonewhocan', 'admin', get_capability_string($this->capability)));
     if ($this->includeadmins) {
         $admins = get_admins();
         foreach ($admins as $user) {
             $this->choices[$user->id] = fullname($user);
         }
     }
     if (is_array($users)) {
         foreach ($users as $user) {
             $this->choices[$user->id] = fullname($user);
         }
     }
     return true;
 }
Esempio n. 25
0
 } else {
     $isff = core_useragent::check_browser_version('Gecko');
 }
 if ($isff) {
     $blankcolspan = 'colspan="999" ';
 } else {
     $blankcolspan = '';
 }
 $questions = $DB->get_records('realtimequiz_question', array('quizid' => $realtimequiz->id), 'questionnum');
 $linkurl = new moodle_url('/mod/realtimequiz/responses.php', array('id' => $cm->id, 'showsession' => $showsession));
 if ($showusers) {
     $linkurl->param('showusers', 1);
     if ($CFG->version < 2013111800) {
         $usernames = 'u.firstname, u.lastname';
     } else {
         $usernames = get_all_user_name_fields(true, 'u');
     }
     $sql = 'SELECT DISTINCT u.id, ' . $usernames . '
               FROM {user} u
               JOIN {realtimequiz_submitted} s ON s.userid = u.id
               JOIN {realtimequiz_question} q ON s.questionid = q.id
              WHERE q.quizid = :quizid';
     $params = array('quizid' => $realtimequiz->id);
     if ($showsession) {
         $sql .= ' AND s.sessionid = :sessionid';
         $params['sessionid'] = $showsession;
     }
     $sql .= ' ORDER BY u.firstname ASC';
     $users = $DB->get_records_sql($sql, $params);
     if ($page * $perpage > count($users)) {
         $page = 0;
Esempio n. 26
0
/**
 * Reduces lines of duplicated code for getting user name fields.
 *
 * See also {@link user_picture::unalias()}
 *
 * @param object $addtoobject Object to add user name fields to.
 * @param object $secondobject Object that contains user name field information.
 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
 * @param array $additionalfields Additional fields to be matched with data in the second object.
 * The key can be set to the user table field name.
 * @return object User name fields.
 */
function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null)
{
    $fields = get_all_user_name_fields(false, null, $prefix);
    if ($additionalfields) {
        // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
        // the key is a number and then sets the key to the array value.
        foreach ($additionalfields as $key => $value) {
            if (is_numeric($key)) {
                $additionalfields[$value] = $prefix . $value;
                unset($additionalfields[$key]);
            } else {
                $additionalfields[$key] = $prefix . $value;
            }
        }
        $fields = array_merge($fields, $additionalfields);
    }
    foreach ($fields as $key => $field) {
        // Important that we have all of the user name fields present in the object that we are sending back.
        $addtoobject->{$key} = '';
        if (isset($secondobject->{$field})) {
            $addtoobject->{$key} = $secondobject->{$field};
        }
    }
    return $addtoobject;
}
Esempio n. 27
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");
}
Esempio n. 28
0
 /**
  * Prepares data object with all workshop grades to be rendered
  *
  * @param int $userid the user we are preparing the report for
  * @param int $groupid if non-zero, prepare the report for the given group only
  * @param int $page the current page (for the pagination)
  * @param int $perpage participants per page (for the pagination)
  * @param string $sortby lastname|firstname|submissiontitle|submissiongrade|gradinggrade
  * @param string $sorthow ASC|DESC
  * @return stdclass data for the renderer
  */
 public function prepare_grading_report_data($userid, $groupid, $page, $perpage, $sortby, $sorthow)
 {
     global $DB;
     $canviewall = has_capability('mod/workshop:viewallassessments', $this->context, $userid);
     $isparticipant = $this->is_participant($userid);
     if (!$canviewall and !$isparticipant) {
         // who the hell is this?
         return array();
     }
     if (!in_array($sortby, array('lastname', 'firstname', 'submissiontitle', 'submissiongrade', 'gradinggrade'))) {
         $sortby = 'lastname';
     }
     if (!($sorthow === 'ASC' or $sorthow === 'DESC')) {
         $sorthow = 'ASC';
     }
     // get the list of user ids to be displayed
     if ($canviewall) {
         $participants = $this->get_participants(false, $groupid);
     } else {
         // this is an ordinary workshop participant (aka student) - display the report just for him/her
         $participants = array($userid => (object) array('id' => $userid));
     }
     // we will need to know the number of all records later for the pagination purposes
     $numofparticipants = count($participants);
     if ($numofparticipants > 0) {
         // load all fields which can be used for sorting and paginate the records
         list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
         $params['workshopid1'] = $this->id;
         $params['workshopid2'] = $this->id;
         $sqlsort = array();
         $sqlsortfields = array($sortby => $sorthow) + array('lastname' => 'ASC', 'firstname' => 'ASC', 'u.id' => 'ASC');
         foreach ($sqlsortfields as $sqlsortfieldname => $sqlsortfieldhow) {
             $sqlsort[] = $sqlsortfieldname . ' ' . $sqlsortfieldhow;
         }
         $sqlsort = implode(',', $sqlsort);
         $picturefields = user_picture::fields('u', array(), 'userid');
         $sql = "SELECT {$picturefields}, s.title AS submissiontitle, s.grade AS submissiongrade, ag.gradinggrade\n                      FROM {user} u\n                 LEFT JOIN {workshop_submissions} s ON (s.authorid = u.id AND s.workshopid = :workshopid1 AND s.example = 0)\n                 LEFT JOIN {workshop_aggregations} ag ON (ag.userid = u.id AND ag.workshopid = :workshopid2)\n                     WHERE u.id {$participantids}\n                  ORDER BY {$sqlsort}";
         $participants = $DB->get_records_sql($sql, $params, $page * $perpage, $perpage);
     } else {
         $participants = array();
     }
     // this will hold the information needed to display user names and pictures
     $userinfo = array();
     // get the user details for all participants to display
     $additionalnames = get_all_user_name_fields();
     foreach ($participants as $participant) {
         if (!isset($userinfo[$participant->userid])) {
             $userinfo[$participant->userid] = new stdclass();
             $userinfo[$participant->userid]->id = $participant->userid;
             $userinfo[$participant->userid]->picture = $participant->picture;
             $userinfo[$participant->userid]->imagealt = $participant->imagealt;
             $userinfo[$participant->userid]->email = $participant->email;
             foreach ($additionalnames as $addname) {
                 $userinfo[$participant->userid]->{$addname} = $participant->{$addname};
             }
         }
     }
     // load the submissions details
     $submissions = $this->get_submissions(array_keys($participants));
     // get the user details for all moderators (teachers) that have overridden a submission grade
     foreach ($submissions as $submission) {
         if (!isset($userinfo[$submission->gradeoverby])) {
             $userinfo[$submission->gradeoverby] = new stdclass();
             $userinfo[$submission->gradeoverby]->id = $submission->gradeoverby;
             $userinfo[$submission->gradeoverby]->picture = $submission->overpicture;
             $userinfo[$submission->gradeoverby]->imagealt = $submission->overimagealt;
             $userinfo[$submission->gradeoverby]->email = $submission->overemail;
             foreach ($additionalnames as $addname) {
                 $temp = 'over' . $addname;
                 $userinfo[$submission->gradeoverby]->{$addname} = $submission->{$temp};
             }
         }
     }
     // get the user details for all reviewers of the displayed participants
     $reviewers = array();
     if ($submissions) {
         list($submissionids, $params) = $DB->get_in_or_equal(array_keys($submissions), SQL_PARAMS_NAMED);
         list($sort, $sortparams) = users_order_by_sql('r');
         $picturefields = user_picture::fields('r', array(), 'reviewerid');
         $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.weight,\n                           {$picturefields}, s.id AS submissionid, s.authorid\n                      FROM {workshop_assessments} a\n                      JOIN {user} r ON (a.reviewerid = r.id)\n                      JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)\n                     WHERE a.submissionid {$submissionids}\n                  ORDER BY a.weight DESC, {$sort}";
         $reviewers = $DB->get_records_sql($sql, array_merge($params, $sortparams));
         foreach ($reviewers as $reviewer) {
             if (!isset($userinfo[$reviewer->reviewerid])) {
                 $userinfo[$reviewer->reviewerid] = new stdclass();
                 $userinfo[$reviewer->reviewerid]->id = $reviewer->reviewerid;
                 $userinfo[$reviewer->reviewerid]->picture = $reviewer->picture;
                 $userinfo[$reviewer->reviewerid]->imagealt = $reviewer->imagealt;
                 $userinfo[$reviewer->reviewerid]->email = $reviewer->email;
                 foreach ($additionalnames as $addname) {
                     $userinfo[$reviewer->reviewerid]->{$addname} = $reviewer->{$addname};
                 }
             }
         }
     }
     // get the user details for all reviewees of the displayed participants
     $reviewees = array();
     if ($participants) {
         list($participantids, $params) = $DB->get_in_or_equal(array_keys($participants), SQL_PARAMS_NAMED);
         list($sort, $sortparams) = users_order_by_sql('e');
         $params['workshopid'] = $this->id;
         $picturefields = user_picture::fields('e', array(), 'authorid');
         $sql = "SELECT a.id AS assessmentid, a.submissionid, a.grade, a.gradinggrade, a.gradinggradeover, a.reviewerid, a.weight,\n                           s.id AS submissionid, {$picturefields}\n                      FROM {user} u\n                      JOIN {workshop_assessments} a ON (a.reviewerid = u.id)\n                      JOIN {workshop_submissions} s ON (a.submissionid = s.id AND s.example = 0)\n                      JOIN {user} e ON (s.authorid = e.id)\n                     WHERE u.id {$participantids} AND s.workshopid = :workshopid\n                  ORDER BY a.weight DESC, {$sort}";
         $reviewees = $DB->get_records_sql($sql, array_merge($params, $sortparams));
         foreach ($reviewees as $reviewee) {
             if (!isset($userinfo[$reviewee->authorid])) {
                 $userinfo[$reviewee->authorid] = new stdclass();
                 $userinfo[$reviewee->authorid]->id = $reviewee->authorid;
                 $userinfo[$reviewee->authorid]->picture = $reviewee->picture;
                 $userinfo[$reviewee->authorid]->imagealt = $reviewee->imagealt;
                 $userinfo[$reviewee->authorid]->email = $reviewee->email;
                 foreach ($additionalnames as $addname) {
                     $userinfo[$reviewee->authorid]->{$addname} = $reviewee->{$addname};
                 }
             }
         }
     }
     // finally populate the object to be rendered
     $grades = $participants;
     foreach ($participants as $participant) {
         // set up default (null) values
         $grades[$participant->userid]->submissionid = null;
         $grades[$participant->userid]->submissiontitle = null;
         $grades[$participant->userid]->submissiongrade = null;
         $grades[$participant->userid]->submissiongradeover = null;
         $grades[$participant->userid]->submissiongradeoverby = null;
         $grades[$participant->userid]->submissionpublished = null;
         $grades[$participant->userid]->reviewedby = array();
         $grades[$participant->userid]->reviewerof = array();
     }
     unset($participants);
     unset($participant);
     foreach ($submissions as $submission) {
         $grades[$submission->authorid]->submissionid = $submission->id;
         $grades[$submission->authorid]->submissiontitle = $submission->title;
         $grades[$submission->authorid]->submissiongrade = $this->real_grade($submission->grade);
         $grades[$submission->authorid]->submissiongradeover = $this->real_grade($submission->gradeover);
         $grades[$submission->authorid]->submissiongradeoverby = $submission->gradeoverby;
         $grades[$submission->authorid]->submissionpublished = $submission->published;
     }
     unset($submissions);
     unset($submission);
     foreach ($reviewers as $reviewer) {
         $info = new stdclass();
         $info->userid = $reviewer->reviewerid;
         $info->assessmentid = $reviewer->assessmentid;
         $info->submissionid = $reviewer->submissionid;
         $info->grade = $this->real_grade($reviewer->grade);
         $info->gradinggrade = $this->real_grading_grade($reviewer->gradinggrade);
         $info->gradinggradeover = $this->real_grading_grade($reviewer->gradinggradeover);
         $info->weight = $reviewer->weight;
         $grades[$reviewer->authorid]->reviewedby[$reviewer->reviewerid] = $info;
     }
     unset($reviewers);
     unset($reviewer);
     foreach ($reviewees as $reviewee) {
         $info = new stdclass();
         $info->userid = $reviewee->authorid;
         $info->assessmentid = $reviewee->assessmentid;
         $info->submissionid = $reviewee->submissionid;
         $info->grade = $this->real_grade($reviewee->grade);
         $info->gradinggrade = $this->real_grading_grade($reviewee->gradinggrade);
         $info->gradinggradeover = $this->real_grading_grade($reviewee->gradinggradeover);
         $info->weight = $reviewee->weight;
         $grades[$reviewee->reviewerid]->reviewerof[$reviewee->authorid] = $info;
     }
     unset($reviewees);
     unset($reviewee);
     foreach ($grades as $grade) {
         $grade->gradinggrade = $this->real_grading_grade($grade->gradinggrade);
     }
     $data = new stdclass();
     $data->grades = $grades;
     $data->userinfo = $userinfo;
     $data->totalcount = $numofparticipants;
     $data->maxgrade = $this->real_grade(100);
     $data->maxgradinggrade = $this->real_grading_grade(100);
     return $data;
 }
Esempio n. 29
0
/**
 * Given a course and a time, this module should find recent activity
 * that has occurred in wiki activities and print it out.
 * Return true if there was output, or false is there was none.
 *
 * @global $CFG
 * @global $DB
 * @uses CONTEXT_MODULE
 * @uses VISIBLEGROUPS
 * @param object $course
 * @param bool $viewfullnames capability
 * @param int $timestart
 * @return boolean
 **/
function wiki_print_recent_activity($course, $viewfullnames, $timestart)
{
    global $CFG, $DB, $OUTPUT;
    $usernamefields = get_all_user_name_fields(true, 'u');
    $sql = "SELECT p.id, p.timemodified, p.subwikiid, sw.wikiid, w.wikimode, sw.userid, sw.groupid, {$usernamefields}\n            FROM {wiki_pages} p\n                JOIN {wiki_subwikis} sw ON sw.id = p.subwikiid\n                JOIN {wiki} w ON w.id = sw.wikiid\n                JOIN {user} u ON u.id = sw.userid\n            WHERE p.timemodified > ? AND w.course = ?\n            ORDER BY p.timemodified ASC";
    if (!($pages = $DB->get_records_sql($sql, array($timestart, $course->id)))) {
        return false;
    }
    require_once $CFG->dirroot . "/mod/wiki/locallib.php";
    $wikis = array();
    $modinfo = get_fast_modinfo($course);
    $subwikivisible = array();
    foreach ($pages as $page) {
        if (!isset($subwikivisible[$page->subwikiid])) {
            $subwiki = (object) array('id' => $page->subwikiid, 'wikiid' => $page->wikiid, 'groupid' => $page->groupid, 'userid' => $page->userid);
            $wiki = (object) array('id' => $page->wikiid, 'course' => $course->id, 'wikimode' => $page->wikimode);
            $subwikivisible[$page->subwikiid] = wiki_user_can_view($subwiki, $wiki);
        }
        if ($subwikivisible[$page->subwikiid]) {
            $wikis[] = $page;
        }
    }
    unset($subwikivisible);
    unset($pages);
    if (!$wikis) {
        return false;
    }
    echo $OUTPUT->heading(get_string("updatedwikipages", 'wiki') . ':', 3);
    foreach ($wikis as $wiki) {
        $cm = $modinfo->instances['wiki'][$wiki->wikiid];
        $link = $CFG->wwwroot . '/mod/wiki/view.php?pageid=' . $wiki->id;
        print_recent_activity_note($wiki->timemodified, $wiki, $cm->name, $link, false, $viewfullnames);
    }
    return true;
    //  True if anything was printed, otherwise false
}
 /**
  * Given list of DB records from table course populates each record with list of users with course contact roles
  *
  * This function fills the courses with raw information as {@link get_role_users()} would do.
  * See also {@link course_in_list::get_course_contacts()} for more readable return
  *
  * $courses[$i]->managers = array(
  *   $roleassignmentid => $roleuser,
  *   ...
  * );
  *
  * where $roleuser is an stdClass with the following properties:
  *
  * $roleuser->raid - role assignment id
  * $roleuser->id - user id
  * $roleuser->username
  * $roleuser->firstname
  * $roleuser->lastname
  * $roleuser->rolecoursealias
  * $roleuser->rolename
  * $roleuser->sortorder - role sortorder
  * $roleuser->roleid
  * $roleuser->roleshortname
  *
  * @todo MDL-38596 minimize number of queries to preload contacts for the list of courses
  *
  * @param array $courses
  */
 public static function preload_course_contacts(&$courses)
 {
     global $CFG, $DB;
     if (empty($courses) || empty($CFG->coursecontact)) {
         return;
     }
     $managerroles = explode(',', $CFG->coursecontact);
     $cache = cache::make('core', 'coursecontacts');
     $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
     // Check if cache was set for the current course contacts and it is not yet expired.
     if (empty($cacheddata['basic']) || $cacheddata['basic']['roles'] !== $CFG->coursecontact || $cacheddata['basic']['lastreset'] < time() - self::CACHE_COURSE_CONTACTS_TTL) {
         // Reset cache.
         $cache->purge();
         $cache->set('basic', array('roles' => $CFG->coursecontact, 'lastreset' => time()));
         $cacheddata = $cache->get_many(array_merge(array('basic'), array_keys($courses)));
     }
     $courseids = array();
     foreach (array_keys($courses) as $id) {
         if ($cacheddata[$id] !== false) {
             $courses[$id]->managers = $cacheddata[$id];
         } else {
             $courseids[] = $id;
         }
     }
     // Array $courseids now stores list of ids of courses for which we still need to retrieve contacts.
     if (empty($courseids)) {
         return;
     }
     // First build the array of all context ids of the courses and their categories.
     $allcontexts = array();
     foreach ($courseids as $id) {
         $context = context_course::instance($id);
         $courses[$id]->managers = array();
         foreach (preg_split('|/|', $context->path, 0, PREG_SPLIT_NO_EMPTY) as $ctxid) {
             if (!isset($allcontexts[$ctxid])) {
                 $allcontexts[$ctxid] = array();
             }
             $allcontexts[$ctxid][] = $id;
         }
     }
     // Fetch list of all users with course contact roles in any of the courses contexts or parent contexts.
     list($sql1, $params1) = $DB->get_in_or_equal(array_keys($allcontexts), SQL_PARAMS_NAMED, 'ctxid');
     list($sql2, $params2) = $DB->get_in_or_equal($managerroles, SQL_PARAMS_NAMED, 'rid');
     list($sort, $sortparams) = users_order_by_sql('u');
     $notdeleted = array('notdeleted' => 0);
     $allnames = get_all_user_name_fields(true, 'u');
     $sql = "SELECT ra.contextid, ra.id AS raid,\n                       r.id AS roleid, r.name AS rolename, r.shortname AS roleshortname,\n                       rn.name AS rolecoursealias, u.id, u.username, {$allnames}\n                  FROM {role_assignments} ra\n                  JOIN {user} u ON ra.userid = u.id\n                  JOIN {role} r ON ra.roleid = r.id\n             LEFT JOIN {role_names} rn ON (rn.contextid = ra.contextid AND rn.roleid = r.id)\n                WHERE  ra.contextid " . $sql1 . " AND ra.roleid " . $sql2 . " AND u.deleted = :notdeleted\n             ORDER BY r.sortorder, {$sort}";
     $rs = $DB->get_recordset_sql($sql, $params1 + $params2 + $notdeleted + $sortparams);
     $checkenrolments = array();
     foreach ($rs as $ra) {
         foreach ($allcontexts[$ra->contextid] as $id) {
             $courses[$id]->managers[$ra->raid] = $ra;
             if (!isset($checkenrolments[$id])) {
                 $checkenrolments[$id] = array();
             }
             $checkenrolments[$id][] = $ra->id;
         }
     }
     $rs->close();
     // Remove from course contacts users who are not enrolled in the course.
     $enrolleduserids = self::ensure_users_enrolled($checkenrolments);
     foreach ($checkenrolments as $id => $userids) {
         if (empty($enrolleduserids[$id])) {
             $courses[$id]->managers = array();
         } else {
             if ($notenrolled = array_diff($userids, $enrolleduserids[$id])) {
                 foreach ($courses[$id]->managers as $raid => $ra) {
                     if (in_array($ra->id, $notenrolled)) {
                         unset($courses[$id]->managers[$raid]);
                     }
                 }
             }
         }
     }
     // Set the cache.
     $values = array();
     foreach ($courseids as $id) {
         $values[$id] = $courses[$id]->managers;
     }
     $cache->set_many($values);
 }