/**
 * Returns the url of the first image contained in the course summary file area
 * @param  int $id the course id
 * @return string     the url to the image
 */
function block_my_course_progress_get_course_image_url($id)
{
    global $CFG;
    require_once $CFG->libdir . "/filelib.php";
    $course = get_course($id);
    if ($course instanceof stdClass) {
        require_once $CFG->libdir . '/coursecatlib.php';
        $course = new course_in_list($course);
    }
    foreach ($course->get_course_overviewfiles() as $file) {
        $isimage = $file->is_valid_image();
        if ($isimage) {
            return file_encode_url("{$CFG->wwwroot}/pluginfile.php", '/' . $file->get_contextid() . '/' . $file->get_component() . '/' . $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
        }
    }
    return false;
}
 protected function mycourses($CFG, $sidebar)
 {
     $mycourses = enrol_get_users_courses($_SESSION['USER']->id);
     $courselist = array();
     foreach ($mycourses as $key => $val) {
         $courselist[] = $val->id;
     }
     $content = '';
     for ($x = 1; $x <= sizeof($courselist); $x++) {
         $course = get_course($courselist[$x - 1]);
         $title = $course->fullname;
         if ($course instanceof stdClass) {
             require_once $CFG->libdir . '/coursecatlib.php';
             $course = new course_in_list($course);
         }
         $url = $CFG->wwwroot . "/theme/keats/pix/coursenoimage.jpg";
         foreach ($course->get_course_overviewfiles() as $file) {
             $isimage = $file->is_valid_image();
             $url = file_encode_url("{$CFG->wwwroot}/pluginfile.php", '/' . $file->get_contextid() . '/' . $file->get_component() . '/' . $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
             if (!$isimage) {
                 $url = $CFG->wwwroot . "/theme/keats/pix/coursenoimage.jpg";
             }
         }
         $content .= '<div class="view view-second view-mycourse ' . ($x % 3 == 0 ? 'view-nomargin' : '') . '">
                         <img src="' . $url . '" />
                         <div class="mask">
                             <h2>' . $title . '</h2>
                             <a href="' . $CFG->wwwroot . '/course/view.php?id=' . $courselist[$x - 1] . '" class="info">Enter</a>
                         </div>
                     </div>';
     }
     return $content;
 }
 function definition()
 {
     global $DB, $PAGE, $OUTPUT;
     $id = required_param('id', PARAM_INT);
     // course module
     if (!($cm = get_coursemodule_from_id('blended', $id))) {
         error("Course Module ID was incorrect");
     }
     if (!($course = get_course($cm->course))) {
         error("Course is misconfigured");
     }
     if (!($blended = $DB->get_record('blended', array('id' => $cm->instance)))) {
         error("Course module is incorrect");
     }
     $form =& $this->_form;
     $calificables = new grade_tree($course->id);
     $items = $calificables->items;
     $ins = array();
     $assignmentname = array();
     // Obtenemos las referencias a toda la informaci�n sobre los modulos dentro del curso
     $modinfo = get_fast_modinfo($course->id);
     foreach ($modinfo->instances as $abc) {
         foreach ($abc as $cmd) {
             foreach ($items as $r => $ite) {
                 $ins[$r] = $ite->iteminstance;
                 if ($cmd->instance == $ins[$r]) {
                     $assignmentname[$r] = $cmd->name;
                 }
             }
         }
     }
     $form->addElement('select', 'activities', 'Selecciona la Tarea', $assignmentname);
 }
Пример #4
0
/**
 * Add a "Compile" menu link to the Course Admin block as the top link.
 *
 * @author Gerald Albion
 * date 2014-10-31
 * @copyright 2014 Royal Roads University
 * @param object $settingsnav Main navigation object.
 * @param object $context Course context.
 */
function local_compile_extends_settings_navigation($settingsnav, $context)
{
    // Context must be course.
    if ($context->contextlevel != CONTEXT_COURSE) {
        return;
    }
    // Must be in a valid course: Cannot be course id 0.
    if ($context->instanceid == 0) {
        return;
    }
    // Must be in a valid course: Course must be retrievable.
    if (!($course = get_course($context->instanceid))) {
        return;
    }
    // Must be enrolled or otherwise allowed to view the course.
    if (!(is_enrolled($context) || is_viewing($context))) {
        return;
    }
    // Must have a course admin menu in which to add link.
    if (!($coursenode = $settingsnav->find('courseadmin', navigation_node::TYPE_COURSE))) {
        return;
    }
    // Good to go.  Build the menu item.
    $url = new moodle_url('/local/compile/list_modules.php', array('id' => $course->id));
    $newnode = navigation_node::create(get_string('menucaption', 'local_compile'), $url, navigation_node::NODETYPE_LEAF, 'compile', 'compile', new pix_icon('i/settings', ''));
    // We want to put this link at the top: find the existing top (first) node.
    $firstnode = $coursenode->get_children_key_list()[0];
    // Add the menu item to the menu, before the first node.
    $coursenode->add_node($newnode, $firstnode);
}
Пример #5
0
            function section_activities($secid,$cid){
                $course=get_course($cid);
                $modinfo = get_fast_modinfo($course);
                $mods = $modinfo->get_cms();
                $sections = $modinfo->get_section_info_all();
                $sec_array = get_sections($sections);
                $arr = array();
                $cnt=0;

            //preparing an array which contains sections and activities
                foreach ($mods as $mod) {
                    $arr[$cnt++]=array('secid'=>$mod->section,'modid'=>$mod->id,'modname'=>$mod->name,'modcontent'=>$mod->content);
                    //print_r($mod->name);
                }

            //returns the all activities associated to perticular section in a course
                function get_activities($sectionid,$arr)
                {
                    $cnt=0;
                    $sec_activity_array = array();
                    for($i=0;$i<count($arr);$i++) {
                        if($arr[$i]['secid']==$sectionid){
                            $sec_activity_array[$cnt] = array('modid'=>$arr[$i]['modid'],'modname'=>$arr[$i]['modname'],'modcontent'=>$arr[$i]['modcontent']);
                            $cnt++;
                        }

                    }
                    return $sec_activity_array;
                }

            // Get all course sections in a array
                function get_sections($sections)
                {   $cnt=0;
                    $sec_array = array();
                    foreach ($sections as $sec) {
                        $sec_array[$cnt++] = array('secid'=>$sec->id,'secname'=>$sec->name);
                    }
                    return $sec_array;
                }


                $activities=get_activities($secid,$arr);
                $html='';global $CFG;
                for($i=0;$i<count($activities);$i++) {
                    $html .= '<tr >
                                <td ><span class="mod' . $activities[$i]['modid'] . '">' . ($i + 1) . '</span></td>
                                <td ><span class="mod' . $activities[$i]['modid'] . '">' . $activities[$i]['modname'] . '</span></td>
                                <td ><span class="mod' . $activities[$i]['modid'] . '">' . $activities[$i]['modcontent'] . '</span></td>
                                <td >
                                <button class="showhide" id="show" value=' . $activities[$i]['modid'] . '>
                                <img  alt="start" src="'.$CFG->wwwroot.'/teacher/testcenter/images/start.png" width="16px"/></button>
                                <button class="showhide" id="hide" value=' . $activities[$i]['modid'] . '>
                                <img  alt="stop" src="'.$CFG->wwwroot.'/teacher/testcenter/images/stop.png" width="16px"/></button>
                                </td>
                            </tr>';
                }
                echo $html;
            }//end of section_activities() function
Пример #6
0
 /**
  * Get assign instance.
  *
  * NOTE: to be used from observers only.
  *
  * @throws \coding_exception
  * @return \assign
  */
 public function get_assign()
 {
     if ($this->is_restored()) {
         throw new \coding_exception('get_assign() is intended for event observers only');
     }
     if (!isset($this->assign)) {
         debugging('assign property should be initialised in each event', DEBUG_DEVELOPER);
         global $CFG;
         require_once $CFG->dirroot . '/mod/assign/locallib.php';
         $cm = get_coursemodule_from_id('assign', $this->contextinstanceid, 0, false, MUST_EXIST);
         $course = get_course($cm->course);
         $this->assign = new \assign($this->get_context(), $cm, $course);
     }
     return $this->assign;
 }
Пример #7
0
 function definition()
 {
     global $DB, $PAGE, $OUTPUT;
     $id = optional_param('id', 0, PARAM_INT);
     $a = optional_param('a', 0, PARAM_INT);
     if ($id) {
         if (!($cm = get_coursemodule_from_id('blended', $id))) {
             print_error("Course Module ID was incorrect");
         }
         if (!($course = get_course($cm->course))) {
             print_error("Course is misconfigured");
         }
         if (!($blended = $DB->get_record('blended', array('id' => $cm->instance)))) {
             print_error("Course module is incorrect");
         }
         if (!($context = context_course::instance($course->id))) {
             print_error("Context ID is incorrect");
         }
     } else {
         if (!($blended = $DB->get_record('blended', array('id' => $a)))) {
             print_error("Course module is incorrect");
         }
         if (!($course = $DB->get_record('course', array('id' => $blended->course)))) {
             print_error("Course is misconfigured");
         }
         if (!($cm = get_coursemodule_from_instance("blended", $blended->id, $course->id))) {
             print_error("Course Module ID was incorrect");
         }
         if (!($context = context_course::instance($course->id))) {
             print_error("Context ID is incorrect");
         }
     }
     $form =& $this->_form;
     $t = 0;
     $agrupamientos = array();
     $agrupamientos[$t] = 'Eliga';
     if ($groups = groups_get_all_groupings($course->id)) {
         foreach ($groups as $group) {
             $t++;
             $agrupamientos[$t] = $group->name;
         }
     }
     //Select Elements
     $form->addElement('select', 'grouping', get_string('select_grouping', 'blended'), $agrupamientos);
 }
 /**
  * Create a questionnaire activity.
  * @param array $record Will be changed in this function.
  * @param array $options
  * @return questionnaire
  */
 public function create_instance($record = array(), array $options = array())
 {
     if (is_array($record)) {
         $record = (object) $record;
     }
     $defaultquestionnairesettings = array('qtype' => 0, 'respondenttype' => 'fullname', 'resp_eligible' => 'all', 'resp_view' => 0, 'useopendate' => true, 'opendate' => 0, 'useclosedate' => true, 'closedate' => 0, 'resume' => 0, 'navigate' => 0, 'grade' => 0, 'sid' => 0, 'timemodified' => time(), 'completionsubmit' => 0, 'autonum' => 3, 'create' => 'new-0');
     foreach ($defaultquestionnairesettings as $name => $value) {
         if (!isset($record->{$name})) {
             $record->{$name} = $value;
         }
     }
     $instance = parent::create_instance($record, $options);
     $cm = get_coursemodule_from_instance('questionnaire', $instance->id);
     $course = get_course($cm->course);
     $questionnaire = new questionnaire(0, $instance, $course, $cm, false);
     $this->questionnaires[$instance->id] = $questionnaire;
     return $questionnaire;
 }
 public function execute()
 {
     global $CFG, $DB;
     require_once $CFG->dirroot . '/mod/ratingallocate/locallib.php';
     $site = get_site();
     // parse customdata passed
     $customdata = $this->get_custom_data();
     $userid = $customdata->userid;
     $ratingallocateid = $customdata->ratingallocateid;
     //get instance of ratingallocate
     $ratingallocate = $DB->get_record(this_db\ratingallocate::TABLE, array(this_db\ratingallocate::ID => $ratingallocateid), '*', MUST_EXIST);
     $courseid = $ratingallocate->course;
     $course = get_course($courseid);
     $cm = get_coursemodule_from_instance('ratingallocate', $ratingallocate->id, $courseid);
     $context = \context_module::instance($cm->id);
     $ratingallocateobj = new \ratingallocate($ratingallocate, $course, $cm, $context);
     $ratingallocateobj->notify_users_distribution($userid);
 }
Пример #10
0
/**
 * Run synchronization process
 *
 * @param progress_trace $trace
 * @param int|null $courseid or null for all courses
 * @return void
 */
function local_metagroups_sync(progress_trace $trace, $courseid = null)
{
    global $DB;
    if ($courseid !== null) {
        $courseids = array($courseid);
    } else {
        $courseids = local_metagroups_parent_courses();
    }
    foreach (array_unique($courseids) as $courseid) {
        $parent = get_course($courseid);
        // If parent course doesn't use groups, we can skip synchronization.
        if (groups_get_course_groupmode($parent) == NOGROUPS) {
            continue;
        }
        $trace->output($parent->fullname, 1);
        $children = local_metagroups_child_courses($parent->id);
        foreach ($children as $childid) {
            $child = get_course($childid);
            $trace->output($child->fullname, 2);
            $groups = groups_get_all_groups($child->id);
            foreach ($groups as $group) {
                if (!($metagroup = $DB->get_record('groups', array('courseid' => $parent->id, 'idnumber' => $group->id)))) {
                    $metagroup = new stdClass();
                    $metagroup->courseid = $parent->id;
                    $metagroup->idnumber = $group->id;
                    $metagroup->name = $group->name;
                    $metagroup->id = groups_create_group($metagroup, false, false);
                }
                $trace->output($metagroup->name, 3);
                $users = groups_get_members($group->id);
                foreach ($users as $user) {
                    groups_add_member($metagroup->id, $user->id, 'local_metagroups', $group->id);
                }
            }
        }
    }
}
 /**
  * Output the HTML grid of courses
  * @param  array 	$courses 	the list of enrolled courses
  * @return string          		HTML fragment
  */
 function course_grid($courses)
 {
     global $CFG;
     require_once $CFG->dirroot . '/blocks/my_course_progress/locallib.php';
     $html = sprintf('<div class="grid__container">');
     // LOOP THROUGH EACH COURSE AND GET THE OUTPUT
     foreach ($courses as $c) {
         $course = get_course($c->id);
         // OPEN GRID ITEM
         $html .= sprintf('<div class="grid__item">');
         // RENDER THE COURSE DETAILS
         $html .= $this->course($course);
         // IF COURSE HAS COMPLETION STATS, DO
         if (!!$course->enablecompletion) {
             // TODO: GET COMPLETION PERCENTAGE
             $percentage = block_my_course_progress_get_completion_percentage((int) $course->id);
             // RENDER THE COURSE PROGRESS
             $html .= $this->progress($percentage);
         }
         // CLOSE GRID ITEM
         $html .= sprintf('</div>');
     }
     return $html;
 }
Пример #12
0
              <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
              </tr>
            </thead>
            <tbody>
              <?php 
$i = 1;
while ($a = mysqli_fetch_array($papers)) {
    ?>
                <tr>
                  <td><?php 
    echo get_course($a['course']);
    ?>
</td>
                  <td><?php 
    echo get_branch($a['course'], $a['branch']);
    ?>
</td>
                  <td><?php 
    echo $a['semester'];
    ?>
</td>
                  <td><?php 
    echo $a['file_name'];
    ?>
</td>
                  <td>
Пример #13
0
 public function test_get_course()
 {
     global $DB, $PAGE, $SITE;
     $this->resetAfterTest();
     // First test course will be current course ($COURSE).
     $course1obj = $this->getDataGenerator()->create_course(array('shortname' => 'FROGS'));
     $PAGE->set_course($course1obj);
     // Second test course is not current course.
     $course2obj = $this->getDataGenerator()->create_course(array('shortname' => 'ZOMBIES'));
     // Check it does not make any queries when requesting the $COURSE/$SITE.
     $before = $DB->perf_get_queries();
     $result = get_course($course1obj->id);
     $this->assertEquals($before, $DB->perf_get_queries());
     $this->assertSame('FROGS', $result->shortname);
     $result = get_course($SITE->id);
     $this->assertEquals($before, $DB->perf_get_queries());
     // Check it makes 1 query to request other courses.
     $result = get_course($course2obj->id);
     $this->assertSame('ZOMBIES', $result->shortname);
     $this->assertEquals($before + 1, $DB->perf_get_queries());
 }
Пример #14
0
 /**
  * Self enrol the current user in the given course.
  *
  * @param int $courseid id of course
  * @param string $password enrolment key
  * @param int $instanceid instance id of self enrolment plugin
  * @return array of warnings and status result
  * @since Moodle 3.0
  * @throws moodle_exception
  */
 public static function enrol_user($courseid, $password = '', $instanceid = 0)
 {
     global $CFG;
     require_once $CFG->libdir . '/enrollib.php';
     $params = self::validate_parameters(self::enrol_user_parameters(), array('courseid' => $courseid, 'password' => $password, 'instanceid' => $instanceid));
     $warnings = array();
     $course = get_course($params['courseid']);
     $context = context_course::instance($course->id);
     self::validate_context(context_system::instance());
     if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $context)) {
         throw new moodle_exception('coursehidden');
     }
     // Retrieve the self enrolment plugin.
     $enrol = enrol_get_plugin('self');
     if (empty($enrol)) {
         throw new moodle_exception('canntenrol', 'enrol_self');
     }
     // We can expect multiple self-enrolment instances.
     $instances = array();
     $enrolinstances = enrol_get_instances($course->id, true);
     foreach ($enrolinstances as $courseenrolinstance) {
         if ($courseenrolinstance->enrol == "self") {
             // Instance specified.
             if (!empty($params['instanceid'])) {
                 if ($courseenrolinstance->id == $params['instanceid']) {
                     $instances[] = $courseenrolinstance;
                     break;
                 }
             } else {
                 $instances[] = $courseenrolinstance;
             }
         }
     }
     if (empty($instances)) {
         throw new moodle_exception('canntenrol', 'enrol_self');
     }
     // Try to enrol the user in the instance/s.
     $enrolled = false;
     foreach ($instances as $instance) {
         $enrolstatus = $enrol->can_self_enrol($instance);
         if ($enrolstatus === true) {
             if ($instance->password and $params['password'] !== $instance->password) {
                 // Check if we are using group enrolment keys.
                 if ($instance->customint1) {
                     require_once $CFG->dirroot . "/enrol/self/locallib.php";
                     if (!enrol_self_check_group_enrolment_key($course->id, $params['password'])) {
                         $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '2', 'message' => get_string('passwordinvalid', 'enrol_self'));
                         continue;
                     }
                 } else {
                     if ($enrol->get_config('showhint')) {
                         $hint = core_text::substr($instance->password, 0, 1);
                         $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '3', 'message' => s(get_string('passwordinvalidhint', 'enrol_self', $hint)));
                         continue;
                     } else {
                         $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '4', 'message' => get_string('passwordinvalid', 'enrol_self'));
                         continue;
                     }
                 }
             }
             // Do the enrolment.
             $data = array('enrolpassword' => $params['password']);
             $enrol->enrol_self($instance, (object) $data);
             $enrolled = true;
             break;
         } else {
             $warnings[] = array('item' => 'instance', 'itemid' => $instance->id, 'warningcode' => '1', 'message' => $enrolstatus);
         }
     }
     $result = array();
     $result['status'] = $enrolled;
     $result['warnings'] = $warnings;
     return $result;
 }
Пример #15
0
/**
 * Get all discussions in a forum
 *
 * @global object
 * @global object
 * @global object
 * @uses CONTEXT_MODULE
 * @uses VISIBLEGROUPS
 * @param object $cm
 * @param string $forumsort
 * @param bool $fullpost
 * @param int $unused
 * @param int $limit
 * @param bool $userlastmodified
 * @param int $page
 * @param int $perpage
 * @param int $groupid if groups enabled, get discussions for this group overriding the current group.
 *                     Use FORUM_POSTS_ALL_USER_GROUPS for all the user groups
 * @param int $updatedsince retrieve only discussions updated since the given time
 * @return array
 */
function forum_get_discussions($cm, $forumsort = "", $fullpost = true, $unused = -1, $limit = -1, $userlastmodified = false, $page = -1, $perpage = 0, $groupid = -1, $updatedsince = 0)
{
    global $CFG, $DB, $USER;
    $timelimit = '';
    $now = round(time(), -2);
    $params = array($cm->instance);
    $modcontext = context_module::instance($cm->id);
    if (!has_capability('mod/forum:viewdiscussion', $modcontext)) {
        /// User must have perms to view discussions
        return array();
    }
    if (!empty($CFG->forum_enabletimedposts)) {
        /// Users must fulfill timed posts
        if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
            $timelimit = " AND ((d.timestart <= ? AND (d.timeend = 0 OR d.timeend > ?))";
            $params[] = $now;
            $params[] = $now;
            if (isloggedin()) {
                $timelimit .= " OR d.userid = ?";
                $params[] = $USER->id;
            }
            $timelimit .= ")";
        }
    }
    if ($limit > 0) {
        $limitfrom = 0;
        $limitnum = $limit;
    } else {
        if ($page != -1) {
            $limitfrom = $page * $perpage;
            $limitnum = $perpage;
        } else {
            $limitfrom = 0;
            $limitnum = 0;
        }
    }
    $groupmode = groups_get_activity_groupmode($cm);
    if ($groupmode) {
        if (empty($modcontext)) {
            $modcontext = context_module::instance($cm->id);
        }
        // Special case, we received a groupid to override currentgroup.
        if ($groupid > 0) {
            $course = get_course($cm->course);
            if (!groups_group_visible($groupid, $course, $cm)) {
                // User doesn't belong to this group, return nothing.
                return array();
            }
            $currentgroup = $groupid;
        } else {
            if ($groupid === -1) {
                $currentgroup = groups_get_activity_group($cm);
            } else {
                // Get discussions for all groups current user can see.
                $currentgroup = null;
            }
        }
        if ($groupmode == VISIBLEGROUPS or has_capability('moodle/site:accessallgroups', $modcontext)) {
            if ($currentgroup) {
                $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
                $params[] = $currentgroup;
            } else {
                $groupselect = "";
            }
        } else {
            // Separate groups.
            // Get discussions for all groups current user can see.
            if ($currentgroup === null) {
                $mygroups = array_keys(groups_get_all_groups($cm->course, $USER->id, $cm->groupingid, 'g.id'));
                if (empty($mygroups)) {
                    $groupselect = "AND d.groupid = -1";
                } else {
                    list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($mygroups);
                    $groupselect = "AND (d.groupid = -1 OR d.groupid {$insqlgroups})";
                    $params = array_merge($params, $inparamsgroups);
                }
            } else {
                if ($currentgroup) {
                    $groupselect = "AND (d.groupid = ? OR d.groupid = -1)";
                    $params[] = $currentgroup;
                } else {
                    $groupselect = "AND d.groupid = -1";
                }
            }
        }
    } else {
        $groupselect = "";
    }
    if (empty($forumsort)) {
        $forumsort = forum_get_default_sort_order();
    }
    if (empty($fullpost)) {
        $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
    } else {
        $postdata = "p.*";
    }
    if (empty($userlastmodified)) {
        // We don't need to know this
        $umfields = "";
        $umtable = "";
    } else {
        $umfields = ', ' . get_all_user_name_fields(true, 'um', null, 'um') . ', um.email AS umemail, um.picture AS umpicture,
                        um.imagealt AS umimagealt';
        $umtable = " LEFT JOIN {user} um ON (d.usermodified = um.id)";
    }
    $updatedsincesql = '';
    if (!empty($updatedsince)) {
        $updatedsincesql = 'AND d.timemodified > ?';
        $params[] = $updatedsince;
    }
    $allnames = get_all_user_name_fields(true, 'u');
    $sql = "SELECT {$postdata}, d.name, d.timemodified, d.usermodified, d.groupid, d.timestart, d.timeend, d.pinned, {$allnames},\n                   u.email, u.picture, u.imagealt {$umfields}\n              FROM {forum_discussions} d\n                   JOIN {forum_posts} p ON p.discussion = d.id\n                   JOIN {user} u ON p.userid = u.id\n                   {$umtable}\n             WHERE d.forum = ? AND p.parent = 0\n                   {$timelimit} {$groupselect} {$updatedsincesql}\n          ORDER BY {$forumsort}, d.id DESC";
    return $DB->get_records_sql($sql, $params, $limitfrom, $limitnum);
}
Пример #16
0
 /**
  * Used to notify the completion system (if necessary) that a user's grade
  * has changed, and clear up a possible score cache.
  *
  * @param bool $deleted True if grade was actually deleted
  */
 protected function notify_changed($deleted)
 {
     global $CFG;
     // Condition code may cache the grades for conditional availability of
     // modules or sections. (This code should use a hook for communication
     // with plugin, but hooks are not implemented at time of writing.)
     if (!empty($CFG->enableavailability) && class_exists('\\availability_grade\\callbacks')) {
         \availability_grade\callbacks::grade_changed($this->userid);
     }
     require_once $CFG->libdir . '/completionlib.php';
     // Bail out immediately if completion is not enabled for site (saves loading
     // grade item & requiring the restore stuff).
     if (!completion_info::is_enabled_for_site()) {
         return;
     }
     // Ignore during restore, as completion data will be updated anyway and
     // doing it now will result in incorrect dates (it will say they got the
     // grade completion now, instead of the correct time).
     if (class_exists('restore_controller', false) && restore_controller::is_executing()) {
         return;
     }
     // Load information about grade item
     $this->load_grade_item();
     // Only course-modules have completion data
     if ($this->grade_item->itemtype != 'mod') {
         return;
     }
     // Use $COURSE if available otherwise get it via item fields
     $course = get_course($this->grade_item->courseid, false);
     // Bail out if completion is not enabled for course
     $completion = new completion_info($course);
     if (!$completion->is_enabled()) {
         return;
     }
     // Get course-module
     $cm = get_coursemodule_from_instance($this->grade_item->itemmodule, $this->grade_item->iteminstance, $this->grade_item->courseid);
     // If the course-module doesn't exist, display a warning...
     if (!$cm) {
         // ...unless the grade is being deleted in which case it's likely
         // that the course-module was just deleted too, so that's okay.
         if (!$deleted) {
             debugging("Couldn't find course-module for module '" . $this->grade_item->itemmodule . "', instance '" . $this->grade_item->iteminstance . "', course '" . $this->grade_item->courseid . "'");
         }
         return;
     }
     // Pass information on to completion system
     $completion->inform_grade_changed($cm, $this->grade_item, $this, $deleted);
 }
Пример #17
0
/**
 * Get current course cache
 *
 * @param array $coursecache list of course cache
 * @param int $courseid id of the course
 * @return stdClass $coursecache[$courseid] return the specific course cache
 */
function calendar_get_course_cached(&$coursecache, $courseid)
{
    if (!isset($coursecache[$courseid])) {
        $coursecache[$courseid] = get_course($courseid);
    }
    return $coursecache[$courseid];
}
 public function test_coursebyshortname()
 {
     $expected = get_course($this->courses[0]->id);
     $actual = $this->courseservice->coursebyshortname($this->courses[0]->shortname);
     $this->assertEquals($expected, $actual);
 }
Пример #19
0
 /**
  * Returns a record from course database table plus additional fields
  * that course format defines
  *
  * @return stdClass
  */
 public function get_course()
 {
     global $DB;
     if (!$this->courseid) {
         return null;
     }
     if ($this->course === false) {
         $this->course = get_course($this->courseid);
         $options = $this->get_format_options();
         $dbcoursecolumns = null;
         foreach ($options as $optionname => $optionvalue) {
             if (isset($this->course->{$optionname})) {
                 // Course format options must not have the same names as existing columns in db table "course".
                 if (!isset($dbcoursecolumns)) {
                     $dbcoursecolumns = $DB->get_columns('course');
                 }
                 if (isset($dbcoursecolumns[$optionname])) {
                     debugging('The option name ' . $optionname . ' in course format ' . $this->format . ' is invalid because the field with the same name exists in {course} table', DEBUG_DEVELOPER);
                     continue;
                 }
             }
             $this->course->{$optionname} = $optionvalue;
         }
     }
     return $this->course;
 }
Пример #20
0
 *
 * You can have a rather longer description of the file as well,
 * if you like, and it can span multiple lines.
 *
 * @package    mod_zoom
 * @copyright  2015 UC Regents
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */
require_once dirname(dirname(dirname(__FILE__))) . '/config.php';
require_once $CFG->libdir . '/gradelib.php';
require_once $CFG->libdir . '/moodlelib.php';
$id = required_param('id', PARAM_INT);
// Course_module ID.
if ($id) {
    $cm = get_coursemodule_from_id('zoom', $id, 0, false, MUST_EXIST);
    $course = get_course($cm->course);
    $zoom = $DB->get_record('zoom', array('id' => $cm->instance), '*', MUST_EXIST);
} else {
    error('You must specify a course_module ID');
}
require_login($course, true, $cm);
$context = context_module::instance($cm->id);
$PAGE->set_context($context);
require_capability('mod/zoom:view', $context);
// Check whether user had a grade. If no, then assign full credits to him or her.
$gradelist = grade_get_grades($course->id, 'mod', 'zoom', $cm->instance, $USER->id);
// Assign full credits for user who has no grade yet, if this meeting is gradable
// (i.e. the grade type is not "None").
if (!empty($gradelist->items) && empty($gradelist->items[0]->grades[$USER->id]->grade)) {
    $grademax = $gradelist->items[0]->grademax;
    $grades = array('rawgrade' => $grademax, 'userid' => $USER->id, 'usermodified' => $USER->id, 'dategraded' => '', 'feedbackformat' => '', 'feedback' => '');
Пример #21
0
 /**
  * Returns a list of forum discussions as well as a summary of the discussion
  * in a provided list of forums.
  *
  * @param array $forumids the forum ids
  * @param int $limitfrom limit from SQL data
  * @param int $limitnum limit number SQL data
  *
  * @return array the forum discussion details
  * @since Moodle 2.5
  */
 public static function get_forum_discussions($forumids, $limitfrom = 0, $limitnum = 0)
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . "/mod/forum/lib.php";
     // Validate the parameter.
     $params = self::validate_parameters(self::get_forum_discussions_parameters(), array('forumids' => $forumids, 'limitfrom' => $limitfrom, 'limitnum' => $limitnum));
     $forumids = $params['forumids'];
     $limitfrom = $params['limitfrom'];
     $limitnum = $params['limitnum'];
     // Array to store the forum discussions to return.
     $arrdiscussions = array();
     // Keep track of the users we have looked up in the DB.
     $arrusers = array();
     // Loop through them.
     foreach ($forumids as $id) {
         // Get the forum object.
         $forum = $DB->get_record('forum', array('id' => $id), '*', MUST_EXIST);
         $course = get_course($forum->course);
         $modinfo = get_fast_modinfo($course);
         $forums = $modinfo->get_instances_of('forum');
         $cm = $forums[$forum->id];
         // Get the module context.
         $modcontext = context_module::instance($cm->id);
         // Validate the context.
         self::validate_context($modcontext);
         require_capability('mod/forum:viewdiscussion', $modcontext);
         // Get the discussions for this forum.
         $params = array();
         $groupselect = "";
         $groupmode = groups_get_activity_groupmode($cm, $course);
         if ($groupmode and $groupmode != VISIBLEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
             // Get all the discussions from all the groups this user belongs to.
             $usergroups = groups_get_user_groups($course->id);
             if (!empty($usergroups['0'])) {
                 list($sql, $params) = $DB->get_in_or_equal($usergroups['0']);
                 $groupselect = "AND (groupid {$sql} OR groupid = -1)";
             }
         }
         array_unshift($params, $id);
         $select = "forum = ? {$groupselect}";
         if ($discussions = $DB->get_records_select('forum_discussions', $select, $params, 'timemodified DESC', '*', $limitfrom, $limitnum)) {
             // Check if they can view full names.
             $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
             // Get the unreads array, this takes a forum id and returns data for all discussions.
             $unreads = array();
             if ($cantrack = forum_tp_can_track_forums($forum)) {
                 if ($forumtracked = forum_tp_is_tracked($forum)) {
                     $unreads = forum_get_discussions_unread($cm);
                 }
             }
             // The forum function returns the replies for all the discussions in a given forum.
             $replies = forum_count_discussion_replies($id);
             foreach ($discussions as $discussion) {
                 // This function checks capabilities, timed discussions, groups and qanda forums posting.
                 if (!forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
                     continue;
                 }
                 $usernamefields = user_picture::fields();
                 // If we don't have the users details then perform DB call.
                 if (empty($arrusers[$discussion->userid])) {
                     $arrusers[$discussion->userid] = $DB->get_record('user', array('id' => $discussion->userid), $usernamefields, MUST_EXIST);
                 }
                 // Get the subject.
                 $subject = $DB->get_field('forum_posts', 'subject', array('id' => $discussion->firstpost), MUST_EXIST);
                 // Create object to return.
                 $return = new stdClass();
                 $return->id = (int) $discussion->id;
                 $return->course = $discussion->course;
                 $return->forum = $discussion->forum;
                 $return->name = $discussion->name;
                 $return->userid = $discussion->userid;
                 $return->groupid = $discussion->groupid;
                 $return->assessed = $discussion->assessed;
                 $return->timemodified = (int) $discussion->timemodified;
                 $return->usermodified = $discussion->usermodified;
                 $return->timestart = $discussion->timestart;
                 $return->timeend = $discussion->timeend;
                 $return->firstpost = (int) $discussion->firstpost;
                 $return->firstuserfullname = fullname($arrusers[$discussion->userid], $canviewfullname);
                 $return->firstuserimagealt = $arrusers[$discussion->userid]->imagealt;
                 $return->firstuserpicture = $arrusers[$discussion->userid]->picture;
                 $return->firstuseremail = $arrusers[$discussion->userid]->email;
                 $return->subject = $subject;
                 $return->numunread = '';
                 if ($cantrack && $forumtracked) {
                     if (isset($unreads[$discussion->id])) {
                         $return->numunread = (int) $unreads[$discussion->id];
                     }
                 }
                 // Check if there are any replies to this discussion.
                 if (!empty($replies[$discussion->id])) {
                     $return->numreplies = (int) $replies[$discussion->id]->replies;
                     $return->lastpost = (int) $replies[$discussion->id]->lastpostid;
                 } else {
                     // No replies, so the last post will be the first post.
                     $return->numreplies = 0;
                     $return->lastpost = (int) $discussion->firstpost;
                 }
                 // Get the last post as well as the user who made it.
                 $lastpost = $DB->get_record('forum_posts', array('id' => $return->lastpost), '*', MUST_EXIST);
                 if (empty($arrusers[$lastpost->userid])) {
                     $arrusers[$lastpost->userid] = $DB->get_record('user', array('id' => $lastpost->userid), $usernamefields, MUST_EXIST);
                 }
                 $return->lastuserid = $lastpost->userid;
                 $return->lastuserfullname = fullname($arrusers[$lastpost->userid], $canviewfullname);
                 $return->lastuserimagealt = $arrusers[$lastpost->userid]->imagealt;
                 $return->lastuserpicture = $arrusers[$lastpost->userid]->picture;
                 $return->lastuseremail = $arrusers[$lastpost->userid]->email;
                 // Add the discussion statistics to the array to return.
                 $arrdiscussions[$return->id] = (array) $return;
             }
         }
     }
     return $arrdiscussions;
 }
Пример #22
0
 /**
  * Returns an array of courses the user is enrolled, and for each course all of the assignments that the user can
  * view within that course.
  *
  * @param array $courseids An optional array of course ids. If provided only assignments within the given course
  * will be returned. If the user is not enrolled in or can't view a given course a warning will be generated and returned.
  * @param array $capabilities An array of additional capability checks you wish to be made on the course context.
  * @param bool $includenotenrolledcourses Wheter to return courses that the user can see even if is not enroled in.
  * This requires the parameter $courseids to not be empty.
  * @return An array of courses and warnings.
  * @since  Moodle 2.4
  */
 public static function get_assignments($courseids = array(), $capabilities = array(), $includenotenrolledcourses = false)
 {
     global $USER, $DB, $CFG;
     $params = self::validate_parameters(self::get_assignments_parameters(), array('courseids' => $courseids, 'capabilities' => $capabilities, 'includenotenrolledcourses' => $includenotenrolledcourses));
     $warnings = array();
     $courses = array();
     $fields = 'sortorder,shortname,fullname,timemodified';
     // If the courseids list is empty, we return only the courses where the user is enrolled in.
     if (empty($params['courseids'])) {
         $courses = enrol_get_users_courses($USER->id, true, $fields);
         $courseids = array_keys($courses);
     } else {
         if ($includenotenrolledcourses) {
             // In this case, we don't have to check here for enrolmnents. Maybe the user can see the course even if is not enrolled.
             $courseids = $params['courseids'];
         } else {
             // We need to check for enrolments.
             $mycourses = enrol_get_users_courses($USER->id, true, $fields);
             $mycourseids = array_keys($mycourses);
             foreach ($params['courseids'] as $courseid) {
                 if (!in_array($courseid, $mycourseids)) {
                     unset($courses[$courseid]);
                     $warnings[] = array('item' => 'course', 'itemid' => $courseid, 'warningcode' => '2', 'message' => 'User is not enrolled or does not have requested capability');
                 } else {
                     $courses[$courseid] = $mycourses[$courseid];
                 }
             }
             $courseids = array_keys($courses);
         }
     }
     foreach ($courseids as $cid) {
         try {
             $context = context_course::instance($cid);
             self::validate_context($context);
             // Check if this course was already loaded (by enrol_get_users_courses).
             if (!isset($courses[$cid])) {
                 $courses[$cid] = get_course($cid);
             }
             $courses[$cid]->contextid = $context->id;
         } catch (Exception $e) {
             unset($courses[$cid]);
             $warnings[] = array('item' => 'course', 'itemid' => $cid, 'warningcode' => '1', 'message' => 'No access rights in course context ' . $e->getMessage());
             continue;
         }
         if (count($params['capabilities']) > 0 && !has_all_capabilities($params['capabilities'], $context)) {
             unset($courses[$cid]);
         }
     }
     $extrafields = 'm.id as assignmentid, ' . 'm.course, ' . 'm.nosubmissions, ' . 'm.submissiondrafts, ' . 'm.sendnotifications, ' . 'm.sendlatenotifications, ' . 'm.sendstudentnotifications, ' . 'm.duedate, ' . 'm.allowsubmissionsfromdate, ' . 'm.grade, ' . 'm.timemodified, ' . 'm.completionsubmit, ' . 'm.cutoffdate, ' . 'm.teamsubmission, ' . 'm.requireallteammemberssubmit, ' . 'm.teamsubmissiongroupingid, ' . 'm.blindmarking, ' . 'm.revealidentities, ' . 'm.attemptreopenmethod, ' . 'm.maxattempts, ' . 'm.markingworkflow, ' . 'm.markingallocation, ' . 'm.requiresubmissionstatement, ' . 'm.preventsubmissionnotingroup, ' . 'm.intro, ' . 'm.introformat';
     $coursearray = array();
     foreach ($courses as $id => $course) {
         $assignmentarray = array();
         // Get a list of assignments for the course.
         if ($modules = get_coursemodules_in_course('assign', $courses[$id]->id, $extrafields)) {
             foreach ($modules as $module) {
                 $context = context_module::instance($module->id);
                 try {
                     self::validate_context($context);
                     require_capability('mod/assign:view', $context);
                 } catch (Exception $e) {
                     $warnings[] = array('item' => 'module', 'itemid' => $module->id, 'warningcode' => '1', 'message' => 'No access rights in module context');
                     continue;
                 }
                 $assign = new assign($context, null, null);
                 // Get configurations for only enabled plugins.
                 $plugins = $assign->get_submission_plugins();
                 $plugins = array_merge($plugins, $assign->get_feedback_plugins());
                 $configarray = array();
                 foreach ($plugins as $plugin) {
                     if ($plugin->is_enabled() && $plugin->is_visible()) {
                         $configrecords = $plugin->get_config_for_external();
                         foreach ($configrecords as $name => $value) {
                             $configarray[] = array('plugin' => $plugin->get_type(), 'subtype' => $plugin->get_subtype(), 'name' => $name, 'value' => $value);
                         }
                     }
                 }
                 $assignment = array('id' => $module->assignmentid, 'cmid' => $module->id, 'course' => $module->course, 'name' => $module->name, 'nosubmissions' => $module->nosubmissions, 'submissiondrafts' => $module->submissiondrafts, 'sendnotifications' => $module->sendnotifications, 'sendlatenotifications' => $module->sendlatenotifications, 'sendstudentnotifications' => $module->sendstudentnotifications, 'duedate' => $module->duedate, 'allowsubmissionsfromdate' => $module->allowsubmissionsfromdate, 'grade' => $module->grade, 'timemodified' => $module->timemodified, 'completionsubmit' => $module->completionsubmit, 'cutoffdate' => $module->cutoffdate, 'teamsubmission' => $module->teamsubmission, 'requireallteammemberssubmit' => $module->requireallteammemberssubmit, 'teamsubmissiongroupingid' => $module->teamsubmissiongroupingid, 'blindmarking' => $module->blindmarking, 'revealidentities' => $module->revealidentities, 'attemptreopenmethod' => $module->attemptreopenmethod, 'maxattempts' => $module->maxattempts, 'markingworkflow' => $module->markingworkflow, 'markingallocation' => $module->markingallocation, 'requiresubmissionstatement' => $module->requiresubmissionstatement, 'preventsubmissionnotingroup' => $module->preventsubmissionnotingroup, 'configs' => $configarray);
                 // Return or not intro and file attachments depending on the plugin settings.
                 if ($assign->show_intro()) {
                     list($assignment['intro'], $assignment['introformat']) = external_format_text($module->intro, $module->introformat, $context->id, 'mod_assign', 'intro', null);
                     $assignment['introfiles'] = external_util::get_area_files($context->id, 'mod_assign', 'intro', false, false);
                     $assignment['introattachments'] = external_util::get_area_files($context->id, 'mod_assign', ASSIGN_INTROATTACHMENT_FILEAREA, 0);
                 }
                 if ($module->requiresubmissionstatement) {
                     // Submission statement is required, return the submission statement value.
                     $adminconfig = get_config('assign');
                     list($assignment['submissionstatement'], $assignment['submissionstatementformat']) = external_format_text($adminconfig->submissionstatement, FORMAT_MOODLE, $context->id, 'mod_assign', '', 0);
                 }
                 $assignmentarray[] = $assignment;
             }
         }
         $coursearray[] = array('id' => $courses[$id]->id, 'fullname' => external_format_string($courses[$id]->fullname, $course->contextid), 'shortname' => external_format_string($courses[$id]->shortname, $course->contextid), 'timemodified' => $courses[$id]->timemodified, 'assignments' => $assignmentarray);
     }
     $result = array('courses' => $coursearray, 'warnings' => $warnings);
     return $result;
 }
 /**
  * Helper for test_auto_openclose_courses() and test_enrol_uaims_cron().
  * @param $courseid
  * @param $visible Assert that course visibility matches this value
  * @param null $lastopenedshouldbezero true, we assert for zero values; false, we assert not non-null values; null, we don't
  * assert
  * @param null $lastclosedshouldbezero true, we assert for zero values; false, we assert not non-null values; null, we don't
  * assert
  */
 public function check_courseid_vis_opened_closed($courseid, $visible, $lastopenedshouldbezero = null, $lastclosedshouldbezero = null)
 {
     global $DB;
     $course = get_course($courseid);
     $ecmrecord = $DB->get_record('eclass_course_management', array('courseid' => $courseid));
     $this->assertEquals($visible, $course->visible);
     if (isset($lastopenedshouldbezero)) {
         if ($lastopenedshouldbezero) {
             $this->assertEquals(0, $ecmrecord->lastopened);
         } else {
             $this->assertNotEquals(0, $ecmrecord->lastopened);
         }
     }
     if (isset($lastclosedshouldbezero)) {
         if ($lastclosedshouldbezero) {
             $this->assertEquals(0, $ecmrecord->lastclosed);
         } else {
             $this->assertNotEquals(0, $ecmrecord->lastclosed);
         }
     }
 }
Пример #24
0
 /**
  * Performs the synchronisation of grades.
  *
  * @return bool|void
  */
 public function execute()
 {
     global $DB, $CFG;
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuth.php';
     require_once $CFG->dirroot . '/enrol/lti/ims-blti/OAuthBody.php';
     require_once $CFG->dirroot . '/lib/completionlib.php';
     require_once $CFG->libdir . '/gradelib.php';
     require_once $CFG->dirroot . '/grade/querylib.php';
     // Check if the authentication plugin is disabled.
     if (!is_enabled_auth('lti')) {
         mtrace('Skipping task - ' . get_string('pluginnotenabled', 'auth', get_string('pluginname', 'auth_lti')));
         return true;
     }
     // Check if the enrolment plugin is disabled - isn't really necessary as the task should not run if
     // the plugin is disabled, but there is no harm in making sure core hasn't done something wrong.
     if (!enrol_is_enabled('lti')) {
         mtrace('Skipping task - ' . get_string('enrolisdisabled', 'enrol_lti'));
         return true;
     }
     // Get all the enabled tools.
     if ($tools = \enrol_lti\helper::get_lti_tools(array('status' => ENROL_INSTANCE_ENABLED, 'gradesync' => 1))) {
         foreach ($tools as $tool) {
             mtrace("Starting - Grade sync for shared tool '{$tool->id}' for the course '{$tool->courseid}'.");
             // Variables to keep track of information to display later.
             $usercount = 0;
             $sendcount = 0;
             // We check for all the users - users can access the same tool from different consumers.
             if ($ltiusers = $DB->get_records('enrol_lti_users', array('toolid' => $tool->id), 'lastaccess DESC')) {
                 $completion = new \completion_info(get_course($tool->courseid));
                 foreach ($ltiusers as $ltiuser) {
                     $mtracecontent = "for the user '{$ltiuser->userid}' in the tool '{$tool->id}' for the course " . "'{$tool->courseid}'";
                     $usercount = $usercount + 1;
                     // Check if we do not have a serviceurl - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->serviceurl)) {
                         mtrace("Skipping - Empty serviceurl {$mtracecontent}.");
                         continue;
                     }
                     // Check if we do not have a sourceid - this can happen if the sync process has an unexpected error.
                     if (empty($ltiuser->sourceid)) {
                         mtrace("Skipping - Empty sourceid {$mtracecontent}.");
                         continue;
                     }
                     // Need a valid context to continue.
                     if (!($context = \context::instance_by_id($tool->contextid))) {
                         mtrace("Failed - Invalid contextid '{$tool->contextid}' for the tool '{$tool->id}'.");
                         continue;
                     }
                     // Ok, let's get the grade.
                     $grade = false;
                     if ($context->contextlevel == CONTEXT_COURSE) {
                         // Check if the user did not completed the course when it was required.
                         if ($tool->gradesynccompletion && !$completion->is_course_complete($ltiuser->userid)) {
                             mtrace("Skipping - Course not completed {$mtracecontent}.");
                             continue;
                         }
                         // Get the grade.
                         if ($grade = grade_get_course_grade($ltiuser->userid, $tool->courseid)) {
                             $grademax = floatval($grade->item->grademax);
                             $grade = $grade->grade;
                         }
                     } else {
                         if ($context->contextlevel == CONTEXT_MODULE) {
                             $cm = get_coursemodule_from_id(false, $context->instanceid, 0, false, MUST_EXIST);
                             if ($tool->gradesynccompletion) {
                                 $data = $completion->get_data($cm, false, $ltiuser->userid);
                                 if ($data->completionstate != COMPLETION_COMPLETE_PASS && $data->completionstate != COMPLETION_COMPLETE) {
                                     mtrace("Skipping - Activity not completed {$mtracecontent}.");
                                     continue;
                                 }
                             }
                             $grades = grade_get_grades($cm->course, 'mod', $cm->modname, $cm->instance, $ltiuser->userid);
                             if (!empty($grades->items[0]->grades)) {
                                 $grade = reset($grades->items[0]->grades);
                                 if (!empty($grade->item)) {
                                     $grademax = floatval($grade->item->grademax);
                                 } else {
                                     $grademax = floatval($grades->items[0]->grademax);
                                 }
                                 $grade = $grade->grade;
                             }
                         }
                     }
                     if ($grade === false || $grade === null || strlen($grade) < 1) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // No need to be dividing by zero.
                     if (empty($grademax)) {
                         mtrace("Skipping - Invalid grade {$mtracecontent}.");
                         continue;
                     }
                     // This can happen if the sync process has an unexpected error.
                     if ($grade == $ltiuser->lastgrade) {
                         mtrace("Not sent - The grade {$mtracecontent} was not sent as the grades are the same.");
                         continue;
                     }
                     // Sync with the external system.
                     $floatgrade = $grade / $grademax;
                     $body = \enrol_lti\helper::create_service_body($ltiuser->sourceid, $floatgrade);
                     try {
                         $response = sendOAuthBodyPOST('POST', $ltiuser->serviceurl, $ltiuser->consumerkey, $ltiuser->consumersecret, 'application/xml', $body);
                     } catch (\Exception $e) {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                         mtrace($e->getMessage());
                         continue;
                     }
                     if (strpos(strtolower($response), 'success') !== false) {
                         $DB->set_field('enrol_lti_users', 'lastgrade', intval($grade), array('id' => $ltiuser->id));
                         mtrace("Success - The grade '{$floatgrade}' {$mtracecontent} was sent.");
                         $sendcount = $sendcount + 1;
                     } else {
                         mtrace("Failed - The grade '{$floatgrade}' {$mtracecontent} failed to send.");
                     }
                 }
             }
             mtrace("Completed - Synced grades for tool '{$tool->id}' in the course '{$tool->courseid}'. " . "Processed {$usercount} users; sent {$sendcount} grades.");
             mtrace("");
         }
     }
 }
 public function top_promoted_courses()
 {
     global $CFG, $OUTPUT, $DB, $PAGE;
     $featuredcontent = '';
     /* Get Featured courses id from DB */
     $featuredids = theme_pioneer_get_setting('toppromotedcourses');
     $rcourseids = !empty($featuredids) ? explode(",", $featuredids, 10) : array();
     if (empty($rcourseids)) {
         return false;
     }
     $hcourseids = theme_pioneer_hidden_courses_ids();
     if (!empty($hcourseids)) {
         foreach ($rcourseids as $key => $val) {
             if (in_array($val, $hcourseids)) {
                 unset($rcourseids[$key]);
             }
         }
     }
     foreach ($rcourseids as $key => $val) {
         $ccourse = $DB->get_record('course', array('id' => $val));
         if (empty($ccourse)) {
             unset($rcourseids[$key]);
             continue;
         }
     }
     if (empty($rcourseids)) {
         return false;
     }
     $fcourseids = array_chunk($rcourseids, 10);
     $totalfcourse = count($fcourseids);
     $promotedtitle = theme_pioneer_get_setting('toppromotedtitle', 'format_text');
     $promotedtitle = theme_pioneer_lang($promotedtitle);
     $closelisting = theme_pioneer_get_setting('topclosefeatured', 'format_text');
     $topshowfeatured = theme_pioneer_get_setting('topshowfeatured', 'format_text');
     $featuredheader = '<div class="custom-courses-list" id="topPromoted-Courses">
                           <div class="container-fluid">
                          <div class="promoted_courses" data-crow="' . $totalfcourse . '">';
     $featuredfooter = ' </div>
                         </div>
                         </div>';
     if (!empty($fcourseids)) {
         echo '<div id="featured-listing" class="collapse out">';
         echo '<div data-toggle="collapse" data-target="#featured-listing" class="btn-link"style="text-align:center;">' . $closelisting . '</div>';
         foreach ($fcourseids as $courseids) {
             $rowcontent = '<div><div class="row-fluid topcarousel">';
             foreach ($courseids as $courseid) {
                 $course = get_course($courseid);
                 $no = get_config('theme_pioneer', 'toppatternselect');
                 $nimgp = empty($no) || $no == "default" ? 'no-image' : 'cs0' . $no . '/no-image';
                 $noimgurl = $OUTPUT->pix_url($nimgp, 'theme');
                 $courseurl = new moodle_url('/course/view.php', array('id' => $courseid));
                 if ($course instanceof stdClass) {
                     require_once $CFG->libdir . '/coursecatlib.php';
                     $course = new course_in_list($course);
                 }
                 $imgurl = '';
                 $summary = theme_pioneer_strip_html_tags($course->summary);
                 $summary = theme_pioneer_course_trim_char($summary, 125);
                 $trimtitle = theme_pioneer_course_trim_char($course->fullname, 90);
                 $context = context_course::instance($course->id);
                 $nostudents = count_role_users(5, $context);
                 foreach ($course->get_course_overviewfiles() as $file) {
                     $isimage = $file->is_valid_image();
                     $imgurl = file_encode_url("{$CFG->wwwroot}/pluginfile.php", '/' . $file->get_contextid() . '/' . $file->get_component() . '/' . $file->get_filearea() . $file->get_filepath() . $file->get_filename(), !$isimage);
                     if (!$isimage) {
                         $imgurl = $noimgurl;
                     }
                 }
                 if (empty($imgurl)) {
                     $imgurl = $PAGE->theme->setting_file_url('headerbackgroundimage', 'headerbackgroundimage', true);
                     if (!$imgurl) {
                         $imgurl = $noimgurl;
                     }
                 }
                 $listitems = '
                 <div class="row-fluid">
                 <div class="span3">
                 <img src="' . $imgurl . '" width="100%" height="75px" alt="' . $course->fullname . '">
                 </div>
                 <div class="span5">
                 <h5><a href="' . $courseurl . '" >' . $trimtitle . '</a></h5>
                 </div>
                 <div class="span4">
                 <p>' . $summary . '</p>
                 </div>
                 </div>';
                 $coursehtml = '
                     <div style="background-image: url(' . $imgurl . ');background-repeat: no-repeat;background-size:cover; background-position:center;" class="promowrap">
                         <div class="fp-coursebox">
                             <div class="fp-courseinfo">
                                 <p style="font-size:24px;font-weight:bold;"><a href="' . $courseurl . '" id="button" data-toggle="tooltip" data-placement="bottom"title="' . $summary . '" >' . $trimtitle . '</a></p>
                             <div class="titlebar"> <h5>' . $promotedtitle . '</h5> </div>
                             <div data-toggle="collapse" data-target="#featured-listing" class="btn-link">' . $topshowfeatured . '</div>
                             </div>
                         </div>
                     </div>';
                 $rowcontent .= $coursehtml;
                 echo $listitems;
             }
             $rowcontent .= '</div></div> ';
             $featuredcontent .= $rowcontent;
         }
         echo "</div>";
     }
     $featuredcourses = $featuredheader . $featuredcontent . $featuredfooter;
     return $featuredcourses;
 }
Пример #26
0
 /**
  * Returns a list of databases in a provided list of courses,
  * if no list is provided all databases that the user can view will be returned.
  *
  * @param array $courseids the course ids
  * @return array the database details
  * @since Moodle 2.9
  */
 public static function get_databases_by_courses($courseids = array())
 {
     global $CFG;
     $params = self::validate_parameters(self::get_databases_by_courses_parameters(), array('courseids' => $courseids));
     $warnings = array();
     if (!empty($params['courseids'])) {
         $courses = array();
         $courseids = $params['courseids'];
     } else {
         $courses = enrol_get_my_courses();
         $courseids = array_keys($courses);
     }
     // Array to store the databases to return.
     $arrdatabases = array();
     // Ensure there are courseids to loop through.
     if (!empty($courseids)) {
         // Array of the courses we are going to retrieve the databases from.
         $dbcourses = array();
         // Go through the courseids.
         foreach ($courseids as $cid) {
             // Check the user can function in this context.
             try {
                 $context = context_course::instance($cid);
                 self::validate_context($context);
                 // Check if this course was already loaded (by enrol_get_my_courses).
                 if (!isset($courses[$cid])) {
                     $courses[$cid] = get_course($cid);
                 }
                 $dbcourses[$cid] = $courses[$cid];
             } catch (Exception $e) {
                 $warnings[] = array('item' => 'course', 'itemid' => $cid, 'warningcode' => '1', 'message' => 'No access rights in course context ' . $e->getMessage());
             }
         }
         // Get the databases in this course, this function checks users visibility permissions.
         // We can avoid then additional validate_context calls.
         $databases = get_all_instances_in_courses("data", $dbcourses);
         foreach ($databases as $database) {
             $datacontext = context_module::instance($database->coursemodule);
             // Entry to return.
             $newdb = array();
             // First, we return information that any user can see in the web interface.
             $newdb['id'] = $database->id;
             $newdb['coursemodule'] = $database->coursemodule;
             $newdb['course'] = $database->course;
             $newdb['name'] = $database->name;
             // Format intro.
             list($newdb['intro'], $newdb['introformat']) = external_format_text($database->intro, $database->introformat, $datacontext->id, 'mod_data', 'intro', null);
             // This information should be only available if the user can see the database entries.
             if (has_capability('mod/data:viewentry', $datacontext)) {
                 $viewablefields = array('comments', 'timeavailablefrom', 'timeavailableto', 'timeviewfrom', 'timeviewto', 'requiredentries', 'requiredentriestoview');
                 // This is for avoid a long repetitive list and for
                 // checking that we are retrieving all the required fields.
                 foreach ($viewablefields as $field) {
                     // We do not use isset because it won't work for existing null values.
                     if (!property_exists($database, $field)) {
                         throw new invalid_response_exception('Missing database module required field: ' . $field);
                     }
                     $newdb[$field] = $database->{$field};
                 }
             }
             // Check additional permissions for returning optional private settings.
             // I avoid intentionally to use can_[add|update]_moduleinfo.
             if (has_capability('moodle/course:manageactivities', $context)) {
                 $additionalfields = array('maxentries', 'rssarticles', 'singletemplate', 'listtemplate', 'listtemplateheader', 'listtemplatefooter', 'addtemplate', 'rsstemplate', 'rsstitletemplate', 'csstemplate', 'jstemplate', 'asearchtemplate', 'approval', 'scale', 'assessed', 'assesstimestart', 'assesstimefinish', 'defaultsort', 'defaultsortdir', 'editany', 'notification');
                 // This is for avoid a long repetitive list.
                 foreach ($additionalfields as $field) {
                     if (property_exists($database, $field)) {
                         $newdb[$field] = $database->{$field};
                     }
                 }
             }
             $arrdatabases[] = $newdb;
         }
     }
     $result = array();
     $result['databases'] = $arrdatabases;
     $result['warnings'] = $warnings;
     return $result;
 }
Пример #27
0
/**
 * Returns effective groupmode used in activity, course setting
 * overrides activity setting if groupmodeforce enabled.
 *
 * If $cm is an instance of cm_info it is easier to use $cm->effectivegroupmode
 *
 * @category group
 * @param cm_info|stdClass $cm the course module object. Only the ->course and ->groupmode need to be set.
 * @param stdClass $course object optional course object to improve perf
 * @return int group mode
 */
function groups_get_activity_groupmode($cm, $course = null)
{
    if ($cm instanceof cm_info) {
        return $cm->effectivegroupmode;
    }
    if (isset($course->id) and $course->id == $cm->course) {
        //ok
    } else {
        // Get course object (reuse $COURSE if possible).
        $course = get_course($cm->course, false);
    }
    return empty($course->groupmodeforce) ? $cm->groupmode : $course->groupmode;
}
Пример #28
0
 /**
  * Check if there is updates affecting the user for the given course and contexts.
  * Right now only modules are supported.
  * This WS calls mod_check_updates_since for each module to check if there is any update the user should we aware of.
  *
  * @param int $courseid the list of modules to check
  * @param array $tocheck the list of modules to check
  * @param array $filter check only for updates in these areas
  * @return array list of updates and warnings
  * @throws moodle_exception
  * @since Moodle 3.2
  */
 public static function check_updates($courseid, $tocheck, $filter = array())
 {
     global $CFG, $DB;
     $params = self::validate_parameters(self::check_updates_parameters(), array('courseid' => $courseid, 'tocheck' => $tocheck, 'filter' => $filter));
     $course = get_course($params['courseid']);
     $context = context_course::instance($course->id);
     self::validate_context($context);
     list($instances, $warnings) = course_check_updates($course, $params['tocheck'], $filter);
     $instancesformatted = array();
     foreach ($instances as $instance) {
         $updates = array();
         foreach ($instance['updates'] as $name => $data) {
             if (empty($data->updated)) {
                 continue;
             }
             $updatedata = array('name' => $name);
             if (!empty($data->timeupdated)) {
                 $updatedata['timeupdated'] = $data->timeupdated;
             }
             if (!empty($data->itemids)) {
                 $updatedata['itemids'] = $data->itemids;
             }
             $updates[] = $updatedata;
         }
         if (!empty($updates)) {
             $instancesformatted[] = array('contextlevel' => $instance['contextlevel'], 'id' => $instance['id'], 'updates' => $updates);
         }
     }
     return array('instances' => $instancesformatted, 'warnings' => $warnings);
 }
Пример #29
0
 /**
  * Tests moving the course up and down by one.
  */
 public function test_course_change_sortorder_by_one()
 {
     global $DB;
     $this->resetAfterTest(true);
     $generator = $this->getDataGenerator();
     $category = $generator->create_category();
     $course3 = $generator->create_course(array('category' => $category->id));
     $course2 = $generator->create_course(array('category' => $category->id));
     $course1 = $generator->create_course(array('category' => $category->id));
     $courses = $category->get_courses();
     $this->assertInternalType('array', $courses);
     $this->assertEquals(array($course1->id, $course2->id, $course3->id), array_keys($courses));
     $dbcourses = $DB->get_records('course', array('category' => $category->id), 'sortorder', 'id');
     $this->assertEquals(array_keys($dbcourses), array_keys($courses));
     // Test moving down.
     $course1 = get_course($course1->id);
     $this->assertTrue(course_change_sortorder_by_one($course1, false));
     $courses = $category->get_courses();
     $this->assertInternalType('array', $courses);
     $this->assertEquals(array($course2->id, $course1->id, $course3->id), array_keys($courses));
     $dbcourses = $DB->get_records('course', array('category' => $category->id), 'sortorder', 'id');
     $this->assertEquals(array_keys($dbcourses), array_keys($courses));
     // Test moving up.
     $course1 = get_course($course1->id);
     $this->assertTrue(course_change_sortorder_by_one($course1, true));
     $courses = $category->get_courses();
     $this->assertInternalType('array', $courses);
     $this->assertEquals(array($course1->id, $course2->id, $course3->id), array_keys($courses));
     $dbcourses = $DB->get_records('course', array('category' => $category->id), 'sortorder', 'id');
     $this->assertEquals(array_keys($dbcourses), array_keys($courses));
     // Test moving the top course up one.
     $course1 = get_course($course1->id);
     $this->assertFalse(course_change_sortorder_by_one($course1, true));
     // Check nothing changed.
     $courses = $category->get_courses();
     $this->assertInternalType('array', $courses);
     $this->assertEquals(array($course1->id, $course2->id, $course3->id), array_keys($courses));
     $dbcourses = $DB->get_records('course', array('category' => $category->id), 'sortorder', 'id');
     $this->assertEquals(array_keys($dbcourses), array_keys($courses));
     // Test moving the bottom course up down.
     $course3 = get_course($course3->id);
     $this->assertFalse(course_change_sortorder_by_one($course3, false));
     // Check nothing changed.
     $courses = $category->get_courses();
     $this->assertInternalType('array', $courses);
     $this->assertEquals(array($course1->id, $course2->id, $course3->id), array_keys($courses));
     $dbcourses = $DB->get_records('course', array('category' => $category->id), 'sortorder', 'id');
     $this->assertEquals(array_keys($dbcourses), array_keys($courses));
 }
Пример #30
0
/**
 * Changes the sort order of courses in a category so that the first course appears after the second.
 *
 * @param int|stdClass $courseorid The course to focus on.
 * @param int $moveaftercourseid The course to shifter after or 0 if you want it to be the first course in the category.
 * @return bool
 */
function course_change_sortorder_after_course($courseorid, $moveaftercourseid)
{
    global $DB;
    if (!is_object($courseorid)) {
        $course = get_course($courseorid);
    } else {
        $course = $courseorid;
    }
    if ((int) $moveaftercourseid === 0) {
        // We've moving the course to the start of the queue.
        $sql = 'SELECT sortorder
                      FROM {course}
                     WHERE category = :categoryid
                  ORDER BY sortorder';
        $params = array('categoryid' => $course->category);
        $sortorder = $DB->get_field_sql($sql, $params, IGNORE_MULTIPLE);
        $sql = 'UPDATE {course}
                   SET sortorder = sortorder + 1
                 WHERE category = :categoryid
                   AND id <> :id';
        $params = array('categoryid' => $course->category, 'id' => $course->id);
        $DB->execute($sql, $params);
        $DB->set_field('course', 'sortorder', $sortorder, array('id' => $course->id));
    } else {
        if ($course->id === $moveaftercourseid) {
            // They're the same - moronic.
            debugging("Invalid move after course given.", DEBUG_DEVELOPER);
            return false;
        } else {
            // Moving this course after the given course. It could be before it could be after.
            $moveaftercourse = get_course($moveaftercourseid);
            if ($course->category !== $moveaftercourse->category) {
                debugging("Cannot re-order courses. The given courses do not belong to the same category.", DEBUG_DEVELOPER);
                return false;
            }
            // Increment all courses in the same category that are ordered after the moveafter course.
            // This makes a space for the course we're moving.
            $sql = 'UPDATE {course}
                       SET sortorder = sortorder + 1
                     WHERE category = :categoryid
                       AND sortorder > :sortorder';
            $params = array('categoryid' => $moveaftercourse->category, 'sortorder' => $moveaftercourse->sortorder);
            $DB->execute($sql, $params);
            $DB->set_field('course', 'sortorder', $moveaftercourse->sortorder + 1, array('id' => $course->id));
        }
    }
    fix_course_sortorder();
    cache_helper::purge_by_event('changesincourse');
    return true;
}