Fill the table for displaying.

@param bool $activitylink If this report link to the activity report or the user report.
@param bool $studentcoursesonly Only show courses that the user is a student of.
770133
public function fill_table($activitylink = false, $studentcoursesonly = false) {
        global $CFG, $DB, $OUTPUT, $USER;

        if ($studentcoursesonly && count($this->studentcourseids) == 0) {
            return false;
        }

        // Only show user's courses instead of all courses.
        if ($this->courses) {
            $coursesdata = $this->setup_courses_data($studentcoursesonly);

            foreach ($coursesdata as $coursedata) {

                $course = $coursedata['course'];
                $coursecontext = $coursedata['context'];
                $finalgrade = $coursedata['finalgrade'];
                $courseitem = $coursedata['courseitem'];

                $coursename = format_string(get_course_display_name_for_list($course), true, array('context' => $coursecontext));
                // Link to the activity report version of the user grade report.
                if ($activitylink) {
                    $courselink = html_writer::link(new moodle_url('/course/user.php', array('mode' => 'grade', 'id' => $course->id,
                        'user' => $this->user->id)), $coursename);
                } else {
                    $courselink = html_writer::link(new moodle_url('/grade/report/user/index.php', array('id' => $course->id,
                        'userid' => $this->user->id, 'group' => $this->gpr->groupid)), $coursename);
                }

                $data = array($courselink, grade_format_gradevalue($finalgrade, $courseitem, true));

                if ($this->showrank['any']) {
                    if ($this->showrank[$course->id] && !is_null($finalgrade)) {
                        $rank = $coursedata['rank'];
                        $numusers = $coursedata['numusers'];
                        $data[] = "$rank/$numusers";
                    } else {
                        // No grade, no rank.
                        // Or this course wants rank hidden.
                        $data[] = '-';
                    }
                }

                $this->table->add_data($data);
            }

            return true;
        } else {
            echo $OUTPUT->notification(get_string('notenrolled', 'grades'), 'notifymessage');
            return false;
        }
    }
463250
public function calculate_sample($sampleid, $sampleorigin, $notusedstarttime = false, $notusedendtime = false) {

        $context = $this->retrieve('context', $sampleid);

        if (is_null($this->studentroleids)) {
            $this->studentroleids = array_keys(get_archetype_roles('student'));
        }

        foreach ($this->studentroleids as $role) {
            // We look for roles, not enrolments as a student assigned at category level is supposed to be a
            // course student.
            $students = get_role_users($role, $context, false, 'u.id', 'u.id');
            if ($students) {
                return self::get_max_value();
            }
        }

        return self::get_min_value();
    }
807673
public function link ( SiteLink $toSiteLink, SiteLink $fromSiteLink, EditInfo $editInfo = null ) {
		$params = array(
			'tosite' => $toSiteLink->getSiteId(),
			'totitle' => $toSiteLink->getPageName(),
			'fromsite' => $fromSiteLink->getSiteId(),
			'fromtitle' => $fromSiteLink->getPageName(),
		);

		$this->api->postRequest( 'wblinktitles', $params, $editInfo );
		return true;
	}
791885
public function can_add_instance($courseid) {
        global $CFG;
        require_once($CFG->dirroot . '/cohort/lib.php');
        $coursecontext = context_course::instance($courseid);
        if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) {
            return false;
        }
        return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
    }
742180
public function deleteResourceLink($resourcelink) {
        global $DB;

        $resourcelinkid = $resourcelink->getRecordId();

        // Delete any outstanding share keys for resource links for this consumer.
        $DB->delete_records($this->sharekeytable, ['resourcelinkid' => $resourcelinkid]);

        // Delete users.
        $DB->delete_records($this->userresulttable, ['resourcelinkid' => $resourcelinkid]);

        // Update any resource links for which this is the primary resource link.
        $records = $DB->get_records($this->resourcelinktable, ['primaryresourcelinkid' => $resourcelinkid]);
        foreach ($records as $record) {
            $record->primaryresourcelinkid = null;
            $DB->update_record($this->resourcelinktable, $record);
        }

        // Delete resource link.
        $DB->delete_records($this->resourcelinktable, ['id' => $resourcelinkid]);

        $resourcelink->initialize();

        return true;
    }
51151
protected function update_course($course, $externalcourse, progress_trace $trace) {
        global $CFG, $DB;

        $coursefields = array ('shortname', 'fullname', 'summary');
        static $shouldupdate;

        // Initialize $shouldupdate variable. Set to true if one or more fields are marked for update.
        if (!isset($shouldupdate)) {
            $shouldupdate = false;
            foreach ($coursefields as $field) {
                $shouldupdate = $shouldupdate || $this->get_config('course_'.$field.'_updateonsync');
            }
        }

        // If we should not update return immediately.
        if (!$shouldupdate) {
            return false;
        }

        require_once("$CFG->dirroot/course/lib.php");
        $courseupdated = false;
        $updatedcourse = new stdClass();
        $updatedcourse->id = $course->id;

        // Update course fields if necessary.
        foreach ($coursefields as $field) {
            // If field is marked to be updated on sync && field data was changed update it.
            if ($this->get_config('course_'.$field.'_updateonsync')
                    && isset($externalcourse[$this->get_config('course_'.$field)][0])
                    && $course->{$field} != $externalcourse[$this->get_config('course_'.$field)][0]) {
                $updatedcourse->{$field} = $externalcourse[$this->get_config('course_'.$field)][0];
                $courseupdated = true;
            }
        }

        if (!$courseupdated) {
            $trace->output(get_string('courseupdateskipped', 'enrol_ldap', $course));
            return false;
        }

        // Do not allow empty fullname or shortname.
        if ((isset($updatedcourse->fullname) && empty($updatedcourse->fullname))
                || (isset($updatedcourse->shortname) && empty($updatedcourse->shortname))) {
            // We are in trouble!
            $trace->output(get_string('cannotupdatecourse', 'enrol_ldap', $course));
            return false;
        }

        // Check if the shortname already exists if it does - skip course updating.
        if (isset($updatedcourse->shortname)
                && $DB->record_exists('course', array('shortname' => $updatedcourse->shortname))) {
            $trace->output(get_string('cannotupdatecourse_duplicateshortname', 'enrol_ldap', $course));
            return false;
        }

        // Finally - update course in DB.
        update_course($updatedcourse);
        $trace->output(get_string('courseupdated', 'enrol_ldap', $course));

        return true;
    }
357858
public function fill_links($links) {
	foreach ($links as $key => $link) {
		$this->add_link($key, $link);
	}
}
319321
public function createEntry(
        $title,
        $link = null,
        $content_type = 'text/plain'
    ) {
        $this->addEntry(new SwatNavBarEntry($title, $link, $content_type));
    }
1299518
public function assertRegionLinkFollow($link, $region)
    {
        $regionObj = $this->getRegion($region);

        // Find the link within the region
        $linkObj = $regionObj->findLink($link);
        if (empty($linkObj)) {
            throw new \Exception(sprintf('The link "%s" was not found in the region "%s" on the page %s', $link, $region, $this->getSession()->getCurrentUrl()));
        }
        $linkObj->click();
    }
167260
public static function get_activities_completion_status($courseid, $userid) {
        global $CFG, $USER;
        require_once($CFG->libdir . '/grouplib.php');

        $warnings = array();
        $arrayparams = array(
            'courseid' => $courseid,
            'userid'   => $userid,
        );

        $params = self::validate_parameters(self::get_activities_completion_status_parameters(), $arrayparams);

        $course = get_course($params['courseid']);
        $user = core_user::get_user($params['userid'], '*', MUST_EXIST);
        core_user::require_active_user($user);

        $context = context_course::instance($course->id);
        self::validate_context($context);

        // Check that current user have permissions to see this user's activities.
        if ($user->id != $USER->id) {
            require_capability('report/progress:view', $context);
            if (!groups_user_groups_visible($course, $user->id)) {
                // We are not in the same group!
                throw new moodle_exception('accessdenied', 'admin');
            }
        }

        $completion = new completion_info($course);
        $activities = $completion->get_activities();

        $results = array();
        foreach ($activities as $activity) {

            // Check if current user has visibility on this activity.
            if (!$activity->uservisible) {
                continue;
            }

            // Get progress information and state (we must use get_data because it works for all user roles in course).
            $activitycompletiondata = $completion->get_data($activity, true, $user->id);

            $results[] = array(
                       'cmid'          => $activity->id,
                       'modname'       => $activity->modname,
                       'instance'      => $activity->instance,
                       'state'         => $activitycompletiondata->completionstate,
                       'timecompleted' => $activitycompletiondata->timemodified,
                       'tracking'      => $activity->completion,
                       'overrideby'    => $activitycompletiondata->overrideby,
                       'valueused'     => core_availability\info::completion_value_used($course, $activity->id)
            );
        }

        $results = array(
            'statuses' => $results,
            'warnings' => $warnings
        );
        return $results;
    }
162494
public function can_add_instance($courseid) {
        global $CFG, $DB;
        require_once($CFG->dirroot.'/mnet/service/enrol/locallib.php');

        $service = mnetservice_enrol::get_instance();
        if (!$service->is_available()) {
            return false;
        }
        $coursecontext = context_course::instance($courseid);
        if (!has_capability('moodle/course:enrolconfig', $coursecontext)) {
            return false;
        }
        $subscribers = $service->get_remote_subscribers();
        if (empty($subscribers)) {
            return false;
        }

        return true;
    }
766119
public function update_calendar($coursemoduleid) {
        global $DB, $CFG;
        require_once($CFG->dirroot.'/calendar/lib.php');

        // Special case for add_instance as the coursemodule has not been set yet.
        $instance = $this->get_instance();

        // Start with creating the event.
        $event = new stdClass();
        $event->modulename  = 'assign';
        $event->courseid = $instance->course;
        $event->groupid = 0;
        $event->userid  = 0;
        $event->instance  = $instance->id;
        $event->type = CALENDAR_EVENT_TYPE_ACTION;

        // Convert the links to pluginfile. It is a bit hacky but at this stage the files
        // might not have been saved in the module area yet.
        $intro = $instance->intro;
        if ($draftid = file_get_submitted_draft_itemid('introeditor')) {
            $intro = file_rewrite_urls_to_pluginfile($intro, $draftid);
        }

        // We need to remove the links to files as the calendar is not ready
        // to support module events with file areas.
        $intro = strip_pluginfile_content($intro);
        if ($this->show_intro()) {
            $event->description = array(
                'text' => $intro,
                'format' => $instance->introformat
            );
        } else {
            $event->description = array(
                'text' => '',
                'format' => $instance->introformat
            );
        }

        $eventtype = ASSIGN_EVENT_TYPE_DUE;
        if ($instance->duedate) {
            $event->name = get_string('calendardue', 'assign', $instance->name);
            $event->eventtype = $eventtype;
            $event->timestart = $instance->duedate;
            $event->timesort = $instance->duedate;
            $select = "modulename = :modulename
                       AND instance = :instance
                       AND eventtype = :eventtype
                       AND groupid = 0
                       AND courseid <> 0";
            $params = array('modulename' => 'assign', 'instance' => $instance->id, 'eventtype' => $eventtype);
            $event->id = $DB->get_field_select('event', 'id', $select, $params);

            // Now process the event.
            if ($event->id) {
                $calendarevent = calendar_event::load($event->id);
                $calendarevent->update($event, false);
            } else {
                calendar_event::create($event, false);
            }
        } else {
            $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
                'eventtype' => $eventtype));
        }

        $eventtype = ASSIGN_EVENT_TYPE_GRADINGDUE;
        if ($instance->gradingduedate) {
            $event->name = get_string('calendargradingdue', 'assign', $instance->name);
            $event->eventtype = $eventtype;
            $event->timestart = $instance->gradingduedate;
            $event->timesort = $instance->gradingduedate;
            $event->id = $DB->get_field('event', 'id', array('modulename' => 'assign',
                'instance' => $instance->id, 'eventtype' => $event->eventtype));

            // Now process the event.
            if ($event->id) {
                $calendarevent = calendar_event::load($event->id);
                $calendarevent->update($event, false);
            } else {
                calendar_event::create($event, false);
            }
        } else {
            $DB->delete_records('event', array('modulename' => 'assign', 'instance' => $instance->id,
                'eventtype' => $eventtype));
        }

        return true;
    }
821875
public function onPageSectionIClickAtLink( $link, $pageSection = null )
    {
        trigger_error(
            "onPageSectionIClickAtLink is deprecated since v6.3.0 and will be removed in v7.0.0",
            E_USER_DEPRECATED
        );
        $base = $this->makeXpathForBlock( $pageSection );
        $el = $this->getXpath()->findLinks( $link, $base );
        EzAssertion::assertElementFound( $link, $el, $pageSection, 'link' );
        $el[0]->click();
    }
720111
protected static function sync_course_instances($courseid, $userid) {
        global $DB;

        static $preventrecursion = false;

        // does anything want to sync with this parent?
        if (!$enrols = $DB->get_records('enrol', array('customint1'=>$courseid, 'enrol'=>'meta'), 'id ASC')) {
            return;
        }

        if ($preventrecursion) {
            return;
        }

        $preventrecursion = true;

        try {
            foreach ($enrols as $enrol) {
                self::sync_with_parent_course($enrol, $userid);
            }
        } catch (Exception $e) {
            $preventrecursion = false;
            throw $e;
        }

        $preventrecursion = false;
    }
320690
private static function relationAddRelationshipTo($link, $plurality, $extra=[]){
    $options = static::relationOptions();

    preg_match('((?<FOREIGN_CLASS>\w+)(\.(?<FOREIGN_KEY>\w+))?(:(?<LOCAL_KEY>\w+))?)', $link, $parts);

    $foreign_class = isset($parts['FOREIGN_CLASS']) ? $parts['FOREIGN_CLASS'] : false;
    $foreign_key   = isset($parts['FOREIGN_KEY'])   ? $parts['FOREIGN_KEY']   : false;
    $local_key     = isset($parts['LOCAL_KEY'])     ? $parts['LOCAL_KEY']     : false;

    if ( ! $foreign_class )
       throw new Exception("[Core.Relation] Class ".get_called_class()." must define a foreign Model when assigning a relation.", 1);

    if ( ! is_subclass_of($foreign_class,"Model") )
       throw new Exception("[Core.Relation] Class ".get_called_class()." want to relate to $foreign_class but it's not a Model.", 1);

    if ( ! $foreign_key ) {
      // Retrieve primary key from foreign class
      $foreign_key = $foreign_class::persistenceOptions("key");
    }

    if ( ! $local_key ) {
      // Retrieve local primary key
      $local_key = static::persistenceOptions("key");
    }

    $single = $plurality == 'single';

    $method = preg_replace_callback('([A-Z])', function($m){
      return "_" . strtolower($m[0]);
    }, lcfirst($foreign_class) . ($single ? '' : 's'));

    $hh = [$foreign_class,$foreign_key,$local_key];
    sort($hh);
    $options->links[md5(serialize($hh))] = $rel = (object)[
      'foreign_class' =>  $foreign_class,
      'foreign_key'   =>  $foreign_key,
      'local_key'     =>  $local_key,
      'single'        =>  $single,
      'method'        =>  $method,
      'extra'         =>  (object) $extra,
    ];

    if (empty($options->relations)) $options->relations = (object)[];
    $options->relations->$method = $getset = (object)[
      'get' => function($self) use ($foreign_class, $rel) {
         $val = $self->{$rel->local_key};
         $val = is_numeric($val) ? $val : "'" . addslashes($val) . "'";
         $data = $foreign_class::where("{$rel->foreign_key} = {$val}");
         return $rel->single ? current($data) : $data;
      },
      'set' => function($value, $self) use ($foreign_class, $rel) {
        if (!is_a($value, $foreign_class))
          throw new Exception("[Core.Relation] Relationship for {$rel->method} must be of class $foreign_class.", 1);
        $self->local_key = $value->foreign_key;
        return $value;
      },
    ];

  }
1314397
protected function addNextLink($startRowNumber, &$nextLink)
    {
        $nextLink = $this->getLink($this->incrementPageRowNumber($startRowNumber), $this->getStyleClassAttributes('next'), $this->nextName);
    }
594889
protected function section_hidden($sectionno, $courseorid = null) {
        if ($courseorid) {
            $sectionname = get_section_name($courseorid, $sectionno);
            $strnotavailable = get_string('notavailablecourse', '', $sectionname);
        } else {
            $strnotavailable = get_string('notavailable');
        }

        $o = '';
        $o.= html_writer::start_tag('li', array('id' => 'section-'.$sectionno, 'class' => 'section main clearfix hidden'));
        $o.= html_writer::tag('div', '', array('class' => 'left side'));
        $o.= html_writer::tag('div', '', array('class' => 'right side'));
        $o.= html_writer::start_tag('div', array('class' => 'content'));
        $o.= html_writer::tag('div', $strnotavailable);
        $o.= html_writer::end_tag('div');
        $o.= html_writer::end_tag('li');
        return $o;
    }