protected function get_other_values(renderer_base $output)
 {
     global $PAGE, $CFG;
     // Add user picture.
     $userpicture = new \user_picture($this->data);
     $userpicture->size = 1;
     // Size f1.
     $profileimageurl = $userpicture->get_url($PAGE)->out(false);
     $userpicture->size = 0;
     // Size f2.
     $profileimageurlsmall = $userpicture->get_url($PAGE)->out(false);
     $profileurl = (new moodle_url('/user/profile.php', array('id' => $this->data->id)))->out(false);
     $identityfields = array_flip(explode(',', $CFG->showuseridentity));
     $data = $this->data;
     foreach ($identityfields as $field => $index) {
         if (!empty($data->{$field})) {
             $identityfields[$field] = $data->{$field};
         } else {
             unset($identityfields[$field]);
         }
     }
     $identity = implode(', ', $identityfields);
     return array('fullname' => fullname($this->data), 'profileimageurl' => $profileimageurl, 'profileimageurlsmall' => $profileimageurlsmall, 'profileurl' => $profileurl, 'identity' => $identity);
 }
Exemplo n.º 2
0
/**
 * Get the students points based on a time interval
 *
 * @param int
 * @param int
 * @param int
 * @return mixed
 */
function block_ranking_get_students_by_date($limit = null, $datestart, $dateend)
{
    global $COURSE, $DB, $PAGE;
    // Get block ranking configuration.
    $cfgranking = get_config('block_ranking');
    // Get limit from default configuration or instance configuration.
    if (!$limit) {
        if (isset($cfgranking->rankingsize) && trim($cfgranking->rankingsize) != '') {
            $limit = $cfgranking->rankingsize;
        } else {
            $limit = 10;
        }
    }
    $context = $PAGE->context;
    $userfields = user_picture::fields('u', array('username'));
    $sql = "SELECT\n                DISTINCT {$userfields},\n                sum(rl.points) as points\n            FROM\n                {user} u\n            INNER JOIN {role_assignments} a ON a.userid = u.id\n            INNER JOIN {ranking_points} r ON r.userid = u.id AND r.courseid = :r_courseid\n            INNER JOIN {ranking_logs} rl ON rl.rankingid = r.id\n            INNER JOIN {context} c ON c.id = a.contextid\n            WHERE a.contextid = :contextid\n            AND a.userid = u.id\n            AND a.roleid = :roleid\n            AND c.instanceid = :courseid\n            AND r.courseid = :crsid\n            AND rl.timecreated BETWEEN :weekstart AND :weekend\n            GROUP BY u.id\n            ORDER BY points DESC, u.firstname ASC\n            LIMIT " . $limit;
    $params['contextid'] = $context->id;
    $params['roleid'] = 5;
    $params['courseid'] = $COURSE->id;
    $params['r_courseid'] = $COURSE->id;
    $params['crsid'] = $COURSE->id;
    $params['weekstart'] = $datestart;
    $params['weekend'] = $dateend;
    $users = array_values($DB->get_records_sql($sql, $params));
    return $users;
}
Exemplo n.º 3
0
 /**
  * Test the update user profile image function.
  */
 public function test_update_user_profile_image()
 {
     global $DB, $CFG;
     // Set the profile image.
     \enrol_lti\helper::update_user_profile_image($this->user1->id, $this->getExternalTestFileUrl('/test.jpg'));
     // Get the new user record.
     $this->user1 = $DB->get_record('user', array('id' => $this->user1->id));
     // Set the page details.
     $page = new moodle_page();
     $page->set_url('/user/profile.php');
     $page->set_context(context_system::instance());
     $renderer = $page->get_renderer('core');
     $usercontext = context_user::instance($this->user1->id);
     // Get the user's profile picture and make sure it is correct.
     $userpicture = new user_picture($this->user1);
     $this->assertSame($CFG->wwwroot . '/pluginfile.php/' . $usercontext->id . '/user/icon/clean/f2?rev=' . $this->user1->picture, $userpicture->get_url($page, $renderer)->out(false));
 }
Exemplo n.º 4
0
function get_user_picture($userid)
{
    global $DB;
    $extrafields[] = 'lastaccess';
    $ufields = user_picture::fields('u', $extrafields);
    $sql = "SELECT DISTINCT {$ufields} FROM {user} u where u.id={$userid}";
    $user = $DB->get_record_sql($sql);
    return new user_picture($user);
}
/**
 * get list of attendants for slot form
 * @param int $cmid the course module
 * @param mixed $groupid id number of the group to select from, 0 or '' if all groups
 * @return array of moodle user records
 */
function scheduler_get_attendants($cmid, $groupid = '')
{
    $context = context_module::instance($cmid);
    if (!$groupid) {
        $groupkeys = '';
    } else {
        $groupkeys = array($groupid);
    }
    $attendants = get_users_by_capability($context, 'mod/scheduler:attend', user_picture::fields('u'), 'u.lastname, u.firstname', '', '', $groupkeys, '', false, false, false);
    return $attendants;
}
Exemplo n.º 6
0
 function get_content()
 {
     global $USER, $CFG, $DB, $OUTPUT;
     if (!$CFG->messaging) {
         $this->content = new stdClass();
         $this->content->text = '';
         $this->content->footer = '';
         if ($this->page->user_is_editing()) {
             $this->content->text = get_string('disabled', 'message');
         }
         return $this->content;
     }
     if ($this->content !== NULL) {
         return $this->content;
     }
     $this->content = new stdClass();
     $this->content->text = '';
     $this->content->footer = '';
     if (empty($this->instance) or !isloggedin() or isguestuser() or empty($CFG->messaging)) {
         return $this->content;
     }
     $link = '/message/index.php';
     $action = null;
     //this was using popup_action() but popping up a fullsize window seems wrong
     $this->content->footer = $OUTPUT->action_link($link, get_string('messages', 'message'), $action);
     $ufields = user_picture::fields('u', array('lastaccess'));
     $users = $DB->get_records_sql("SELECT {$ufields}, COUNT(m.useridfrom) AS count\n                                         FROM {user} u, {message} m\n                                        WHERE m.useridto = ? AND u.id = m.useridfrom AND m.notification = 0\n                                     GROUP BY {$ufields}", array($USER->id));
     //Now, we have in users, the list of users to show
     //Because they are online
     if (!empty($users)) {
         $this->content->text .= '<ul class="list">';
         foreach ($users as $user) {
             $timeago = format_time(time() - $user->lastaccess);
             $this->content->text .= '<li class="listentry"><div class="user"><a href="' . $CFG->wwwroot . '/user/view.php?id=' . $user->id . '&amp;course=' . SITEID . '" title="' . $timeago . '">';
             $this->content->text .= $OUTPUT->user_picture($user, array('courseid' => SITEID));
             //TODO: user might not have capability to view frontpage profile :-(
             $this->content->text .= fullname($user) . '</a></div>';
             $link = '/message/index.php?usergroup=unread&id=' . $user->id;
             $anchortagcontents = '<img class="iconsmall" src="' . $OUTPUT->pix_url('t/message') . '" alt="" />&nbsp;' . $user->count;
             $action = null;
             // popup is gone now
             $anchortag = $OUTPUT->action_link($link, $anchortagcontents, $action);
             $this->content->text .= '<div class="message">' . $anchortag . '</div></li>';
         }
         $this->content->text .= '</ul>';
     } else {
         $this->content->text .= '<div class="info">';
         $this->content->text .= get_string('nomessages', 'message');
         $this->content->text .= '</div>';
     }
     return $this->content;
 }
Exemplo n.º 7
0
 public function definition()
 {
     global $USER, $OUTPUT, $CFG;
     $mform = $this->_form;
     $instance = $this->_customdata;
     $this->instance = $instance;
     $plugin = enrol_get_plugin('boleto');
     $heading = $plugin->get_instance_name($instance);
     $mform->addElement('header', 'boletoheader', $heading);
     if ($instance->password) {
         // Change the id of boleto enrolment key input as there can be multiple boleto enrolment methods.
         $mform->addElement('passwordunmask', 'enrolpassword', get_string('password', 'enrol_boleto'), array('id' => 'enrolpassword_' . $instance->id));
         $context = context_course::instance($this->instance->courseid);
         $keyholders = get_users_by_capability($context, 'enrol/boleto:holdkey', user_picture::fields('u'));
         $keyholdercount = 0;
         foreach ($keyholders as $keyholder) {
             $keyholdercount++;
             if ($keyholdercount === 1) {
                 $mform->addElement('static', 'keyholder', '', get_string('keyholder', 'enrol_boleto'));
             }
             $keyholdercontext = context_user::instance($keyholder->id);
             if ($USER->id == $keyholder->id || has_capability('moodle/user:viewdetails', context_system::instance()) || has_coursecontact_role($keyholder->id)) {
                 $profilelink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $keyholder->id . '&amp;course=' . $this->instance->courseid . '">' . fullname($keyholder) . '</a>';
             } else {
                 $profilelink = fullname($keyholder);
             }
             $profilepic = $OUTPUT->user_picture($keyholder, array('size' => 35, 'courseid' => $this->instance->courseid));
             $mform->addElement('static', 'keyholder' . $keyholdercount, '', $profilepic . $profilelink);
         }
     }
     $boletourl = new moodle_url('/enrol/boleto/boleto.php', array('instanceid' => $this->instance->id));
     $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfo', 'enrol_boleto'));
     // customint8 == avista.
     if ($this->instance->customint8) {
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfodirectlinks', 'enrol_boleto', $boletourl->out(false)));
     } else {
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfoparceladolink0', 'enrol_boleto', $boletourl->out(false)));
         $boletourl->param('parcela', 1);
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfoparceladolink1', 'enrol_boleto', $boletourl->out(false)));
         $boletourl->param('parcela', 2);
         $mform->addElement('static', 'info', '', get_string('boletoprintandpayinfoparceladolink2', 'enrol_boleto', $boletourl->out(false)));
     }
     $this->add_action_buttons(false, get_string('enrolme', 'enrol_boleto'));
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->setDefault('id', $instance->courseid);
     $mform->addElement('hidden', 'instance');
     $mform->setType('instance', PARAM_INT);
     $mform->setDefault('instance', $instance->id);
 }
Exemplo n.º 8
0
 /**
  * @param stdClass $data row data
  * @return string HTML for the fullname column
  */
 public function col_fullname($data)
 {
     if (is_null($data->realuserid)) {
         // User is in the git history but does not have an account in this Moodle site.
         $user = new stdClass();
         $user->firstname = $data->firstname;
         $user->lastname = $data->lastname;
         // Additional fields so fullname() doesn't display a developer debug message.
         $user->firstnamephonetic = null;
         $user->lastnamephonetic = null;
         $user->middlename = null;
         $user->alternatename = null;
     } else {
         $user = user_picture::unalias($data, null, "realuserid", "realuser");
     }
     return fullname($user);
 }
function getUserList($currentgroup = '', $courseId, $contextlevel, $context, $limitUsers = 15)
{
    global $USER, $CFG, $DB, $OUTPUT;
    $groupmembers = "";
    $groupselect = "";
    $params = array();
    //Add this to the SQL to show only group users
    if ($currentgroup !== NULL) {
        $groupmembers = ", {groups_members} gm";
        $groupselect = "AND u.id = gm.userid AND gm.groupid = :currentgroup";
        $params['currentgroup'] = $currentgroup;
    }
    $userfields = user_picture::fields('u', array('username'));
    if ($courseId == SITEID or $contextlevel < CONTEXT_COURSE) {
        // Site-level
        //Only show if is admin
        if (!checkIfUserIsAdmin()) {
            return '';
        }
        $sql = "SELECT {$userfields}, ul.lastip, MAX(ul.timemodified) AS lastaccess\n                      FROM {user} u {$groupmembers} ,{sessions} ul\n                     WHERE u.id = ul.userid AND u.deleted = 0\n                     {$groupselect}\n                  GROUP BY {$userfields}\n                  ORDER BY ul.timemodified DESC ";
    } else {
        // Course level - show only enrolled users for now
        //Only show if is teacher or admin
        if (!checkIfUserIsTeacher($courseId)) {
            return '';
        }
        list($esqljoin, $eparams) = get_enrolled_sql($context);
        $params = array_merge($params, $eparams);
        $sql = "SELECT {$userfields}, ul.lastip, MAX(ul.timemodified) AS lastaccess\n                      FROM {sessions} ul {$groupmembers}, {user} u\n                      JOIN ({$esqljoin}) euj ON euj.id = u.id\n                     WHERE u.id = ul.userid\n                           AND u.deleted = 0\n                           {$groupselect}\n                  GROUP BY {$userfields}\n                  ORDER BY lastaccess DESC";
        $params['courseid'] = $courseId;
    }
    if ($users = $DB->get_records_sql($sql, $params, 0, $limitUsers)) {
        // We'll just take the most recent 50 maximum
        foreach ($users as $user) {
            $users[$user->id]->fullname = fullname($user);
        }
    } else {
        $users = array();
    }
    return $users;
}
Exemplo n.º 10
0
 /**
  * Constructor.
  *
  * @param string $uniqueid Unique ID.
  */
 public function __construct($uniqueid, $courseid)
 {
     global $PAGE;
     parent::__construct($uniqueid);
     // Block XP stuff.
     $this->xpmanager = block_xp_manager::get($courseid);
     $this->xpoutput = $PAGE->get_renderer('block_xp');
     // Define columns.
     $this->define_columns(array('rank', 'userpic', 'fullname', 'lvl', 'xp', 'progress'));
     $this->define_headers(array(get_string('rank', 'block_xp'), '', get_string('fullname'), get_string('level', 'block_xp'), get_string('xp', 'block_xp'), get_string('progress', 'block_xp')));
     // Define SQL.
     $this->sql = new stdClass();
     $this->sql->fields = 'x.*, ' . user_picture::fields('u');
     $this->sql->from = '{block_xp} 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(false);
     $this->no_sorting('userpic');
     $this->no_sorting('progress');
     $this->collapsible(false);
 }
Exemplo n.º 11
0
    protected function get_authors() {
        global $DB;
        $rslt = $this->workshop->get_submissions_grouped();
        //now we have to do some magic to turn these back into "authors"
        $ret = array();
        $users = array();
        
        //loop 1: get user ids
        foreach ($rslt as $r) {
            $users[] = $r->authorid;
        }
        $fields = user_picture::fields();
        $users = $DB->get_records_list('user','id',$users,'',$fields);
        //loop 2: apply users to submissions 
        $ret[0] = array();
        foreach ($rslt as $r){
            $ret[$r->group->id] = array( $r->authorid => $users[$r->authorid] );
            $ret[0][$r->authorid] = $users[$r->authorid];
        }

        return $ret;
    }
Exemplo n.º 12
0
 /**
  * Store the SQL queries & params for listing online users
  *
  * @param int $currentgroup The group (if any) to filter on
  * @param int $now Time now
  * @param int $timetoshowusers Number of seconds to show online users
  * @param context $context Context object used to generate the sql for users enrolled in a specific course
  * @param bool $sitelevel Whether to check online users at site level.
  * @param int $courseid The course id to check
  */
 protected function set_sql($currentgroup, $now, $timetoshowusers, $context, $sitelevel, $courseid)
 {
     $timefrom = 100 * floor(($now - $timetoshowusers) / 100);
     // Round to nearest 100 seconds for better query cache.
     $groupmembers = "";
     $groupselect = "";
     $groupby = "";
     $lastaccess = ", lastaccess";
     $timeaccess = ", ul.timeaccess AS lastaccess";
     $params = array();
     $userfields = \user_picture::fields('u', array('username'));
     // Add this to the SQL to show only group users.
     if ($currentgroup !== null) {
         $groupmembers = ", {groups_members} gm";
         $groupselect = "AND u.id = gm.userid AND gm.groupid = :currentgroup";
         $groupby = "GROUP BY {$userfields}";
         $lastaccess = ", MAX(u.lastaccess) AS lastaccess";
         $timeaccess = ", MAX(ul.timeaccess) AS lastaccess";
         $params['currentgroup'] = $currentgroup;
     }
     $params['now'] = $now;
     $params['timefrom'] = $timefrom;
     if ($sitelevel) {
         $sql = "SELECT {$userfields} {$lastaccess}\n                      FROM {user} u {$groupmembers}\n                     WHERE u.lastaccess > :timefrom\n                           AND u.lastaccess <= :now\n                           AND u.deleted = 0\n                           {$groupselect} {$groupby}\n                  ORDER BY lastaccess DESC ";
         $csql = "SELECT COUNT(u.id)\n                      FROM {user} u {$groupmembers}\n                     WHERE u.lastaccess > :timefrom\n                           AND u.lastaccess <= :now\n                           AND u.deleted = 0\n                           {$groupselect}";
     } else {
         // Course level - show only enrolled users for now.
         // TODO: add a new capability for viewing of all users (guests+enrolled+viewing).
         list($esqljoin, $eparams) = get_enrolled_sql($context);
         $params = array_merge($params, $eparams);
         $sql = "SELECT {$userfields} {$timeaccess}\n                      FROM {user_lastaccess} ul {$groupmembers}, {user} u\n                      JOIN ({$esqljoin}) euj ON euj.id = u.id\n                     WHERE ul.timeaccess > :timefrom\n                           AND u.id = ul.userid\n                           AND ul.courseid = :courseid\n                           AND ul.timeaccess <= :now\n                           AND u.deleted = 0\n                           {$groupselect} {$groupby}\n                  ORDER BY lastaccess DESC";
         $csql = "SELECT COUNT(u.id)\n                      FROM {user_lastaccess} ul {$groupmembers}, {user} u\n                      JOIN ({$esqljoin}) euj ON euj.id = u.id\n                     WHERE ul.timeaccess > :timefrom\n                           AND u.id = ul.userid\n                           AND ul.courseid = :courseid\n                           AND ul.timeaccess <= :now\n                           AND u.deleted = 0\n                           {$groupselect}";
         $params['courseid'] = $courseid;
     }
     $this->sql = $sql;
     $this->csql = $csql;
     $this->params = $params;
 }
Exemplo n.º 13
0
 /**
  * Constructor.
  *
  * @param string $uniqueid Unique ID.
  */
 public function __construct($uniqueid, $courseid)
 {
     global $DB, $PAGE;
     parent::__construct($uniqueid);
     // Block XP stuff.
     $this->xpmanager = block_xp_manager::get($courseid);
     $this->xpoutput = $PAGE->get_renderer('block_xp');
     $context = context_course::instance($courseid);
     // Define columns.
     $this->define_columns(array('userpic', 'fullname', 'lvl', 'xp', 'progress', 'actions'));
     $this->define_headers(array('', get_string('fullname'), get_string('level', 'block_xp'), get_string('xp', 'block_xp'), get_string('progress', 'block_xp'), ''));
     // Get the relevant user IDs, users enrolled or users with XP.
     // This might be a performance issue at some point.
     $ids = array();
     $users = get_enrolled_users($context, 'block/xp:earnxp');
     foreach ($users as $user) {
         $ids[$user->id] = $user->id;
     }
     unset($users);
     $entries = $DB->get_recordset_sql('SELECT userid FROM {block_xp} WHERE courseid = :courseid', array('courseid' => $courseid));
     foreach ($entries as $entry) {
         $ids[$entry->userid] = $entry->userid;
     }
     $entries->close();
     list($insql, $inparams) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED, 'param', true, null);
     // Define SQL.
     $this->sql = new stdClass();
     $this->sql->fields = user_picture::fields('u') . ', x.lvl, x.xp';
     $this->sql->from = "{user} u LEFT JOIN {block_xp} x ON (x.userid = u.id AND x.courseid = :courseid)";
     $this->sql->where = "u.id {$insql}";
     $this->sql->params = array_merge($inparams, array('courseid' => $courseid));
     // Define various table settings.
     $this->sortable(true, 'lvl', SORT_DESC);
     $this->no_sorting('userpic');
     $this->no_sorting('progress');
     $this->collapsible(false);
 }
 /**
  * Formats the column userpic.
  *
  * @param stdClass $row Table row.
  * @return string Output produced.
  */
 protected function col_userpic($row)
 {
     global $CFG, $OUTPUT;
     if ($this->identitymode == block_xp_manager::IDENTITY_OFF && $this->userid != $row->userid) {
         static $guestuser = null;
         if ($guestuser === null) {
             $guestuser = guest_user();
         }
         return $OUTPUT->user_picture($guestuser, array('link' => false, 'alttext' => false));
     }
     return $OUTPUT->user_picture(user_picture::unalias($row, null, 'userid'));
 }
Exemplo n.º 15
0
 /**
  * Test function username_load_fields_from_object().
  */
 public function test_username_load_fields_from_object()
 {
     $this->resetAfterTest();
     // This object represents the information returned from an sql query.
     $userinfo = new stdClass();
     $userinfo->userid = 1;
     $userinfo->username = '******';
     $userinfo->firstname = 'Bruce';
     $userinfo->lastname = 'Campbell';
     $userinfo->firstnamephonetic = 'ブルース';
     $userinfo->lastnamephonetic = 'カンベッル';
     $userinfo->middlename = '';
     $userinfo->alternatename = '';
     $userinfo->email = '';
     $userinfo->picture = 23;
     $userinfo->imagealt = 'Michael Jordan draining another basket.';
     $userinfo->idnumber = 3982;
     // Just user name fields.
     $user = new stdClass();
     $user = username_load_fields_from_object($user, $userinfo);
     $expectedarray = new stdClass();
     $expectedarray->firstname = 'Bruce';
     $expectedarray->lastname = 'Campbell';
     $expectedarray->firstnamephonetic = 'ブルース';
     $expectedarray->lastnamephonetic = 'カンベッル';
     $expectedarray->middlename = '';
     $expectedarray->alternatename = '';
     $this->assertEquals($user, $expectedarray);
     // User information for showing a picture.
     $user = new stdClass();
     $additionalfields = explode(',', user_picture::fields());
     $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
     $user->id = $userinfo->userid;
     $expectedarray = new stdClass();
     $expectedarray->id = 1;
     $expectedarray->firstname = 'Bruce';
     $expectedarray->lastname = 'Campbell';
     $expectedarray->firstnamephonetic = 'ブルース';
     $expectedarray->lastnamephonetic = 'カンベッル';
     $expectedarray->middlename = '';
     $expectedarray->alternatename = '';
     $expectedarray->email = '';
     $expectedarray->picture = 23;
     $expectedarray->imagealt = 'Michael Jordan draining another basket.';
     $this->assertEquals($user, $expectedarray);
     // Alter the userinfo object to have a prefix.
     $userinfo->authorfirstname = 'Bruce';
     $userinfo->authorlastname = 'Campbell';
     $userinfo->authorfirstnamephonetic = 'ブルース';
     $userinfo->authorlastnamephonetic = 'カンベッル';
     $userinfo->authormiddlename = '';
     $userinfo->authorpicture = 23;
     $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
     $userinfo->authoremail = '*****@*****.**';
     // Return an object with user picture information.
     $user = new stdClass();
     $additionalfields = explode(',', user_picture::fields());
     $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
     $user->id = $userinfo->userid;
     $expectedarray = new stdClass();
     $expectedarray->id = 1;
     $expectedarray->firstname = 'Bruce';
     $expectedarray->lastname = 'Campbell';
     $expectedarray->firstnamephonetic = 'ブルース';
     $expectedarray->lastnamephonetic = 'カンベッル';
     $expectedarray->middlename = '';
     $expectedarray->alternatename = '';
     $expectedarray->email = '*****@*****.**';
     $expectedarray->picture = 23;
     $expectedarray->imagealt = 'Michael Jordan draining another basket.';
     $this->assertEquals($user, $expectedarray);
 }
Exemplo n.º 16
0
    /**
     *  Display all the submissions ready for grading
     *
     * @global object
     * @global object
     * @global object
     * @global object
     * @param string $message
     * @return bool|void
     */
    function display_submissions($message='') {
        global $CFG, $DB, $USER, $DB, $OUTPUT, $PAGE;
        require_once($CFG->libdir.'/gradelib.php');

        /* first we check to see if the form has just been submitted
         * to request user_preference updates
         */

       $filters = array(self::FILTER_ALL             => get_string('all'),
                        self::FILTER_SUBMITTED       => get_string('submitted', 'assignment'),
                        self::FILTER_REQUIRE_GRADING => get_string('requiregrading', 'assignment'));

        $updatepref = optional_param('updatepref', 0, PARAM_INT);

        if (isset($_POST['updatepref'])){
            $perpage = optional_param('perpage', 10, PARAM_INT);
            $perpage = ($perpage <= 0) ? 10 : $perpage ;
            $filter = optional_param('filter', 0, PARAM_INT);
            set_user_preference('assignment_perpage', $perpage);
            set_user_preference('assignment_quickgrade', optional_param('quickgrade', 0, PARAM_BOOL));
            set_user_preference('assignment_filter', $filter);
        }

        /* next we get perpage and quickgrade (allow quick grade) params
         * from database
         */
        $perpage    = get_user_preferences('assignment_perpage', 10);
        $quickgrade = get_user_preferences('assignment_quickgrade', 0);
        $filter = get_user_preferences('assignment_filter', 0);
        $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);

        if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
            $uses_outcomes = true;
        } else {
            $uses_outcomes = false;
        }

        $page    = optional_param('page', 0, PARAM_INT);
        $strsaveallfeedback = get_string('saveallfeedback', 'assignment');

    /// Some shortcuts to make the code read better

        $course     = $this->course;
        $assignment = $this->assignment;
        $cm         = $this->cm;

        $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
        add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->cm->id, $this->assignment->id, $this->cm->id);

        $PAGE->set_title(format_string($this->assignment->name,true));
        $PAGE->set_heading($this->course->fullname);
        echo $OUTPUT->header();

        echo '<div class="usersubmissions">';

        //hook to allow plagiarism plugins to update status/print links.
        plagiarism_update_status($this->course, $this->cm);

        /// Print quickgrade form around the table
        if ($quickgrade) {
            $formattrs = array();
            $formattrs['action'] = new moodle_url('/mod/assignment/submissions.php');
            $formattrs['id'] = 'fastg';
            $formattrs['method'] = 'post';

            echo html_writer::start_tag('form', $formattrs);
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'id',      'value'=> $this->cm->id));
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'mode',    'value'=> 'fastgrade'));
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'page',    'value'=> $page));
            echo html_writer::empty_tag('input', array('type'=>'hidden', 'name'=>'sesskey', 'value'=> sesskey()));
        }

        $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
        if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
            echo '<div class="allcoursegrades"><a href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
                . get_string('seeallcoursegrades', 'grades') . '</a></div>';
        }

        if (!empty($message)) {
            echo $message;   // display messages here if any
        }

        $context = get_context_instance(CONTEXT_MODULE, $cm->id);

    /// Check to see if groups are being used in this assignment

        /// find out current groups mode
        $groupmode = groups_get_activity_groupmode($cm);
        $currentgroup = groups_get_activity_group($cm, true);
        groups_print_activity_menu($cm, $CFG->wwwroot . '/mod/assignment/submissions.php?id=' . $this->cm->id);

        /// Get all ppl that are allowed to submit assignments
        list($esql, $params) = get_enrolled_sql($context, 'mod/assignment:view', $currentgroup);

        if ($filter == self::FILTER_ALL) {
            $sql = "SELECT u.id FROM {user} u ".
                   "LEFT JOIN ($esql) eu ON eu.id=u.id ".
                   "WHERE u.deleted = 0 AND eu.id=u.id ";
        } else {
            $wherefilter = '';
            if($filter == self::FILTER_SUBMITTED) {
               $wherefilter = ' AND s.timemodified > 0';
            } else if($filter == self::FILTER_REQUIRE_GRADING) {
                $wherefilter = ' AND s.timemarked < s.timemodified ';
            }

            $sql = "SELECT u.id FROM {user} u ".
                   "LEFT JOIN ($esql) eu ON eu.id=u.id ".
                   "LEFT JOIN {assignment_submissions} s ON (u.id = s.userid) " .
                   "WHERE u.deleted = 0 AND eu.id=u.id ".
                   'AND s.assignment = '. $this->assignment->id .
                    $wherefilter;
        }

        $users = $DB->get_records_sql($sql, $params);
        if (!empty($users)) {
            $users = array_keys($users);
        }

        // if groupmembersonly used, remove users who are not in any group
        if ($users and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
            if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
                $users = array_intersect($users, array_keys($groupingusers));
            }
        }

        $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
        if ($uses_outcomes) {
            $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
        }

        $tableheaders = array('',
                              get_string('fullname'),
                              get_string('grade'),
                              get_string('comment', 'assignment'),
                              get_string('lastmodified').' ('.get_string('submission', 'assignment').')',
                              get_string('lastmodified').' ('.get_string('grade').')',
                              get_string('status'),
                              get_string('finalgrade', 'grades'));
        if ($uses_outcomes) {
            $tableheaders[] = get_string('outcome', 'grades');
        }

        require_once($CFG->libdir.'/tablelib.php');
        $table = new flexible_table('mod-assignment-submissions');

        $table->define_columns($tablecolumns);
        $table->define_headers($tableheaders);
        $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);

        $table->sortable(true, 'lastname');//sorted by lastname by default
        $table->collapsible(true);
        $table->initialbars(true);

        $table->column_suppress('picture');
        $table->column_suppress('fullname');

        $table->column_class('picture', 'picture');
        $table->column_class('fullname', 'fullname');
        $table->column_class('grade', 'grade');
        $table->column_class('submissioncomment', 'comment');
        $table->column_class('timemodified', 'timemodified');
        $table->column_class('timemarked', 'timemarked');
        $table->column_class('status', 'status');
        $table->column_class('finalgrade', 'finalgrade');
        if ($uses_outcomes) {
            $table->column_class('outcome', 'outcome');
        }

        $table->set_attribute('cellspacing', '0');
        $table->set_attribute('id', 'attempts');
        $table->set_attribute('class', 'submissions');
        $table->set_attribute('width', '100%');
        //$table->set_attribute('align', 'center');

        $table->no_sorting('finalgrade');
        $table->no_sorting('outcome');

        // Start working -- this is necessary as soon as the niceties are over
        $table->setup();

        if (empty($users)) {
            echo $OUTPUT->heading(get_string('nosubmitusers','assignment'));
            echo '</div>';
            return true;
        }
        if ($this->assignment->assignmenttype=='upload' || $this->assignment->assignmenttype=='online' || $this->assignment->assignmenttype=='uploadsingle') { //TODO: this is an ugly hack, where is the plugin spirit? (skodak)
            echo '<div style="text-align:right"><a href="submissions.php?id='.$this->cm->id.'&amp;download=zip">'.get_string('downloadall', 'assignment').'</a></div>';
        }
    /// Construct the SQL

        list($where, $params) = $table->get_sql_where();
        if ($where) {
            $where .= ' AND ';
        }

        if ($filter == self::FILTER_SUBMITTED) {
           $where .= 's.timemodified > 0 AND ';
        } else if($filter == self::FILTER_REQUIRE_GRADING) {
           $where .= 's.timemarked < s.timemodified AND ';
        }

        if ($sort = $table->get_sql_sort()) {
            $sort = ' ORDER BY '.$sort;
        }

        $ufields = user_picture::fields('u');

        $select = "SELECT $ufields,
                          s.id AS submissionid, s.grade, s.submissioncomment,
                          s.timemodified, s.timemarked,
                          COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ";
        $sql = 'FROM {user} u '.
               'LEFT JOIN {assignment_submissions} s ON u.id = s.userid
                AND s.assignment = '.$this->assignment->id.' '.
               'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';

        $ausers = $DB->get_records_sql($select.$sql.$sort, $params, $table->get_page_start(), $table->get_page_size());

        $table->pagesize($perpage, count($users));

        ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
        $offset = $page * $perpage;
        $strupdate = get_string('update');
        $strgrade  = get_string('grade');
        $grademenu = make_grades_menu($this->assignment->grade);

        if ($ausers !== false) {
            $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
            $endposition = $offset + $perpage;
            $currentposition = 0;
            foreach ($ausers as $auser) {
                if ($currentposition == $offset && $offset < $endposition) {
                    $final_grade = $grading_info->items[0]->grades[$auser->id];
                    $grademax = $grading_info->items[0]->grademax;
                    $final_grade->formatted_grade = round($final_grade->grade,2) .' / ' . round($grademax,2);
                    $locked_overridden = 'locked';
                    if ($final_grade->overridden) {
                        $locked_overridden = 'overridden';
                    }

                /// Calculate user status
                    $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
                    $picture = $OUTPUT->user_picture($auser);

                    if (empty($auser->submissionid)) {
                        $auser->grade = -1; //no submission yet
                    }

                    if (!empty($auser->submissionid)) {
                    ///Prints student answer and student modified date
                    ///attach file or print link to student answer, depending on the type of the assignment.
                    ///Refer to print_student_answer in inherited classes.
                        if ($auser->timemodified > 0) {
                            $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
                                             . userdate($auser->timemodified).'</div>';
                        } else {
                            $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
                        }
                    ///Print grade, dropdown or text
                        if ($auser->timemarked > 0) {
                            $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';

                            if ($final_grade->locked or $final_grade->overridden) {
                                $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
                            } else if ($quickgrade) {
                                $attributes = array();
                                $attributes['tabindex'] = $tabindex++;
                                $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
                                $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
                            } else {
                                $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
                            }

                        } else {
                            $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
                            if ($final_grade->locked or $final_grade->overridden) {
                                $grade = '<div id="g'.$auser->id.'" class="'. $locked_overridden .'">'.$final_grade->formatted_grade.'</div>';
                            } else if ($quickgrade) {
                                $attributes = array();
                                $attributes['tabindex'] = $tabindex++;
                                $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
                                $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
                            } else {
                                $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
                            }
                        }
                    ///Print Comment
                        if ($final_grade->locked or $final_grade->overridden) {
                            $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';

                        } else if ($quickgrade) {
                            $comment = '<div id="com'.$auser->id.'">'
                                     . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
                                     . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
                        } else {
                            $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
                        }
                    } else {
                        $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
                        $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
                        $status          = '<div id="st'.$auser->id.'">&nbsp;</div>';

                        if ($final_grade->locked or $final_grade->overridden) {
                            $grade = '<div id="g'.$auser->id.'">'.$final_grade->formatted_grade . '</div>';
                        } else if ($quickgrade) {   // allow editing
                            $attributes = array();
                            $attributes['tabindex'] = $tabindex++;
                            $menu = html_writer::select(make_grades_menu($this->assignment->grade), 'menu['.$auser->id.']', $auser->grade, array(-1=>get_string('nograde')), $attributes);
                            $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
                        } else {
                            $grade = '<div id="g'.$auser->id.'">-</div>';
                        }

                        if ($final_grade->locked or $final_grade->overridden) {
                            $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
                        } else if ($quickgrade) {
                            $comment = '<div id="com'.$auser->id.'">'
                                     . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
                                     . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
                        } else {
                            $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
                        }
                    }

                    if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
                        $auser->status = 0;
                    } else {
                        $auser->status = 1;
                    }

                    $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;

                    ///No more buttons, we use popups ;-).
                    $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
                               . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;filter='.$filter.'&amp;offset='.$offset++;

                    $button = $OUTPUT->action_link($popup_url, $buttontext);

                    $status  = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';

                    $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';

                    $outcomes = '';

                    if ($uses_outcomes) {

                        foreach($grading_info->outcomes as $n=>$outcome) {
                            $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
                            $options = make_grades_menu(-$outcome->scaleid);

                            if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
                                $options[0] = get_string('nooutcome', 'grades');
                                $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
                            } else {
                                $attributes = array();
                                $attributes['tabindex'] = $tabindex++;
                                $attributes['id'] = 'outcome_'.$n.'_'.$auser->id;
                                $outcomes .= ' '.html_writer::select($options, 'outcome_'.$n.'['.$auser->id.']', $outcome->grades[$auser->id]->grade, array(0=>get_string('nooutcome', 'grades')), $attributes);
                            }
                            $outcomes .= '</div>';
                        }
                    }

                    $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser, has_capability('moodle/site:viewfullnames', $this->context)) . '</a>';
                    $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
                    if ($uses_outcomes) {
                        $row[] = $outcomes;
                    }

                    $table->add_data($row);
                }
                $currentposition++;
            }
        }

        $table->print_html();  /// Print the whole table

        /// Print quickgrade form around the table
        if ($quickgrade && $table->started_output){
            $mailinfopref = false;
            if (get_user_preferences('assignment_mailinfo', 1)) {
                $mailinfopref = true;
            }
            $emailnotification =  html_writer::checkbox('mailinfo', 1, $mailinfopref, get_string('enableemailnotification','assignment'));

            $emailnotification .= $OUTPUT->help_icon('enableemailnotification', 'assignment');
            echo html_writer::tag('div', $emailnotification, array('class'=>'emailnotification'));

            $savefeedback = html_writer::empty_tag('input', array('type'=>'submit', 'name'=>'fastg', 'value'=>get_string('saveallfeedback', 'assignment')));
            echo html_writer::tag('div', $savefeedback, array('class'=>'fastgbutton'));

            echo html_writer::end_tag('form');
        } else if ($quickgrade) {
            echo html_writer::end_tag('form');
        }

        echo '</div>';
        /// End of fast grading form

        /// Mini form for setting user preference

        $formaction = new moodle_url('/mod/assignment/submissions.php', array('id'=>$this->cm->id));
        $mform = new MoodleQuickForm('optionspref', 'post', $formaction, '', array('class'=>'optionspref'));

        $mform->addElement('hidden', 'updatepref');
        $mform->setDefault('updatepref', 1);
        $mform->addElement('header', 'qgprefs', get_string('optionalsettings', 'assignment'));
        $mform->addElement('select', 'filter', get_string('show'),  $filters);

        $mform->setDefault('filter', $filter);

        $mform->addElement('text', 'perpage', get_string('pagesize', 'assignment'), array('size'=>1));
        $mform->setDefault('perpage', $perpage);

        $mform->addElement('checkbox', 'quickgrade', get_string('quickgrade','assignment'));
        $mform->setDefault('quickgrade', $quickgrade);
        $mform->addHelpButton('quickgrade', 'quickgrade', 'assignment');

        $mform->addElement('submit', 'savepreferences', get_string('savepreferences'));

        $mform->display();

        echo $OUTPUT->footer();
    }
Exemplo n.º 17
0
 /**
  * MDL-27591 made this method obsolete.
  */
 public function get_users($groupid = 0, $page = 1)
 {
     global $DB, $CFG;
     // Fields we need from the user table.
     $userfields = user_picture::fields('u', array('username', 'idnumber', 'institution', 'department'));
     if (isset($this->pageparams->sort) and $this->pageparams->sort == ATT_SORT_FIRSTNAME) {
         $orderby = "u.firstname ASC, u.lastname ASC, u.idnumber ASC, u.institution ASC, u.department ASC";
     } else {
         $orderby = "u.lastname ASC, u.firstname ASC, u.idnumber ASC, u.institution ASC, u.department ASC";
     }
     if ($page) {
         $usersperpage = $this->pageparams->perpage;
         if (!empty($CFG->enablegroupmembersonly) and $this->cm->groupmembersonly) {
             $startusers = ($page - 1) * $usersperpage;
             if ($groupid == 0) {
                 $groups = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
             } else {
                 $groups = $groupid;
             }
             $users = get_users_by_capability($this->context, 'mod/attendance:canbelisted', $userfields . ',u.id, u.firstname, u.lastname, u.email', $orderby, $startusers, $usersperpage, $groups, '', false, true);
         } else {
             $startusers = ($page - 1) * $usersperpage;
             $users = get_enrolled_users($this->context, 'mod/attendance:canbelisted', $groupid, $userfields, $orderby, $startusers, $usersperpage);
         }
     } else {
         if (!empty($CFG->enablegroupmembersonly) and $this->cm->groupmembersonly) {
             if ($groupid == 0) {
                 $groups = array_keys(groups_get_all_groups($this->cm->course, 0, $this->cm->groupingid, 'g.id'));
             } else {
                 $groups = $groupid;
             }
             $users = get_users_by_capability($this->context, 'mod/attendance:canbelisted', $userfields . ',u.id, u.firstname, u.lastname, u.email', $orderby, '', '', $groups, '', false, true);
         } else {
             $users = get_enrolled_users($this->context, 'mod/attendance:canbelisted', $groupid, $userfields, $orderby);
         }
     }
     // Add a flag to each user indicating whether their enrolment is active.
     if (!empty($users)) {
         list($sql, $params) = $DB->get_in_or_equal(array_keys($users), SQL_PARAMS_NAMED, 'usid0');
         // See CONTRIB-4868.
         $mintime = 'MIN(CASE WHEN (ue.timestart > :zerotime) THEN ue.timestart ELSE ue.timecreated END)';
         $maxtime = 'CASE WHEN MIN(ue.timeend) = 0 THEN 0 ELSE MAX(ue.timeend) END';
         // See CONTRIB-3549.
         $sql = "SELECT ue.userid, MIN(ue.status) as status,\n                           {$mintime} AS mintime,\n                           {$maxtime} AS maxtime\n                      FROM {user_enrolments} ue\n                      JOIN {enrol} e ON e.id = ue.enrolid\n                     WHERE ue.userid {$sql}\n                           AND e.status = :estatus\n                           AND e.courseid = :courseid\n                  GROUP BY ue.userid";
         $params += array('zerotime' => 0, 'estatus' => ENROL_INSTANCE_ENABLED, 'courseid' => $this->course->id);
         $enrolments = $DB->get_records_sql($sql, $params);
         foreach ($users as $user) {
             $users[$user->id]->enrolmentstatus = $enrolments[$user->id]->status;
             $users[$user->id]->enrolmentstart = $enrolments[$user->id]->mintime;
             $users[$user->id]->enrolmentend = $enrolments[$user->id]->maxtime;
             $users[$user->id]->type = 'standard';
             // Mark as a standard (not a temporary) user.
         }
     }
     // Add the 'temporary' users to this list.
     $tempusers = $DB->get_records('attendance_tempusers', array('courseid' => $this->course->id));
     foreach ($tempusers as $tempuser) {
         $users[] = self::tempuser_to_user($tempuser);
     }
     return $users;
 }
Exemplo n.º 18
0
 /**
  * Retrieve a list of users blocked
  *
  * @param  int $userid the user whose blocked users we want to retrieve
  * @return external_description
  * @since 2.9
  */
 public static function get_blocked_users($userid)
 {
     global $CFG, $USER, $PAGE;
     // Warnings array, it can be empty at the end but is mandatory.
     $warnings = array();
     // Validate params.
     $params = array('userid' => $userid);
     $params = self::validate_parameters(self::get_blocked_users_parameters(), $params);
     $userid = $params['userid'];
     // Validate context.
     $context = context_system::instance();
     self::validate_context($context);
     // Check if private messaging between users is allowed.
     if (empty($CFG->messaging)) {
         throw new moodle_exception('disabled', 'message');
     }
     $user = core_user::get_user($userid, '*', MUST_EXIST);
     core_user::require_active_user($user);
     // Check if we have permissions for retrieve the information.
     if ($userid != $USER->id and !has_capability('moodle/site:readallmessages', $context)) {
         throw new moodle_exception('accessdenied', 'admin');
     }
     // Now, we can get safely all the blocked users.
     $users = message_get_blocked_users($user);
     $blockedusers = array();
     foreach ($users as $user) {
         $newuser = array('id' => $user->id, 'fullname' => fullname($user));
         $userpicture = new user_picture($user);
         $userpicture->size = 1;
         // Size f1.
         $newuser['profileimageurl'] = $userpicture->get_url($PAGE)->out(false);
         $blockedusers[] = $newuser;
     }
     $results = array('users' => $blockedusers, 'warnings' => $warnings);
     return $results;
 }
Exemplo n.º 19
0
/**
 * @global object
 * @param int $surveyid
 * @param int $groupid
 * @param string $sort
 * @return array
 */
function survey_get_user_answers($surveyid, $questionid, $groupid, $sort="sa.answer1,sa.answer2 ASC") {
    global $DB;

    $params = array('surveyid'=>$surveyid, 'questionid'=>$questionid);

    if ($groupid) {
        $groupfrom = ', {groups_members} gm';
        $groupsql  = 'AND gm.groupid = :groupid AND u.id = gm.userid';
        $params['groupid'] = $groupid;
    } else {
        $groupfrom = '';
        $groupsql  = '';
    }

    $userfields = user_picture::fields('u');
    return $DB->get_records_sql("SELECT sa.*, $userfields
                                   FROM {survey_answers} sa,  {user} u $groupfrom
                                  WHERE sa.survey = :surveyid
                                        AND sa.question = :questionid
                                        AND u.id = sa.userid $groupsql
                               ORDER BY $sort", $params);
}
Exemplo n.º 20
0
    $table->sortable(true, 'firstname', SORT_ASC);
}
$table->no_sorting('roles');
$table->no_sorting('groups');
$table->no_sorting('groupings');
$table->no_sorting('select');
$table->set_attribute('cellspacing', '0');
$table->set_attribute('id', 'participants');
$table->set_attribute('class', 'generaltable generalbox');
$table->set_control_variables(array(TABLE_VAR_SORT => 'ssort', TABLE_VAR_HIDE => 'shide', TABLE_VAR_SHOW => 'sshow', TABLE_VAR_IFIRST => 'sifirst', TABLE_VAR_ILAST => 'silast', TABLE_VAR_PAGE => 'spage'));
$table->setup();
list($esql, $params) = get_enrolled_sql($context, null, $currentgroup, true);
$joins = array("FROM {user} u");
$wheres = array();
$userfields = array('username', 'email', 'city', 'country', 'lang', 'timezone', 'maildisplay');
$mainuserfields = user_picture::fields('u', $userfields);
$extrasql = get_extra_user_fields_sql($context, 'u', '', $userfields);
if ($isfrontpage) {
    $select = "SELECT {$mainuserfields}, u.lastaccess{$extrasql}";
    $joins[] = "JOIN ({$esql}) e ON e.id = u.id";
    // Everybody on the frontpage usually.
    if ($accesssince) {
        $wheres[] = get_user_lastaccess_sql($accesssince);
    }
} else {
    $select = "SELECT {$mainuserfields}, COALESCE(ul.timeaccess, 0) AS lastaccess{$extrasql}";
    $joins[] = "JOIN ({$esql}) e ON e.id = u.id";
    // Course enrolled users only.
    $joins[] = "LEFT JOIN {user_lastaccess} ul ON (ul.userid = u.id AND ul.courseid = :courseid)";
    // Not everybody accessed course yet.
    $params['courseid'] = $course->id;
Exemplo n.º 21
0
/**
 * Returns posts made by the selected user in the requested courses.
 *
 * This method can be used to return all of the posts made by the requested user
 * within the given courses.
 * For each course the access of the current user and requested user is checked
 * and then for each post access to the post and forum is checked as well.
 *
 * This function is safe to use with usercapabilities.
 *
 * @global moodle_database $DB
 * @param stdClass $user The user whose posts we want to get
 * @param array $courses The courses to search
 * @param bool $musthaveaccess If set to true errors will be thrown if the user
 *                             cannot access one or more of the courses to search
 * @param bool $discussionsonly If set to true only discussion starting posts
 *                              will be returned.
 * @param int $limitfrom The offset of records to return
 * @param int $limitnum The number of records to return
 * @return stdClass An object the following properties
 *               ->totalcount: the total number of posts made by the requested user
 *                             that the current user can see.
 *               ->courses: An array of courses the current user can see that the
 *                          requested user has posted in.
 *               ->forums: An array of forums relating to the posts returned in the
 *                         property below.
 *               ->posts: An array containing the posts to show for this request.
 */
function forum_get_posts_by_user($user, array $courses, $musthaveaccess = false, $discussionsonly = false, $limitfrom = 0, $limitnum = 50) {
    global $DB, $USER, $CFG;

    $return = new stdClass;
    $return->totalcount = 0;    // The total number of posts that the current user is able to view
    $return->courses = array(); // The courses the current user can access
    $return->forums = array();  // The forums that the current user can access that contain posts
    $return->posts = array();   // The posts to display

    // First up a small sanity check. If there are no courses to check we can
    // return immediately, there is obviously nothing to search.
    if (empty($courses)) {
        return $return;
    }

    // A couple of quick setups
    $isloggedin = isloggedin();
    $isguestuser = $isloggedin && isguestuser();
    $iscurrentuser = $isloggedin && $USER->id == $user->id;

    // Checkout whether or not the current user has capabilities over the requested
    // user and if so they have the capabilities required to view the requested
    // users content.
    $usercontext = context_user::instance($user->id, MUST_EXIST);
    $hascapsonuser = !$iscurrentuser && $DB->record_exists('role_assignments', array('userid' => $USER->id, 'contextid' => $usercontext->id));
    $hascapsonuser = $hascapsonuser && has_all_capabilities(array('moodle/user:viewdetails', 'moodle/user:readuserposts'), $usercontext);

    // Before we actually search each course we need to check the user's access to the
    // course. If the user doesn't have the appropraite access then we either throw an
    // error if a particular course was requested or we just skip over the course.
    foreach ($courses as $course) {
        $coursecontext = context_course::instance($course->id, MUST_EXIST);
        if ($iscurrentuser || $hascapsonuser) {
            // If it is the current user, or the current user has capabilities to the
            // requested user then all we need to do is check the requested users
            // current access to the course.
            // Note: There is no need to check group access or anything of the like
            // as either the current user is the requested user, or has granted
            // capabilities on the requested user. Either way they can see what the
            // requested user posted, although its VERY unlikely in the `parent` situation
            // that the current user will be able to view the posts in context.
            if (!is_viewing($coursecontext, $user) && !is_enrolled($coursecontext, $user)) {
                // Need to have full access to a course to see the rest of own info
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }
        } else {
            // Check whether the current user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course)) {
                if ($musthaveaccess) {
                    print_error('errorenrolmentrequired', 'forum');
                }
                continue;
            }

            // Check whether the requested user is enrolled or has access to view the course
            // if they don't we immediately have a problem.
            if (!can_access_course($course, $user)) {
                if ($musthaveaccess) {
                    print_error('notenrolled', 'forum');
                }
                continue;
            }

            // If groups are in use and enforced throughout the course then make sure
            // we can meet in at least one course level group.
            // Note that we check if either the current user or the requested user have
            // the capability to access all groups. This is because with that capability
            // a user in group A could post in the group B forum. Grrrr.
            if (groups_get_course_groupmode($course) == SEPARATEGROUPS && $course->groupmodeforce
              && !has_capability('moodle/site:accessallgroups', $coursecontext) && !has_capability('moodle/site:accessallgroups', $coursecontext, $user->id)) {
                // If its the guest user to bad... the guest user cannot access groups
                if (!$isloggedin or $isguestuser) {
                    // do not use require_login() here because we might have already used require_login($course)
                    if ($musthaveaccess) {
                        redirect(get_login_url());
                    }
                    continue;
                }
                // Get the groups of the current user
                $mygroups = array_keys(groups_get_all_groups($course->id, $USER->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Get the groups the requested user is a member of
                $usergroups = array_keys(groups_get_all_groups($course->id, $user->id, $course->defaultgroupingid, 'g.id, g.name'));
                // Check whether they are members of the same group. If they are great.
                $intersect = array_intersect($mygroups, $usergroups);
                if (empty($intersect)) {
                    // But they're not... if it was a specific course throw an error otherwise
                    // just skip this course so that it is not searched.
                    if ($musthaveaccess) {
                        print_error("groupnotamember", '', $CFG->wwwroot."/course/view.php?id=$course->id");
                    }
                    continue;
                }
            }
        }
        // Woo hoo we got this far which means the current user can search this
        // this course for the requested user. Although this is only the course accessibility
        // handling that is complete, the forum accessibility tests are yet to come.
        $return->courses[$course->id] = $course;
    }
    // No longer beed $courses array - lose it not it may be big
    unset($courses);

    // Make sure that we have some courses to search
    if (empty($return->courses)) {
        // If we don't have any courses to search then the reality is that the current
        // user doesn't have access to any courses is which the requested user has posted.
        // Although we do know at this point that the requested user has posts.
        if ($musthaveaccess) {
            print_error('permissiondenied');
        } else {
            return $return;
        }
    }

    // Next step: Collect all of the forums that we will want to search.
    // It is important to note that this step isn't actually about searching, it is
    // about determining which forums we can search by testing accessibility.
    $forums = forum_get_forums_user_posted_in($user, array_keys($return->courses), $discussionsonly);

    // Will be used to build the where conditions for the search
    $forumsearchwhere = array();
    // Will be used to store the where condition params for the search
    $forumsearchparams = array();
    // Will record forums where the user can freely access everything
    $forumsearchfullaccess = array();
    // DB caching friendly
    $now = round(time(), -2);
    // For each course to search we want to find the forums the user has posted in
    // and providing the current user can access the forum create a search condition
    // for the forum to get the requested users posts.
    foreach ($return->courses as $course) {
        // Now we need to get the forums
        $modinfo = get_fast_modinfo($course);
        if (empty($modinfo->instances['forum'])) {
            // hmmm, no forums? well at least its easy... skip!
            continue;
        }
        // Iterate
        foreach ($modinfo->get_instances_of('forum') as $forumid => $cm) {
            if (!$cm->uservisible or !isset($forums[$forumid])) {
                continue;
            }
            // Get the forum in question
            $forum = $forums[$forumid];
            // This is needed for functionality later on in the forum code....
            $forum->cm = $cm;

            // Check that either the current user can view the forum, or that the
            // current user has capabilities over the requested user and the requested
            // user can view the discussion
            if (!has_capability('mod/forum:viewdiscussion', $cm->context) && !($hascapsonuser && has_capability('mod/forum:viewdiscussion', $cm->context, $user->id))) {
                continue;
            }

            // This will contain forum specific where clauses
            $forumsearchselect = array();
            if (!$iscurrentuser && !$hascapsonuser) {
                // Make sure we check group access
                if (groups_get_activity_groupmode($cm, $course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $cm->context)) {
                    $groups = $modinfo->get_groups($cm->groupingid);
                    $groups[] = -1;
                    list($groupid_sql, $groupid_params) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED, 'grps'.$forumid.'_');
                    $forumsearchparams = array_merge($forumsearchparams, $groupid_params);
                    $forumsearchselect[] = "d.groupid $groupid_sql";
                }

                // hidden timed discussions
                if (!empty($CFG->forum_enabletimedposts) && !has_capability('mod/forum:viewhiddentimedposts', $cm->context)) {
                    $forumsearchselect[] = "(d.userid = :userid{$forumid} OR (d.timestart < :timestart{$forumid} AND (d.timeend = 0 OR d.timeend > :timeend{$forumid})))";
                    $forumsearchparams['userid'.$forumid] = $user->id;
                    $forumsearchparams['timestart'.$forumid] = $now;
                    $forumsearchparams['timeend'.$forumid] = $now;
                }

                // qanda access
                if ($forum->type == 'qanda' && !has_capability('mod/forum:viewqandawithoutposting', $cm->context)) {
                    // We need to check whether the user has posted in the qanda forum.
                    $discussionspostedin = forum_discussions_user_has_posted_in($forum->id, $user->id);
                    if (!empty($discussionspostedin)) {
                        $forumonlydiscussions = array();  // Holds discussion ids for the discussions the user is allowed to see in this forum.
                        foreach ($discussionspostedin as $d) {
                            $forumonlydiscussions[] = $d->id;
                        }
                        list($discussionid_sql, $discussionid_params) = $DB->get_in_or_equal($forumonlydiscussions, SQL_PARAMS_NAMED, 'qanda'.$forumid.'_');
                        $forumsearchparams = array_merge($forumsearchparams, $discussionid_params);
                        $forumsearchselect[] = "(d.id $discussionid_sql OR p.parent = 0)";
                    } else {
                        $forumsearchselect[] = "p.parent = 0";
                    }

                }

                if (count($forumsearchselect) > 0) {
                    $forumsearchwhere[] = "(d.forum = :forum{$forumid} AND ".implode(" AND ", $forumsearchselect).")";
                    $forumsearchparams['forum'.$forumid] = $forumid;
                } else {
                    $forumsearchfullaccess[] = $forumid;
                }
            } else {
                // The current user/parent can see all of their own posts
                $forumsearchfullaccess[] = $forumid;
            }
        }
    }

    // If we dont have any search conditions, and we don't have any forums where
    // the user has full access then we just return the default.
    if (empty($forumsearchwhere) && empty($forumsearchfullaccess)) {
        return $return;
    }

    // Prepare a where condition for the full access forums.
    if (count($forumsearchfullaccess) > 0) {
        list($fullidsql, $fullidparams) = $DB->get_in_or_equal($forumsearchfullaccess, SQL_PARAMS_NAMED, 'fula');
        $forumsearchparams = array_merge($forumsearchparams, $fullidparams);
        $forumsearchwhere[] = "(d.forum $fullidsql)";
    }

    // Prepare SQL to both count and search.
    // We alias user.id to useridx because we forum_posts already has a userid field and not aliasing this would break
    // oracle and mssql.
    $userfields = user_picture::fields('u', null, 'useridx');
    $countsql = 'SELECT COUNT(*) ';
    $selectsql = 'SELECT p.*, d.forum, d.name AS discussionname, '.$userfields.' ';
    $wheresql = implode(" OR ", $forumsearchwhere);

    if ($discussionsonly) {
        if ($wheresql == '') {
            $wheresql = 'p.parent = 0';
        } else {
            $wheresql = 'p.parent = 0 AND ('.$wheresql.')';
        }
    }

    $sql = "FROM {forum_posts} p
            JOIN {forum_discussions} d ON d.id = p.discussion
            JOIN {user} u ON u.id = p.userid
           WHERE ($wheresql)
             AND p.userid = :userid ";
    $orderby = "ORDER BY p.modified DESC";
    $forumsearchparams['userid'] = $user->id;

    // Set the total number posts made by the requested user that the current user can see
    $return->totalcount = $DB->count_records_sql($countsql.$sql, $forumsearchparams);
    // Set the collection of posts that has been requested
    $return->posts = $DB->get_records_sql($selectsql.$sql.$orderby, $forumsearchparams, $limitfrom, $limitnum);

    // We need to build an array of forums for which posts will be displayed.
    // We do this here to save the caller needing to retrieve them themselves before
    // printing these forums posts. Given we have the forums already there is
    // practically no overhead here.
    foreach ($return->posts as $post) {
        if (!array_key_exists($post->forum, $return->forums)) {
            $return->forums[$post->forum] = $forums[$post->forum];
        }
    }

    return $return;
}
Exemplo n.º 22
0
 public function test_user_picture_fields_unaliasing_null()
 {
     $fields = user_picture::fields();
     $fields = array_map('trim', explode(',', $fields));
     $fakerecord = new stdClass();
     $fakerecord->aliasedid = 42;
     foreach ($fields as $field) {
         if ($field !== 'id') {
             $fakerecord->{'prefix' . $field} = "Value of {$field}";
         }
     }
     $fakerecord->prefixcustom1 = 'Value of custom1';
     $fakerecord->prefiximagealt = null;
     $returned = user_picture::unalias($fakerecord, array('custom1'), 'aliasedid', 'prefix');
     $this->assertEqual($returned->id, 42);
     $this->assertEqual($returned->imagealt, null);
     foreach ($fields as $field) {
         if ($field !== 'id' and $field !== 'imagealt') {
             $this->assertEqual($returned->{$field}, "Value of {$field}");
         }
     }
     $this->assertEqual($returned->custom1, 'Value of custom1');
 }
Exemplo n.º 23
0
/**
 * get users which have completed a feedback
 *
 * @global object
 * @uses CONTEXT_MODULE
 * @uses FEEDBACK_ANONYMOUS_NO
 * @param object $cm
 * @param int $group single groupid
 * @param string $where a sql where condition (must end with " AND ")
 * @param array parameters used in $where
 * @param string $sort a table field
 * @param int $startpage
 * @param int $pagecount
 * @return object the userrecords
 */
function feedback_get_complete_users($cm,
                                     $group = false,
                                     $where = '',
                                     array $params = null,
                                     $sort = '',
                                     $startpage = false,
                                     $pagecount = false) {

    global $DB;

    if (!$context = get_context_instance(CONTEXT_MODULE, $cm->id)) {
            print_error('badcontext');
    }

    $params = (array)$params;

    $params['anon'] = FEEDBACK_ANONYMOUS_NO;
    $params['instance'] = $cm->instance;

    $fromgroup = '';
    $wheregroup = '';
    if ($group) {
        $fromgroup = ', {groups_members} g';
        $wheregroup = ' AND g.groupid = :group AND g.userid = c.userid';
        $params['group'] = $group;
    }

    if ($sort) {
        $sortsql = ' ORDER BY '.$sort;
    } else {
        $sortsql = '';
    }

    $ufields = user_picture::fields('u');
    $sql = 'SELECT DISTINCT '.$ufields.', c.timemodified as completed_timemodified
            FROM {user} u, {feedback_completed} c '.$fromgroup.'
            WHERE '.$where.' anonymous_response = :anon
                AND u.id = c.userid
                AND c.feedback = :instance
              '.$wheregroup.$sortsql;

    if ($startpage === false OR $pagecount === false) {
        $startpage = false;
        $pagecount = false;
    }
    return $DB->get_records_sql($sql, $params, $startpage, $pagecount);
}
Exemplo n.º 24
0
/**
 * @global object
 * @global object
 * @global object
 * @uses CONTEXT_MODULE
 * @param object $choicegroup
 * @param object $cm
 * @return array
 */
function choicegroup_get_response_data($choicegroup, $cm)
{
    // Initialise the returned array, which is a matrix:  $allresponses[responseid][userid] = responseobject.
    static $allresponses = array();
    if (count($allresponses)) {
        return $allresponses;
    }
    // First get all the users who have access here.
    // To start with we assume they are all "unanswered" then move them later.
    $ctx = \context_module::instance($cm->id);
    $users = get_enrolled_users($ctx, 'mod/choicegroup:choose', 0, user_picture::fields('u', array('idnumber')), 'u.lastname ASC,u.firstname ASC');
    if ($users) {
        $modinfo = get_fast_modinfo($cm->course);
        $cminfo = $modinfo->get_cm($cm->id);
        $availability = new \core_availability\info_module($cminfo);
        $users = $availability->filter_user_list($users);
    }
    $allresponses[0] = $users;
    foreach ($allresponses[0] as $user) {
        $currentanswers = choicegroup_get_user_answer($choicegroup, $user, true);
        if ($currentanswers != false) {
            foreach ($currentanswers as $current) {
                $allresponses[$current->id][$user->id] = clone $allresponses[0][$user->id];
                $allresponses[$current->id][$user->id]->timemodified = $current->timeuseradded;
            }
            // Remove from unanswered column.
            unset($allresponses[0][$user->id]);
        }
    }
    return $allresponses;
}
 /**
  * overridden constructor keeps a reference to the assignment class that is displaying this table
  *
  * @param assign $assignment The assignment class
  * @param int $perpage how many per page
  * @param string $filter The current filter
  * @param int $rowoffset For showing a subsequent page of results
  * @param bool $quickgrading Is this table wrapped in a quickgrading form?
  * @param string $downloadfilename
  */
 public function __construct(assign $assignment, $perpage, $filter, $rowoffset, $quickgrading, $downloadfilename = null)
 {
     global $CFG, $PAGE, $DB, $USER;
     parent::__construct('mod_assign_grading');
     $this->is_persistent(true);
     $this->assignment = $assignment;
     // Check permissions up front.
     $this->hasgrantextension = has_capability('mod/assign:grantextension', $this->assignment->get_context());
     $this->hasgrade = $this->assignment->can_grade();
     // Check if we have the elevated view capablities to see the blind details.
     $this->hasviewblind = has_capability('mod/assign:viewblinddetails', $this->assignment->get_context());
     foreach ($assignment->get_feedback_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled()) {
             foreach ($plugin->get_grading_batch_operations() as $action => $description) {
                 if (empty($this->plugingradingbatchoperations)) {
                     $this->plugingradingbatchoperations[$plugin->get_type()] = array();
                 }
                 $this->plugingradingbatchoperations[$plugin->get_type()][$action] = $description;
             }
         }
     }
     $this->perpage = $perpage;
     $this->quickgrading = $quickgrading && $this->hasgrade;
     $this->output = $PAGE->get_renderer('mod_assign');
     $urlparams = array('action' => 'grading', 'id' => $assignment->get_course_module()->id);
     $url = new moodle_url($CFG->wwwroot . '/mod/assign/view.php', $urlparams);
     $this->define_baseurl($url);
     // Do some business - then set the sql.
     $currentgroup = groups_get_activity_group($assignment->get_course_module(), true);
     if ($rowoffset) {
         $this->rownum = $rowoffset - 1;
     }
     $users = array_keys($assignment->list_participants($currentgroup, true));
     if (count($users) == 0) {
         // Insert a record that will never match to the sql is still valid.
         $users[] = -1;
     }
     $params = array();
     $params['assignmentid1'] = (int) $this->assignment->get_instance()->id;
     $params['assignmentid2'] = (int) $this->assignment->get_instance()->id;
     $params['assignmentid3'] = (int) $this->assignment->get_instance()->id;
     $extrauserfields = get_extra_user_fields($this->assignment->get_context());
     $fields = user_picture::fields('u', $extrauserfields) . ', ';
     $fields .= 'u.id as userid, ';
     $fields .= 's.status as status, ';
     $fields .= 's.id as submissionid, ';
     $fields .= 's.timecreated as firstsubmission, ';
     $fields .= 's.timemodified as timesubmitted, ';
     $fields .= 's.attemptnumber as attemptnumber, ';
     $fields .= 'g.id as gradeid, ';
     $fields .= 'g.grade as grade, ';
     $fields .= 'g.timemodified as timemarked, ';
     $fields .= 'g.timecreated as firstmarked, ';
     $fields .= 'uf.mailed as mailed, ';
     $fields .= 'uf.locked as locked, ';
     $fields .= 'uf.extensionduedate as extensionduedate, ';
     $fields .= 'uf.workflowstate as workflowstate, ';
     $fields .= 'uf.allocatedmarker as allocatedmarker ';
     $from = '{user} u
                      LEFT JOIN {assign_submission} s
                             ON u.id = s.userid
                            AND s.assignment = :assignmentid1
                            AND s.latest = 1
                      LEFT JOIN {assign_grades} g
                             ON u.id = g.userid
                            AND g.assignment = :assignmentid2 ';
     // For group submissions we don't immediately create an entry in the assign_submission table for each user,
     // instead the userid is set to 0. In this case we use a different query to retrieve the grade for the user.
     if ($this->assignment->get_instance()->teamsubmission) {
         $params['assignmentid4'] = (int) $this->assignment->get_instance()->id;
         $grademaxattempt = 'SELECT mxg.userid, MAX(mxg.attemptnumber) AS maxattempt
                               FROM {assign_grades} mxg
                              WHERE mxg.assignment = :assignmentid4
                           GROUP BY mxg.userid';
         $from .= 'LEFT JOIN (' . $grademaxattempt . ') gmx
                          ON u.id = gmx.userid
                         AND g.attemptnumber = gmx.maxattempt ';
     } else {
         $from .= 'AND g.attemptnumber = s.attemptnumber ';
     }
     $from .= 'LEFT JOIN {assign_user_flags} uf
                      ON u.id = uf.userid
                     AND uf.assignment = :assignmentid3';
     $userparams = array();
     $userindex = 0;
     list($userwhere, $userparams) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED, 'user');
     $where = 'u.id ' . $userwhere;
     $params = array_merge($params, $userparams);
     // The filters do not make sense when there are no submissions, so do not apply them.
     if ($this->assignment->is_any_submission_plugin_enabled()) {
         if ($filter == ASSIGN_FILTER_SUBMITTED) {
             $where .= ' AND (s.timemodified IS NOT NULL AND
                              s.status = :submitted) ';
             $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
         } else {
             if ($filter == ASSIGN_FILTER_NOT_SUBMITTED) {
                 $where .= ' AND (s.timemodified IS NULL OR s.status != :submitted) ';
                 $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
             } else {
                 if ($filter == ASSIGN_FILTER_REQUIRE_GRADING) {
                     $where .= ' AND (s.timemodified IS NOT NULL AND
                              s.status = :submitted AND
                              (s.timemodified >= g.timemodified OR g.timemodified IS NULL OR g.grade IS NULL))';
                     $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
                 } else {
                     if (strpos($filter, ASSIGN_FILTER_SINGLE_USER) === 0) {
                         $userfilter = (int) array_pop(explode('=', $filter));
                         $where .= ' AND (u.id = :userid)';
                         $params['userid'] = $userfilter;
                     }
                 }
             }
         }
     }
     if ($this->assignment->get_instance()->markingworkflow && $this->assignment->get_instance()->markingallocation) {
         if (has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
             // Check to see if marker filter is set.
             $markerfilter = (int) get_user_preferences('assign_markerfilter', '');
             if (!empty($markerfilter)) {
                 if ($markerfilter == ASSIGN_MARKER_FILTER_NO_MARKER) {
                     $where .= ' AND (uf.allocatedmarker IS NULL OR uf.allocatedmarker = 0)';
                 } else {
                     $where .= ' AND uf.allocatedmarker = :markerid';
                     $params['markerid'] = $markerfilter;
                 }
             }
         } else {
             // Only show users allocated to this marker.
             $where .= ' AND uf.allocatedmarker = :markerid';
             $params['markerid'] = $USER->id;
         }
     }
     if ($this->assignment->get_instance()->markingworkflow) {
         $workflowstates = $this->assignment->get_marking_workflow_states_for_current_user();
         if (!empty($workflowstates)) {
             $workflowfilter = get_user_preferences('assign_workflowfilter', '');
             if ($workflowfilter == ASSIGN_MARKING_WORKFLOW_STATE_NOTMARKED) {
                 $where .= ' AND (uf.workflowstate = :workflowstate OR uf.workflowstate IS NULL OR ' . $DB->sql_isempty('assign_user_flags', 'workflowstate', true, true) . ')';
                 $params['workflowstate'] = $workflowfilter;
             } else {
                 if (array_key_exists($workflowfilter, $workflowstates)) {
                     $where .= ' AND uf.workflowstate = :workflowstate';
                     $params['workflowstate'] = $workflowfilter;
                 }
             }
         }
     }
     $this->set_sql($fields, $from, $where, $params);
     if ($downloadfilename) {
         $this->is_downloading('csv', $downloadfilename);
     }
     $columns = array();
     $headers = array();
     // Select.
     if (!$this->is_downloading() && $this->hasgrade) {
         $columns[] = 'select';
         $headers[] = get_string('select') . '<div class="selectall"><label class="accesshide" for="selectall">' . get_string('selectall') . '</label>
                 <input type="checkbox" id="selectall" name="selectall" title="' . get_string('selectall') . '"/></div>';
     }
     // User picture.
     if ($this->hasviewblind || !$this->assignment->is_blind_marking()) {
         if (!$this->is_downloading()) {
             $columns[] = 'picture';
             $headers[] = get_string('pictureofuser');
         } else {
             $columns[] = 'recordid';
             $headers[] = get_string('recordid', 'assign');
         }
         // Fullname.
         $columns[] = 'fullname';
         $headers[] = get_string('fullname');
         foreach ($extrauserfields as $extrafield) {
             $columns[] = $extrafield;
             $headers[] = get_user_field_name($extrafield);
         }
     } else {
         // Record ID.
         $columns[] = 'recordid';
         $headers[] = get_string('recordid', 'assign');
     }
     // Submission status.
     $columns[] = 'status';
     $headers[] = get_string('status', 'assign');
     // Team submission columns.
     if ($assignment->get_instance()->teamsubmission) {
         $columns[] = 'team';
         $headers[] = get_string('submissionteam', 'assign');
     }
     // Allocated marker.
     if ($this->assignment->get_instance()->markingworkflow && $this->assignment->get_instance()->markingallocation && has_capability('mod/assign:manageallocations', $this->assignment->get_context())) {
         // Add a column for the allocated marker.
         $columns[] = 'allocatedmarker';
         $headers[] = get_string('marker', 'assign');
     }
     // Grade.
     $columns[] = 'grade';
     $headers[] = get_string('grade');
     if ($this->is_downloading()) {
         if ($this->assignment->get_instance()->grade >= 0) {
             $columns[] = 'grademax';
             $headers[] = get_string('maxgrade', 'assign');
         } else {
             // This is a custom scale.
             $columns[] = 'scale';
             $headers[] = get_string('scale', 'assign');
         }
         if ($this->assignment->get_instance()->markingworkflow) {
             // Add a column for the marking workflow state.
             $columns[] = 'workflowstate';
             $headers[] = get_string('markingworkflowstate', 'assign');
         }
         // Add a column for the list of valid marking workflow states.
         $columns[] = 'gradecanbechanged';
         $headers[] = get_string('gradecanbechanged', 'assign');
     }
     if (!$this->is_downloading() && $this->hasgrade) {
         // We have to call this column userid so we can use userid as a default sortable column.
         $columns[] = 'userid';
         $headers[] = get_string('edit');
     }
     // Submission plugins.
     if ($assignment->is_any_submission_plugin_enabled()) {
         $columns[] = 'timesubmitted';
         $headers[] = get_string('lastmodifiedsubmission', 'assign');
         foreach ($this->assignment->get_submission_plugins() as $plugin) {
             if ($this->is_downloading()) {
                 if ($plugin->is_visible() && $plugin->is_enabled()) {
                     foreach ($plugin->get_editor_fields() as $field => $description) {
                         $index = 'plugin' . count($this->plugincache);
                         $this->plugincache[$index] = array($plugin, $field);
                         $columns[] = $index;
                         $headers[] = $plugin->get_name();
                     }
                 }
             } else {
                 if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
                     $index = 'plugin' . count($this->plugincache);
                     $this->plugincache[$index] = array($plugin);
                     $columns[] = $index;
                     $headers[] = $plugin->get_name();
                 }
             }
         }
     }
     // Time marked.
     $columns[] = 'timemarked';
     $headers[] = get_string('lastmodifiedgrade', 'assign');
     // Feedback plugins.
     foreach ($this->assignment->get_feedback_plugins() as $plugin) {
         if ($this->is_downloading()) {
             if ($plugin->is_visible() && $plugin->is_enabled()) {
                 foreach ($plugin->get_editor_fields() as $field => $description) {
                     $index = 'plugin' . count($this->plugincache);
                     $this->plugincache[$index] = array($plugin, $field);
                     $columns[] = $index;
                     $headers[] = $description;
                 }
             }
         } else {
             if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
                 $index = 'plugin' . count($this->plugincache);
                 $this->plugincache[$index] = array($plugin);
                 $columns[] = $index;
                 $headers[] = $plugin->get_name();
             }
         }
     }
     // Exclude 'Final grade' column in downloaded grading worksheets.
     if (!$this->is_downloading()) {
         // Final grade.
         $columns[] = 'finalgrade';
         $headers[] = get_string('finalgrade', 'grades');
     }
     // Load the grading info for all users.
     $this->gradinginfo = grade_get_grades($this->assignment->get_course()->id, 'mod', 'assign', $this->assignment->get_instance()->id, $users);
     if (!empty($CFG->enableoutcomes) && !empty($this->gradinginfo->outcomes)) {
         $columns[] = 'outcomes';
         $headers[] = get_string('outcomes', 'grades');
     }
     // Set the columns.
     $this->define_columns($columns);
     $this->define_headers($headers);
     foreach ($extrauserfields as $extrafield) {
         $this->column_class($extrafield, $extrafield);
     }
     $this->no_sorting('recordid');
     $this->no_sorting('finalgrade');
     $this->no_sorting('userid');
     $this->no_sorting('select');
     $this->no_sorting('outcomes');
     if ($assignment->get_instance()->teamsubmission) {
         $this->no_sorting('team');
     }
     $plugincolumnindex = 0;
     foreach ($this->assignment->get_submission_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
             $submissionpluginindex = 'plugin' . $plugincolumnindex++;
             $this->no_sorting($submissionpluginindex);
         }
     }
     foreach ($this->assignment->get_feedback_plugins() as $plugin) {
         if ($plugin->is_visible() && $plugin->is_enabled() && $plugin->has_user_summary()) {
             $feedbackpluginindex = 'plugin' . $plugincolumnindex++;
             $this->no_sorting($feedbackpluginindex);
         }
     }
     // When there is no data we still want the column headers printed in the csv file.
     if ($this->is_downloading()) {
         $this->start_output();
     }
 }
Exemplo n.º 26
0
/**
 * Returns all assignments since a given time
 *
 * @param array $activities The activity information is returned in this array
 * @param int $index The current index in the activities array
 * @param int $timestart The earliest activity to show
 * @param int $courseid Limit the search to this course
 * @param int $cmid The course module id
 * @param int $userid Optional user id
 * @param int $groupid Optional group id
 * @return void
 */
function assign_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);
    // no need pass this by reference as the return object already being cached
    $cm = $modinfo->get_cm($cmid);
    $params = array();
    if ($userid) {
        $userselect = "AND u.id = :userid";
        $params['userid'] = $userid;
    } else {
        $userselect = "";
    }
    if ($groupid) {
        $groupselect = "AND gm.groupid = :groupid";
        $groupjoin = "JOIN {groups_members} gm ON  gm.userid=u.id";
        $params['groupid'] = $groupid;
    } else {
        $groupselect = "";
        $groupjoin = "";
    }
    $params['cminstance'] = $cm->instance;
    $params['timestart'] = $timestart;
    $userfields = user_picture::fields('u', null, 'userid');
    if (!($submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified,\n                                                     {$userfields}\n                                                FROM {assign_submission} asb\n                                                JOIN {assign} a      ON a.id = asb.assignment\n                                                JOIN {user} u            ON u.id = asb.userid\n                                          {$groupjoin}\n                                               WHERE asb.timemodified > :timestart AND a.id = :cminstance\n                                                     {$userselect} {$groupselect}\n                                            ORDER BY asb.timemodified ASC", $params))) {
        return;
    }
    $groupmode = groups_get_activity_groupmode($cm, $course);
    $cm_context = context_module::instance($cm->id);
    $grader = has_capability('moodle/grade:viewall', $cm_context);
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
    $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
    if (is_null($modinfo->get_groups())) {
        $modinfo->groups = groups_get_user_groups($course->id);
        // load all my groups and cache it in modinfo
    }
    $showrecentsubmissions = get_config('mod_assign', 'showrecentsubmissions');
    $show = array();
    $usersgroups = groups_get_all_groups($course->id, $USER->id, $cm->groupingid);
    if (is_array($usersgroups)) {
        $usersgroups = array_keys($usersgroups);
    }
    foreach ($submissions as $submission) {
        if ($submission->userid == $USER->id) {
            $show[] = $submission;
            continue;
        }
        // the act of submitting of assignment may be considered private - only graders will see it if specified
        if (empty($showrecentsubmissions)) {
            if (!$grader) {
                continue;
            }
        }
        if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
            if (isguestuser()) {
                // shortcut - guest user does not belong into any group
                continue;
            }
            // this will be slow - show only users that share group with me in this cm
            if (empty($modinfo->groups[$cm->id])) {
                continue;
            }
            if (is_array($usersgroups)) {
                $intersect = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
                if (empty($intersect)) {
                    continue;
                }
            }
        }
        $show[] = $submission;
    }
    if (empty($show)) {
        return;
    }
    if ($grader) {
        require_once $CFG->libdir . '/gradelib.php';
        $userids = array();
        foreach ($show as $id => $submission) {
            $userids[] = $submission->userid;
        }
        $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
    }
    $aname = format_string($cm->name, true);
    foreach ($show as $submission) {
        $activity = new stdClass();
        $activity->type = 'assign';
        $activity->cmid = $cm->id;
        $activity->name = $aname;
        $activity->sectionnum = $cm->sectionnum;
        $activity->timestamp = $submission->timemodified;
        $activity->user = new stdClass();
        if ($grader) {
            $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
        }
        $userfields = explode(',', user_picture::fields());
        foreach ($userfields as $userfield) {
            if ($userfield == 'id') {
                $activity->user->{$userfield} = $submission->userid;
                // aliased in SQL above
            } else {
                $activity->user->{$userfield} = $submission->{$userfield};
            }
        }
        $activity->user->fullname = fullname($submission, $viewfullnames);
        $activities[$index++] = $activity;
    }
    return;
}
Exemplo n.º 27
0
 function definition()
 {
     global $CFG, $COURSE, $USER;
     $mform =& $this->_form;
     $context = context_course::instance($COURSE->id);
     $modinfo = get_fast_modinfo($COURSE);
     $sections = get_all_sections($COURSE->id);
     $mform->addElement('header', 'filters', get_string('managefilters'));
     //TODO: add better string
     $groupoptions = array();
     if (groups_get_course_groupmode($COURSE) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
         // limited group access
         $groups = groups_get_user_groups($COURSE->id);
         $allgroups = groups_get_all_groups($COURSE->id);
         if (!empty($groups[$COURSE->defaultgroupingid])) {
             foreach ($groups[$COURSE->defaultgroupingid] as $groupid) {
                 $groupoptions[$groupid] = format_string($allgroups[$groupid]->name, true, array('context' => $context));
             }
         }
     } else {
         $groupoptions = array('0' => get_string('allgroups'));
         if (has_capability('moodle/site:accessallgroups', $context)) {
             // user can see all groups
             $allgroups = groups_get_all_groups($COURSE->id);
         } else {
             // user can see course level groups
             $allgroups = groups_get_all_groups($COURSE->id, 0, $COURSE->defaultgroupingid);
         }
         foreach ($allgroups as $group) {
             $groupoptions[$group->id] = format_string($group->name, true, array('context' => $context));
         }
     }
     if ($COURSE->id == SITEID) {
         $viewparticipants = has_capability('moodle/site:viewparticipants', context_system::instance());
     } else {
         $viewparticipants = has_capability('moodle/course:viewparticipants', $context);
     }
     if ($viewparticipants) {
         $viewfullnames = has_capability('moodle/site:viewfullnames', context_course::instance($COURSE->id));
         $options = array();
         $options[0] = get_string('allparticipants');
         $options[$CFG->siteguest] = get_string('guestuser');
         if (isset($groupoptions[0])) {
             // can see all enrolled users
             if ($enrolled = get_enrolled_users($context, null, 0, user_picture::fields('u'))) {
                 foreach ($enrolled as $euser) {
                     $options[$euser->id] = fullname($euser, $viewfullnames);
                 }
             }
         } else {
             // can see users from some groups only
             foreach ($groupoptions as $groupid => $unused) {
                 if ($enrolled = get_enrolled_users($context, null, $groupid, user_picture::fields('u'))) {
                     foreach ($enrolled as $euser) {
                         if (!array_key_exists($euser->id, $options)) {
                             $options[$euser->id] = fullname($euser, $viewfullnames);
                         }
                     }
                 }
             }
         }
         $mform->addElement('select', 'user', get_string('participants'), $options);
         $mform->setAdvanced('user');
     }
     $sectiontitle = get_string('sectionname', 'format_' . $COURSE->format);
     $options = array('' => get_string('allactivities'));
     $modsused = array();
     foreach ($modinfo->cms as $cm) {
         if (!$cm->uservisible) {
             continue;
         }
         $modsused[$cm->modname] = true;
     }
     foreach ($modsused as $modname => $unused) {
         $libfile = "{$CFG->dirroot}/mod/{$modname}/lib.php";
         if (!file_exists($libfile)) {
             unset($modsused[$modname]);
             continue;
         }
         include_once $libfile;
         $libfunction = $modname . "_get_recent_mod_activity";
         if (!function_exists($libfunction)) {
             unset($modsused[$modname]);
             continue;
         }
         $options["mod/{$modname}"] = get_string('allmods', '', get_string('modulenameplural', $modname));
     }
     foreach ($modinfo->sections as $section => $cmids) {
         $options["section/{$section}"] = "-- " . get_section_name($COURSE, $sections[$section]) . " --";
         foreach ($cmids as $cmid) {
             $cm = $modinfo->cms[$cmid];
             if (empty($modsused[$cm->modname]) or !$cm->uservisible) {
                 continue;
             }
             $options[$cm->id] = format_string($cm->name);
         }
     }
     $mform->addElement('select', 'modid', get_string('activities'), $options);
     $mform->setAdvanced('modid');
     if ($groupoptions) {
         $mform->addElement('select', 'group', get_string('groups'), $groupoptions);
         $mform->setAdvanced('group');
     } else {
         // no access to groups in separate mode
         $mform->addElement('hidden', 'group');
         $mform->setType('group', PARAM_INT);
         $mform->setConstants(array('group' => -1));
     }
     $options = array('default' => get_string('bycourseorder'), 'dateasc' => get_string('datemostrecentlast'), 'datedesc' => get_string('datemostrecentfirst'));
     $mform->addElement('select', 'sortby', get_string('sortby'), $options);
     $mform->setAdvanced('sortby');
     $mform->addElement('date_time_selector', 'date', get_string('since'), array('optional' => true));
     $mform->addElement('hidden', 'id');
     $mform->setType('id', PARAM_INT);
     $mform->setType('courseid', PARAM_INT);
     $this->add_action_buttons(false, get_string('showrecent'));
 }
Exemplo n.º 28
0
/**
 * @global object
 * @param object $message message to be displayed.
 * @param mixed $chatuser user chat data
 * @param object $currentuser current user for whom the message should be displayed.
 * @param int $groupingid course module grouping id
 * @param string $theme name of the chat theme.
 * @return bool|string Returns HTML or false
 */
function chat_format_message_theme($message, $chatuser, $currentuser, $groupingid, $theme = 'bubble')
{
    global $CFG, $USER, $OUTPUT, $COURSE, $DB, $PAGE;
    require_once $CFG->dirroot . '/mod/chat/locallib.php';
    static $users;
    // Cache user lookups.
    $result = new stdClass();
    if (file_exists($CFG->dirroot . '/mod/chat/gui_ajax/theme/' . $theme . '/config.php')) {
        include $CFG->dirroot . '/mod/chat/gui_ajax/theme/' . $theme . '/config.php';
    }
    if (isset($users[$message->userid])) {
        $sender = $users[$message->userid];
    } else {
        if ($sender = $DB->get_record('user', array('id' => $message->userid), user_picture::fields())) {
            $users[$message->userid] = $sender;
        } else {
            return null;
        }
    }
    // Find the correct timezone for displaying this message.
    $tz = core_date::get_user_timezone($currentuser);
    if (empty($chatuser->course)) {
        $courseid = $COURSE->id;
    } else {
        $courseid = $chatuser->course;
    }
    $message->strtime = userdate($message->timestamp, get_string('strftimemessage', 'chat'), $tz);
    $message->picture = $OUTPUT->user_picture($sender, array('courseid' => $courseid));
    $message->picture = "<a target='_blank'" . " href=\"{$CFG->wwwroot}/user/view.php?id={$sender->id}&amp;course={$courseid}\">{$message->picture}</a>";
    // Start processing the message.
    if (!empty($message->system)) {
        $result->type = 'system';
        $senderprofile = $CFG->wwwroot . '/user/view.php?id=' . $sender->id . '&amp;course=' . $courseid;
        $event = get_string('message' . $message->message, 'chat', fullname($sender));
        $eventmessage = new event_message($senderprofile, fullname($sender), $message->strtime, $event, $theme);
        $output = $PAGE->get_renderer('mod_chat');
        $result->html = $output->render($eventmessage);
        return $result;
    }
    // It's not a system event.
    $text = trim($message->message);
    // Parse the text to clean and filter it.
    $options = new stdClass();
    $options->para = false;
    $text = format_text($text, FORMAT_MOODLE, $options, $courseid);
    // And now check for special cases.
    $special = false;
    $outtime = $message->strtime;
    // Initialise variables.
    $outmain = '';
    $patternto = '#^\\s*To\\s([^:]+):(.*)#';
    if (substr($text, 0, 5) == 'beep ') {
        $special = true;
        // It's a beep!
        $result->type = 'beep';
        $beepwho = trim(substr($text, 5));
        if ($beepwho == 'all') {
            // Everyone.
            $outmain = get_string('messagebeepseveryone', 'chat', fullname($sender));
        } else {
            if ($beepwho == $currentuser->id) {
                // Current user.
                $outmain = get_string('messagebeepsyou', 'chat', fullname($sender));
            } else {
                if ($sender->id == $currentuser->id) {
                    // Something is not caught?
                    // Allow beep for a active chat user only, else user can beep anyone and get fullname.
                    if (!empty($chatuser) && is_numeric($beepwho)) {
                        $chatusers = chat_get_users($chatuser->chatid, $chatuser->groupid, $groupingid);
                        if (array_key_exists($beepwho, $chatusers)) {
                            $outmain = get_string('messageyoubeep', 'chat', fullname($chatusers[$beepwho]));
                        } else {
                            $outmain = get_string('messageyoubeep', 'chat', $beepwho);
                        }
                    } else {
                        $outmain = get_string('messageyoubeep', 'chat', $beepwho);
                    }
                }
            }
        }
    } else {
        if (substr($text, 0, 1) == '/') {
            // It's a user command.
            $special = true;
            $result->type = 'command';
            $pattern = '#(^\\/)(\\w+).*#';
            preg_match($pattern, $text, $matches);
            $command = isset($matches[2]) ? $matches[2] : false;
            // Support some IRC commands.
            switch ($command) {
                case 'me':
                    $outmain = '*** <b>' . $sender->firstname . ' ' . substr($text, 4) . '</b>';
                    break;
                default:
                    // Error, we set special back to false to use the classic message output.
                    $special = false;
                    break;
            }
        } else {
            if (preg_match($patternto, $text)) {
                $special = true;
                $result->type = 'dialogue';
                $matches = array();
                preg_match($patternto, $text, $matches);
                if (isset($matches[1]) && isset($matches[2])) {
                    $outmain = $sender->firstname . ' <b>' . get_string('saidto', 'chat') . '</b> <i>' . $matches[1] . '</i>: ' . $matches[2];
                } else {
                    // Error, we set special back to false to use the classic message output.
                    $special = false;
                }
            }
        }
    }
    if (!$special) {
        $outmain = $text;
    }
    $result->text = strip_tags($outtime . ': ' . $outmain);
    $mymessageclass = '';
    if ($sender->id == $USER->id) {
        $mymessageclass = 'chat-message-mymessage';
    }
    $senderprofile = $CFG->wwwroot . '/user/view.php?id=' . $sender->id . '&amp;course=' . $courseid;
    $usermessage = new user_message($senderprofile, fullname($sender), $message->picture, $mymessageclass, $outtime, $outmain, $theme);
    $output = $PAGE->get_renderer('mod_chat');
    $result->html = $output->render($usermessage);
    // When user beeps other user, then don't show any timestamp to other users in chat.
    if ('' === $outmain && $special) {
        return false;
    } else {
        return $result;
    }
}
Exemplo n.º 29
0
// Sort by replies/discussions.
$mostposts = $mostdiscussions = $posts;
uasort($mostposts, function ($a, $b) {
    return $a->replies < $b->replies ? 1 : -1;
});
uasort($mostdiscussions, function ($a, $b) {
    return $a->discussions < $b->discussions ? 1 : -1;
});
$postkeys = array_keys($mostposts);
$discusskeys = array_keys($mostdiscussions);
echo html_writer::start_div('forumng_usage_contrib');
// Start posts/replies.
echo html_writer::start_div('forumng_usage_contrib_cont');
$toplist = array();
$totaltoshow = $contribcount > count($posts) ? count($posts) : $contribcount;
$userfields = user_picture::fields();
for ($a = 0; $a < $totaltoshow; $a++) {
    // Create list of most posts.
    if ($mostposts[$postkeys[$a]]->replies > 0) {
        if ($user = $DB->get_record('user', array('id' => $postkeys[$a]), $userfields)) {
            $toplist[] = $renderer->render_usage_list_item($forum, $mostposts[$postkeys[$a]]->replies, $user, html_writer::div($forum->display_user_link($user), 'fng_userlink'));
        }
    }
}
echo $renderer->render_usage_list($toplist, 'mostposts');
echo html_writer::end_div();
// End posts.
echo html_writer::start_div('forumng_usage_contrib_cont');
$toplist = array();
$totaltoshow = $contribcount > count($posts) ? count($posts) : $contribcount;
for ($a = 0; $a < $totaltoshow; $a++) {
Exemplo n.º 30
0
     $retorno = json_encode($retorno);
     echo $retorno;
     break;
 case 'mudar_status':
     $user = optional_param('user', 0, PARAM_INT);
     $param = array(1, $user, $USER->id);
     $DB->execute("UPDATE {chatwebgd_mensagem} SET lido = ? WHERE user_id = ? AND para_id = ?", $param);
     break;
 case 'atualizar_user_online':
     $timetoshowusers = 500;
     //Seconds default
     $now = time();
     $timefrom = $now - 3600;
     // $timefrom = 100 * floor(($now - $timetoshowusers) / 100);
     $params = array();
     $userfields = user_picture::fields('u', array('username'));
     $params['now'] = $now;
     $params['timefrom'] = $timefrom;
     $params['user_id'] = $USER->id;
     $sql = "SELECT {$userfields}\r\n                  FROM {user} u\r\n                 WHERE u.lastaccess > :timefrom\r\n                       AND u.lastaccess <= :now\r\n                       AND u.deleted = 0\r\n                       AND u.id <> :user_id";
     if ($users = $DB->get_records_sql($sql, $params, 0, 50)) {
         foreach ($users as $user) {
             $users[$user->id]->fullname = fullname($user);
         }
     } else {
         $users = array();
     }
     $retorno = "<ul class='list'>\n";
     if (!empty($users)) {
         foreach ($users as $user) {
             $retorno .= '<li class="listentry">';