Example #1
1
/**
 * Get accessdata for a given user.
 *
 * @private
 * @param int $userid
 * @param bool $preloadonly true means do not return access array
 * @return array accessdata
 */
function get_user_accessdata($userid, $preloadonly = false)
{
    global $CFG, $ACCESSLIB_PRIVATE, $USER;
    if (!empty($USER->acces['rdef']) and empty($ACCESSLIB_PRIVATE->rolepermissions)) {
        // share rdef from USER session with rolepermissions cache in order to conserve memory
        foreach ($USER->acces['rdef'] as $k => $v) {
            $ACCESSLIB_PRIVATE->rolepermissions[$k] =& $USER->acces['rdef'][$k];
        }
        $ACCESSLIB_PRIVATE->accessdatabyuser[$USER->id] = $USER->acces;
    }
    if (!isset($ACCESSLIB_PRIVATE->accessdatabyuser[$userid])) {
        if (empty($userid)) {
            if (!empty($CFG->notloggedinroleid)) {
                $accessdata = get_role_access($CFG->notloggedinroleid);
            } else {
                // weird
                return get_empty_accessdata();
            }
        } else {
            if (isguestuser($userid)) {
                if ($guestrole = get_guest_role()) {
                    $accessdata = get_role_access($guestrole->id);
                } else {
                    //weird
                    return get_empty_accessdata();
                }
            } else {
                $accessdata = get_user_access_sitewide($userid);
                // includes default role and frontpage role
            }
        }
        $ACCESSLIB_PRIVATE->accessdatabyuser[$userid] = $accessdata;
    }
    if ($preloadonly) {
        return;
    } else {
        return $ACCESSLIB_PRIVATE->accessdatabyuser[$userid];
    }
}
 private function getguestrolename()
 {
     static $guestrolename = null;
     if ($guestrolename === null) {
         $guestrole = get_guest_role();
         $guestrolename = empty($guestrole->name) ? $guestrole->shortname : $guestrole->name;
     }
     return $guestrolename;
 }
Example #3
0
 }
 // stuff under the "accounts" subcategory
 $ADMIN->add('accounts', new admin_externalpage('editusers', get_string('userlist', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/user.php", array('moodle/user:update', 'moodle/user:delete')));
 $ADMIN->add('accounts', new admin_externalpage('userbulk', get_string('userbulk', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/user/user_bulk.php", array('moodle/user:update', 'moodle/user:delete')));
 $ADMIN->add('accounts', new admin_externalpage('addnewuser', get_string('addnewuser'), "{$securewwwroot}/user/editadvanced.php?id=-1", 'moodle/user:create'));
 $ADMIN->add('accounts', new admin_externalpage('uploadusers', get_string('uploadusers'), "{$CFG->wwwroot}/{$CFG->admin}/uploaduser.php", 'moodle/site:uploadusers'));
 $ADMIN->add('accounts', new admin_externalpage('uploadpictures', get_string('uploadpictures', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/uploadpicture.php", 'moodle/site:uploadusers'));
 $ADMIN->add('accounts', new admin_externalpage('profilefields', get_string('profilefields', 'admin'), "{$CFG->wwwroot}/user/profile/index.php", 'moodle/site:config'));
 // stuff under the "roles" subcategory
 $ADMIN->add('users', new admin_category('roles', get_string('permissions', 'role')));
 // "userpolicies" settingpage
 $temp = new admin_settingpage('userpolicies', get_string('userpolicies', 'admin'));
 if ($ADMIN->fulltree) {
     if (!empty($CFG->rolesactive)) {
         $context = get_context_instance(CONTEXT_SYSTEM);
         if (!($guestrole = get_guest_role())) {
             $guestrole->id = 0;
         }
         if ($studentroles = get_roles_with_capability('moodle/legacy:student', CAP_ALLOW)) {
             $studentrole = array_shift($studentroles);
             /// Take the first one
         } else {
             $studentrole->id = 0;
         }
         if ($userroles = get_roles_with_capability('moodle/legacy:user', CAP_ALLOW)) {
             $userrole = array_shift($userroles);
             /// Take the first one
         } else {
             $userrole->id = 0;
         }
         if (empty($CFG->creatornewroleid)) {
    if (strtotime('-' . $i . ' months', $now) >= $minlog) {
        $timeoptions[strtotime('-' . $i . ' months', $now)] = get_string('nummonths', 'moodle', $i);
    }
}
// try a year
if (strtotime('-1 year', $now) >= $minlog) {
    $timeoptions[strtotime('-1 year', $now)] = get_string('lastyear');
}
$roleoptions = array();
// TODO: we need a new list of roles that are visible here
if ($roles = get_roles_used_in_context($context)) {
    foreach ($roles as $r) {
        $roleoptions[$r->id] = $r->name;
    }
}
$guestrole = get_guest_role();
if (empty($roleoptions[$guestrole->id])) {
    $roleoptions[$guestrole->id] = $guestrole->name;
}
$roleoptions = role_fix_names($roleoptions, $context);
// print first controls.
echo '<form class="participationselectform" action="index.php" method="get"><div>' . "\n" . '<input type="hidden" name="id" value="' . $course->id . '" />' . "\n";
echo '<label for="menuinstanceid">' . get_string('activitymodule') . '</label>' . "\n";
echo html_writer::select($instanceoptions, 'instanceid', $instanceid);
echo '<label for="menutimefrom">' . get_string('lookback') . '</label>' . "\n";
echo html_writer::select($timeoptions, 'timefrom', $timefrom);
echo '<label for="menuroleid">' . get_string('showonly') . '</label>' . "\n";
echo html_writer::select($roleoptions, 'roleid', $roleid, false);
echo '<label for="menuaction">' . get_string('showactions') . '</label>' . "\n";
echo html_writer::select($actionoptions, 'action', $action, false);
echo '<input type="submit" value="' . get_string('go') . '" />' . "\n</div></form>\n";
 /**
  * Test getting of guest role.
  */
 public function test_get_guest_role()
 {
     global $CFG;
     $guest = get_guest_role();
     $this->assertEquals('guest', $guest->archetype);
     $this->assertEquals('guest', $guest->shortname);
     $this->assertEquals($CFG->guestroleid, $guest->id);
 }
Example #6
0
/**
 *  A convenience function to completely load all the capabilities
 *  for the current user.   This is what gets called from complete_user_login()
 *  for example. Call it only _after_ you've setup $USER and called
 *  check_enrolment_plugins();
 *
 */
function load_all_capabilities()
{
    global $USER, $CFG, $ACCESSLIB_PRIVATE;
    // roles not installed yet - we are in the middle of installation
    if (empty($CFG->rolesactive)) {
        return;
    }
    $base = '/' . SYSCONTEXTID;
    if (isguestuser()) {
        $guest = get_guest_role();
        // Load the rdefs
        $USER->access = get_role_access($guest->id);
        // Put the ghost enrolment in place...
        $USER->access['ra'][$base] = array($guest->id);
    } else {
        if (isloggedin()) {
            $accessdata = get_user_access_sitewide($USER->id);
            //
            // provide "default role" & set 'dr'
            //
            if (!empty($CFG->defaultuserroleid)) {
                $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
                if (!isset($accessdata['ra'][$base])) {
                    $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
                } else {
                    array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
                }
                $accessdata['dr'] = $CFG->defaultuserroleid;
            }
            $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
            //
            // provide "default frontpage role"
            //
            if (!empty($CFG->defaultfrontpageroleid)) {
                $base = '/' . SYSCONTEXTID . '/' . $frontpagecontext->id;
                $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
                if (!isset($accessdata['ra'][$base])) {
                    $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
                } else {
                    array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
                }
            }
            $USER->access = $accessdata;
        } else {
            if (!empty($CFG->notloggedinroleid)) {
                $USER->access = get_role_access($CFG->notloggedinroleid);
                $USER->access['ra'][$base] = array($CFG->notloggedinroleid);
            }
        }
    }
    // Timestamp to read dirty context timestamps later
    $USER->access['time'] = time();
    $ACCESSLIB_PRIVATE->dirtycontexts = array();
    // Clear to force a refresh
    unset($USER->mycourses);
}
Example #7
0
/**
 * A convenience function to completely load all the capabilities
 * for the current user.   This is what gets called from complete_user_login()
 * for example. Call it only _after_ you've setup $USER and called
 * check_enrolment_plugins();
 * @see check_enrolment_plugins()
 *
 * @return void
 */
function load_all_capabilities()
{
    global $CFG, $ACCESSLIB_PRIVATE;
    //NOTE: we can not use $USER here because it may no be linked to $_SESSION['USER'] yet!
    // roles not installed yet - we are in the middle of installation
    if (during_initial_install()) {
        return;
    }
    $base = '/' . SYSCONTEXTID;
    if (isguestuser($_SESSION['USER'])) {
        $guest = get_guest_role();
        // Load the rdefs
        $_SESSION['USER']->access = get_role_access($guest->id);
        // Put the ghost enrolment in place...
        $_SESSION['USER']->access['ra'][$base] = array($guest->id => $guest->id);
    } else {
        if (!empty($_SESSION['USER']->id)) {
            // can not use isloggedin() yet
            $accessdata = get_user_access_sitewide($_SESSION['USER']->id);
            //
            // provide "default role" & set 'dr'
            //
            if (!empty($CFG->defaultuserroleid)) {
                $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
                if (!isset($accessdata['ra'][$base])) {
                    $accessdata['ra'][$base] = array();
                }
                $accessdata['ra'][$base][$CFG->defaultuserroleid] = $CFG->defaultuserroleid;
                $accessdata['dr'] = $CFG->defaultuserroleid;
            }
            $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
            //
            // provide "default frontpage role"
            //
            if (!empty($CFG->defaultfrontpageroleid)) {
                $base = '/' . SYSCONTEXTID . '/' . $frontpagecontext->id;
                $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
                if (!isset($accessdata['ra'][$base])) {
                    $accessdata['ra'][$base] = array();
                }
                $accessdata['ra'][$base][$CFG->defaultfrontpageroleid] = $CFG->defaultfrontpageroleid;
            }
            $_SESSION['USER']->access = $accessdata;
        } else {
            if (!empty($CFG->notloggedinroleid)) {
                $_SESSION['USER']->access = get_role_access($CFG->notloggedinroleid);
                $_SESSION['USER']->access['ra'][$base] = array($CFG->notloggedinroleid => $CFG->notloggedinroleid);
            }
        }
    }
    // Timestamp to read dirty context timestamps later
    $_SESSION['USER']->access['time'] = time();
    $ACCESSLIB_PRIVATE->dirtycontexts = array();
    // Clear to force a refresh
    unset($_SESSION['USER']->mycourses);
}
Example #8
0
 /**
  * Test the daily stats function.
  *
  * @depends test_statslib_get_base_daily
  * @depends test_statslib_get_next_day_start
  */
 public function test_statslib_cron_daily_no_default_profile_id()
 {
     global $CFG, $DB;
     $CFG->defaultfrontpageroleid = 0;
     $course1 = $DB->get_record('course', array('shortname' => 'course1'));
     $guestid = $CFG->siteguest;
     $start = stats_get_base_daily(1272758400);
     $end = stats_get_next_day_start($start);
     $fpid = (int) $CFG->defaultfrontpageroleid;
     $gr = get_guest_role();
     $dataset = $this->load_xml_data_file(__DIR__ . "/fixtures/statslib-test10.xml");
     $this->prepare_db($dataset[0], array('log'));
     // Stats cron daily uses mtrace, turn on buffering to silence output.
     ob_start();
     stats_cron_daily($maxdays = 1);
     $output = ob_get_contents();
     ob_end_clean();
     $this->verify_stats($dataset[1], $output);
 }
Example #9
0
/**
 * Print filter form.
 *
 * @param stdClass $course course object.
 * @param int $timefrom Time from which records should be fetched.
 * @param int $minlog Time of first record present in log store.
 * @param string $action action to be filtered.
 * @param int $roleid Role to be filtered.
 * @param int $instanceid Instance id of module.
 */
function report_participation_print_filter_form($course, $timefrom, $minlog, $action, $roleid, $instanceid)
{
    global $DB;
    $timeoptions = report_participation_get_time_options($minlog);
    $actionoptions = report_participation_get_action_options();
    // TODO: we need a new list of roles that are visible here.
    $context = context_course::instance($course->id);
    $roles = get_roles_used_in_context($context);
    $guestrole = get_guest_role();
    $roles[$guestrole->id] = $guestrole;
    $roleoptions = role_fix_names($roles, $context, ROLENAME_ALIAS, true);
    $modinfo = get_fast_modinfo($course);
    $modules = $DB->get_records_select('modules', "visible = 1", null, 'name ASC');
    $instanceoptions = array();
    foreach ($modules as $module) {
        if (empty($modinfo->instances[$module->name])) {
            continue;
        }
        $instances = array();
        foreach ($modinfo->instances[$module->name] as $cm) {
            // Skip modules such as label which do not actually have links;
            // this means there's nothing to participate in.
            if (!$cm->has_view()) {
                continue;
            }
            $instances[$cm->id] = format_string($cm->name);
        }
        if (count($instances) == 0) {
            continue;
        }
        $instanceoptions[] = array(get_string('modulenameplural', $module->name) => $instances);
    }
    echo '<form class="participationselectform" action="index.php" method="get"><div>' . "\n" . '<input type="hidden" name="id" value="' . $course->id . '" />' . "\n";
    echo '<label for="menuinstanceid">' . get_string('activitymodule') . '</label>' . "\n";
    echo html_writer::select($instanceoptions, 'instanceid', $instanceid);
    echo '<label for="menutimefrom">' . get_string('lookback') . '</label>' . "\n";
    echo html_writer::select($timeoptions, 'timefrom', $timefrom);
    echo '<label for="menuroleid">' . get_string('showonly') . '</label>' . "\n";
    echo html_writer::select($roleoptions, 'roleid', $roleid, false);
    echo '<label for="menuaction">' . get_string('showactions') . '</label>' . "\n";
    echo html_writer::select($actionoptions, 'action', $action, false);
    echo '<input type="submit" value="' . get_string('go') . '" />' . "\n</div></form>\n";
}
Example #10
0
/**
 * Execute daily statistics gathering
 * @param int $maxdays maximum number of days to be processed
 * @return boolean success
 */
function stats_cron_daily($maxdays = 1)
{
    global $CFG;
    $now = time();
    // read last execution date from db
    if (!($timestart = get_config(NULL, 'statslastdaily'))) {
        $timestart = stats_get_base_daily(stats_get_start_from('daily'));
        set_config('statslastdaily', $timestart);
    }
    $nextmidnight = stats_get_next_day_start($timestart);
    // are there any days that need to be processed?
    if ($now < $nextmidnight) {
        return true;
        // everything ok and up-to-date
    }
    $timeout = empty($CFG->statsmaxruntime) ? 60 * 60 * 24 : $CFG->statsmaxruntime;
    if (!set_cron_lock('statsrunning', $now + $timeout)) {
        return false;
    }
    // fisrt delete entries that should not be there yet
    delete_records_select('stats_daily', "timeend > {$timestart}");
    delete_records_select('stats_user_daily', "timeend > {$timestart}");
    // Read in a few things we'll use later
    $viewactions = implode(',', stats_get_action_names('view'));
    $postactions = implode(',', stats_get_action_names('post'));
    $guest = get_guest();
    $guestrole = get_guest_role();
    list($enroljoin, $enrolwhere) = stats_get_enrolled_sql($CFG->statscatdepth, true);
    list($enroljoin_na, $enrolwhere_na) = stats_get_enrolled_sql($CFG->statscatdepth, false);
    list($fpjoin, $fpwhere) = stats_get_enrolled_sql(0, true);
    mtrace("Running daily statistics gathering, starting at {$timestart}:");
    $days = 0;
    $failed = false;
    // failed stats flag
    while ($now > $nextmidnight) {
        if ($days >= $maxdays) {
            mtrace("...stopping early, reached maximum number of {$maxdays} days - will continue next time.");
            set_cron_lock('statsrunning', null);
            return false;
        }
        $days++;
        @set_time_limit($timeout - 200);
        if ($days > 1) {
            // move the lock
            set_cron_lock('statsrunning', time() + $timeout, true);
        }
        $daystart = time();
        $timesql = "l.time >= {$timestart}  AND l.time  < {$nextmidnight}";
        $timesql1 = "l1.time >= {$timestart} AND l1.time < {$nextmidnight}";
        $timesql2 = "l2.time >= {$timestart} AND l2.time < {$nextmidnight}";
        stats_daily_progress('init');
        /// find out if any logs available for this day
        $sql = "SELECT 'x'\n                  FROM {$CFG->prefix}log l\n                 WHERE {$timesql}";
        $logspresent = get_records_sql($sql, 0, 1);
        /// process login info first
        $sql = "INSERT INTO {$CFG->prefix}stats_user_daily (stattype, timeend, courseid, userid, statsreads)\n\n                SELECT 'logins', timeend, courseid, userid, count(statsreads)\n                  FROM (\n                           SELECT {$nextmidnight} AS timeend, " . SITEID . " AS courseid, l.userid, l.id AS statsreads\n                             FROM {$CFG->prefix}log l\n                            WHERE action = 'login' AND {$timesql}\n                       ) inline_view\n              GROUP BY timeend, courseid, userid\n                HAVING count(statsreads) > 0";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('1');
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'logins' AS stattype, {$nextmidnight} AS timeend, " . SITEID . " as courseid, 0,\n                       COALESCE((SELECT SUM(statsreads)\n                                       FROM {$CFG->prefix}stats_user_daily s1\n                                      WHERE s1.stattype = 'logins' AND timeend = {$nextmidnight}), 0) AS stat1,\n                       (SELECT COUNT('x')\n                          FROM {$CFG->prefix}stats_user_daily s2\n                         WHERE s2.stattype = 'logins' AND timeend = {$nextmidnight}) AS stat2" . sql_null_from_clause();
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('2');
        // Enrolments and active enrolled users
        //
        // Unfortunately, we do not know how many users were registered
        // at given times in history :-(
        // - stat1: enrolled users
        // - stat2: enrolled users active in this period
        // - enrolment is defined now as having course:view capability in
        //   course context or above, we look 3 cats upwards only and ignore prevent
        //   and prohibit caps to simplify it
        // - SITEID is specialcased here, because it's all about default enrolment
        //   in that case, we'll count non-deleted users.
        //
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'enrolments', timeend, courseid, roleid, COUNT(DISTINCT userid), 0\n                  FROM (\n                           SELECT {$nextmidnight} AS timeend, pl.courseid, pl.roleid, pl.userid\n                             FROM (\n                                      SELECT DISTINCT ra.roleid, ra.userid, c.id as courseid\n                                        FROM {$CFG->prefix}role_assignments ra {$enroljoin_na}\n                                       WHERE {$enrolwhere_na}\n                                   ) pl\n                       ) inline_view\n              GROUP BY timeend, courseid, roleid";
        if (!execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('3');
        // using table alias in UPDATE does not work in pg < 8.2
        $sql = "UPDATE {$CFG->prefix}stats_daily\n                   SET stat2 = (SELECT COUNT(DISTINCT ra.userid)\n                                  FROM {$CFG->prefix}role_assignments ra {$enroljoin_na}\n                                 WHERE ra.roleid = {$CFG->prefix}stats_daily.roleid AND\n                                       c.id = {$CFG->prefix}stats_daily.courseid AND\n                                       {$enrolwhere_na} AND\n                                       EXISTS (SELECT 'x'\n                                                 FROM {$CFG->prefix}log l\n                                                WHERE l.course = {$CFG->prefix}stats_daily.courseid AND\n                                                      l.userid = ra.userid AND {$timesql}))\n                 WHERE {$CFG->prefix}stats_daily.stattype = 'enrolments' AND\n                       {$CFG->prefix}stats_daily.timeend = {$nextmidnight} AND\n                       {$CFG->prefix}stats_daily.courseid IN\n                          (SELECT DISTINCT l.course\n                             FROM {$CFG->prefix}log l\n                            WHERE {$timesql})";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('4');
        /// now get course total enrolments (roleid==0) - except frontpage
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'enrolments', timeend, id, nroleid, COUNT(DISTINCT userid), 0\n                  FROM (\n                           SELECT {$nextmidnight} AS timeend, c.id, 0 AS nroleid, ra.userid\n                             FROM {$CFG->prefix}role_assignments ra {$enroljoin_na}\n                            WHERE c.id <> " . SITEID . " AND {$enrolwhere_na}\n                       ) inline_view\n              GROUP BY timeend, id, nroleid\n              HAVING COUNT(DISTINCT userid) > 0";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('5');
        $sql = "UPDATE {$CFG->prefix}stats_daily\n                   SET stat2 = (SELECT COUNT(DISTINCT ra.userid)\n                                  FROM {$CFG->prefix}role_assignments ra {$enroljoin_na}\n                                 WHERE c.id = {$CFG->prefix}stats_daily.courseid AND\n                                       {$enrolwhere_na} AND\n                                       EXISTS (SELECT 'x'\n                                                 FROM {$CFG->prefix}log l\n                                                WHERE l.course = {$CFG->prefix}stats_daily.courseid AND\n                                                      l.userid = ra.userid AND {$timesql}))\n                 WHERE {$CFG->prefix}stats_daily.stattype = 'enrolments' AND\n                       {$CFG->prefix}stats_daily.timeend = {$nextmidnight} AND\n                       {$CFG->prefix}stats_daily.roleid = 0 AND\n                       {$CFG->prefix}stats_daily.courseid IN\n                          (SELECT l.course\n                             FROM {$CFG->prefix}log l\n                            WHERE {$timesql} AND l.course <> " . SITEID . ")";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('6');
        /// frontapge(==site) enrolments total
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'enrolments', {$nextmidnight}, " . SITEID . ", 0,\n                       (SELECT COUNT('x')\n                          FROM {$CFG->prefix}user u\n                         WHERE u.deleted = 0) AS stat1,\n                       (SELECT COUNT(DISTINCT u.id)\n                          FROM {$CFG->prefix}user u\n                               JOIN {$CFG->prefix}log l ON l.userid = u.id\n                         WHERE u.deleted = 0 AND {$timesql}) AS stat2" . sql_null_from_clause();
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('7');
        if (empty($CFG->defaultfrontpageroleid)) {
            // 1.9 only, so far
            $defaultfproleid = 0;
        } else {
            $defaultfproleid = $CFG->defaultfrontpageroleid;
        }
        /// Default frontpage role enrolments are all site users (not deleted)
        if ($defaultfproleid) {
            // first remove default frontpage role counts if created by previous query
            $sql = "DELETE\n                      FROM {$CFG->prefix}stats_daily\n                     WHERE stattype = 'enrolments' AND courseid = " . SITEID . " AND\n                           roleid = {$defaultfproleid} AND timeend = {$nextmidnight}";
            if ($logspresent and !execute_sql($sql, false)) {
                $failed = true;
                break;
            }
            stats_daily_progress('8');
            $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                    SELECT 'enrolments', {$nextmidnight}, " . SITEID . ", {$defaultfproleid},\n                           (SELECT COUNT('x')\n                              FROM {$CFG->prefix}user u\n                             WHERE u.deleted = 0) AS stat1,\n                           (SELECT COUNT(DISTINCT u.id)\n                              FROM {$CFG->prefix}user u\n                                   JOIN {$CFG->prefix}log l ON l.userid = u.id\n                             WHERE u.deleted = 0 AND {$timesql}) AS stat2" . sql_null_from_clause();
            if ($logspresent and !execute_sql($sql, false)) {
                $failed = true;
                break;
            }
            stats_daily_progress('9');
        } else {
            stats_daily_progress('x');
            stats_daily_progress('x');
        }
        /// individual user stats (including not-logged-in) in each course, this is slow - reuse this data if possible
        $sql = "INSERT INTO {$CFG->prefix}stats_user_daily (stattype, timeend, courseid, userid, statsreads, statswrites)\n\n                SELECT 'activity' AS stattype, {$nextmidnight} AS timeend, d.courseid, d.userid,\n                       (SELECT COUNT('x')\n                          FROM {$CFG->prefix}log l\n                         WHERE l.userid = d.userid AND\n                               l.course = d.courseid AND {$timesql} AND\n                               l.action IN ({$viewactions})) AS statsreads,\n                       (SELECT COUNT('x')\n                          FROM {$CFG->prefix}log l\n                         WHERE l.userid = d.userid AND\n                               l.course = d.courseid AND {$timesql} AND\n                               l.action IN ({$postactions})) AS statswrites\n                  FROM (SELECT DISTINCT u.id AS userid, l.course AS courseid\n                          FROM {$CFG->prefix}user u, {$CFG->prefix}log l\n                         WHERE u.id = l.userid AND {$timesql}\n                       UNION\n                        SELECT 0 AS userid, " . SITEID . " AS courseid" . sql_null_from_clause() . ") d";
        // can not use group by here because pg can not handle it :-(
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('10');
        /// how many view/post actions in each course total
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'activity' AS stattype, {$nextmidnight} AS timeend, c.id AS courseid, 0,\n                       (SELECT COUNT('x')\n                          FROM {$CFG->prefix}log l1\n                         WHERE l1.course = c.id AND l1.action IN ({$viewactions}) AND\n                               {$timesql1}) AS stat1,\n                       (SELECT COUNT('x')\n                          FROM {$CFG->prefix}log l2\n                         WHERE l2.course = c.id AND l2.action IN ({$postactions}) AND\n                               {$timesql2}) AS stat2\n                  FROM {$CFG->prefix}course c\n                 WHERE EXISTS (SELECT 'x'\n                                 FROM {$CFG->prefix}log l\n                                WHERE l.course = c.id and {$timesql})";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('11');
        /// how many view actions for each course+role - excluding guests and frontpage
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'activity', timeend, courseid, roleid, SUM(statsreads), SUM(statswrites)\n                FROM (\n                         SELECT {$nextmidnight} AS timeend, pl.courseid, pl.roleid, sud.statsreads, sud.statswrites\n                         FROM {$CFG->prefix}stats_user_daily sud,\n                                  (SELECT DISTINCT ra.userid, ra.roleid, c.id AS courseid\n                                     FROM {$CFG->prefix}role_assignments ra {$enroljoin}\n                                    WHERE c.id <> " . SITEID . " AND\n                                          ra.roleid <> {$guestrole->id} AND\n                                          ra.userid <> {$guest->id} AND\n                                          {$enrolwhere}\n                                  ) pl\n                         WHERE sud.userid = pl.userid AND\n                               sud.courseid = pl.courseid AND\n                               sud.timeend = {$nextmidnight} AND\n                               sud.stattype='activity'\n                     ) inline_view\n            GROUP BY timeend, courseid, roleid\n              HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('12');
        /// how many view actions from guests only in each course - excluding frontpage
        /// (guest is anybody with guest role or no role with course:view in course - this may not work properly if category limit too low)
        /// normal users may enter course with temporary guest acces too
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'activity', timeend, courseid, nroleid, SUM(statsreads), SUM(statswrites)\n                  FROM (\n                           SELECT {$nextmidnight} AS timeend, sud.courseid, {$guestrole->id} AS nroleid, sud.statsreads, sud.statswrites\n                             FROM {$CFG->prefix}stats_user_daily sud\n                            WHERE sud.timeend = {$nextmidnight} AND sud.courseid <> " . SITEID . " AND\n                                  sud.stattype='activity' AND\n                                  (sud.userid = {$guest->id} OR sud.userid\n                                    NOT IN (SELECT ra.userid\n                                              FROM {$CFG->prefix}role_assignments ra {$enroljoin}\n                                             WHERE c.id <> " . SITEID . " AND  ra.roleid <> {$guestrole->id} AND\n                                                   {$enrolwhere}))\n                       ) inline_view\n              GROUP BY timeend, courseid, nroleid\n                HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('13');
        /// how many view actions for each role on frontpage - excluding guests, not-logged-in and default frontpage role
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'activity', timeend, courseid, roleid, SUM(statsreads), SUM(statswrites)\n                  FROM (\n                           SELECT {$nextmidnight} AS timeend, pl.courseid, pl.roleid, sud.statsreads, sud.statswrites\n                             FROM {$CFG->prefix}stats_user_daily sud,\n                                      (SELECT DISTINCT ra.userid, ra.roleid, c.id AS courseid\n                                         FROM {$CFG->prefix}role_assignments ra {$enroljoin}\n                                        WHERE c.id = " . SITEID . " AND\n                                              ra.roleid <> {$defaultfproleid} AND\n                                              ra.roleid <> {$guestrole->id} AND\n                                              ra.userid <> {$guest->id} AND\n                                              {$enrolwhere}\n                                      ) pl\n                            WHERE sud.userid = pl.userid AND\n                                  sud.courseid = pl.courseid AND\n                                  sud.timeend = {$nextmidnight} AND\n                                  sud.stattype='activity'\n                       ) inline_view\n              GROUP BY timeend, courseid, roleid\n                HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('14');
        /// how many view actions for default frontpage role on frontpage only
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'activity', timeend, courseid, nroleid, SUM(statsreads), SUM(statswrites)\n                  FROM (\n                           SELECT {$nextmidnight} AS timeend, sud.courseid, {$defaultfproleid} AS nroleid, sud.statsreads, sud.statswrites\n                             FROM {$CFG->prefix}stats_user_daily sud\n                             WHERE sud.timeend = {$nextmidnight} AND sud.courseid = " . SITEID . " AND\n                                   sud.stattype='activity' AND\n                                   sud.userid <> {$guest->id} AND sud.userid <> 0 AND sud.userid\n                                   NOT IN (SELECT ra.userid\n                                             FROM {$CFG->prefix}role_assignments ra {$fpjoin}\n                                            WHERE c.id = " . SITEID . " AND  ra.roleid <> {$guestrole->id} AND\n                                                  ra.roleid <> {$defaultfproleid} AND {$fpwhere})\n                       ) inline_view\n              GROUP BY timeend, courseid, nroleid\n                HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('15');
        /// how many view actions for guests or not-logged-in on frontpage
        $sql = "INSERT INTO {$CFG->prefix}stats_daily (stattype, timeend, courseid, roleid, stat1, stat2)\n\n                SELECT 'activity', timeend, courseid, nroleid, SUM(statsreads), SUM(statswrites)\n                  FROM (\n                           SELECT {$nextmidnight} AS timeend, " . SITEID . " AS courseid, {$guestrole->id} AS nroleid, pl.statsreads, pl.statswrites\n                             FROM (\n                                      SELECT sud.statsreads, sud.statswrites\n                                        FROM {$CFG->prefix}stats_user_daily sud\n                                      WHERE (sud.userid = {$guest->id} OR sud.userid = 0) AND\n                                            sud.timeend = {$nextmidnight} AND sud.courseid = " . SITEID . " AND\n                                            sud.stattype='activity'\n                                  ) pl\n                       ) inline_view\n              GROUP BY timeend, courseid, nroleid\n                HAVING SUM(statsreads) > 0 OR SUM(statswrites) > 0";
        if ($logspresent and !execute_sql($sql, false)) {
            $failed = true;
            break;
        }
        stats_daily_progress('16');
        // remember processed days
        set_config('statslastdaily', $nextmidnight);
        mtrace("  finished until {$nextmidnight}: " . userdate($nextmidnight) . " (in " . (time() - $daystart) . " s)");
        $timestart = $nextmidnight;
        $nextmidnight = stats_get_next_day_start($nextmidnight);
    }
    set_cron_lock('statsrunning', null);
    if ($failed) {
        $days--;
        mtrace("...error occured, completed {$days} days of statistics.");
        return false;
    } else {
        mtrace("...completed {$days} days of statistics.");
        return true;
    }
}
Example #11
0
/**
 *  A convenience function to completely load all the capabilities 
 *  for the current user.   This is what gets called from login, for example.
 */
function load_all_capabilities()
{
    global $USER, $CFG;
    $base = '/' . SYSCONTEXTID;
    if (isguestuser()) {
        $guest = get_guest_role();
        // Load the rdefs
        $USER->access = get_role_access($guest->id);
        // Put the ghost enrolment in place...
        $USER->access['ra'][$base] = array($guest->id);
    } else {
        if (isloggedin()) {
            check_enrolment_plugins($USER);
            $accessdata = get_user_access_sitewide($USER->id);
            //
            // provide "default role" & set 'dr'
            //
            if (!empty($CFG->defaultuserroleid)) {
                $accessdata = get_role_access($CFG->defaultuserroleid, $accessdata);
                if (!isset($accessdata['ra'][$base])) {
                    $accessdata['ra'][$base] = array($CFG->defaultuserroleid);
                } else {
                    array_push($accessdata['ra'][$base], $CFG->defaultuserroleid);
                }
                $accessdata['dr'] = $CFG->defaultuserroleid;
            }
            $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID);
            //
            // provide "default frontpage role"
            //
            if (!empty($CFG->defaultfrontpageroleid)) {
                $base = '/' . SYSCONTEXTID . '/' . $frontpagecontext->id;
                $accessdata = get_default_frontpage_role_access($CFG->defaultfrontpageroleid, $accessdata);
                if (!isset($accessdata['ra'][$base])) {
                    $accessdata['ra'][$base] = array($CFG->defaultfrontpageroleid);
                } else {
                    array_push($accessdata['ra'][$base], $CFG->defaultfrontpageroleid);
                }
            }
            $USER->access = $accessdata;
        } else {
            if (!empty($CFG->notloggedinroleid)) {
                $USER->access = get_role_access($CFG->notloggedinroleid);
                $USER->access['ra'][$base] = array($CFG->notloggedinroleid);
            }
        }
    }
    // Timestamp to read
    // dirty context timestamps
    $USER->access['time'] = time();
    // Clear to force a refresh
    unset($USER->mycourses);
}
Example #12
0
/**
 * Get the default guest role
 * @return object role
 */
function get_guest_role()
{
    global $CFG;
    if (empty($CFG->guestroleid)) {
        if ($roles = get_roles_with_capability('moodle/legacy:guest', CAP_ALLOW)) {
            $guestrole = array_shift($roles);
            // Pick the first one
            set_config('guestroleid', $guestrole->id);
            return $guestrole;
        } else {
            debugging('Can not find any guest role!');
            return false;
        }
    } else {
        if ($guestrole = get_record('role', 'id', $CFG->guestroleid)) {
            return $guestrole;
        } else {
            //somebody is messing with guest roles, remove incorrect setting and try to find a new one
            set_config('guestroleid', '');
            return get_guest_role();
        }
    }
}