/** * Sets up current user and course environment (lang, etc.) in cron. * Do not use outside of cron script! * * @param stdClass $user full user object, null means default cron user (admin) * @param $course full course record, null means $SITE * @return void */ function cron_setup_user($user = NULL, $course = NULL) { global $CFG, $SITE, $PAGE; static $cronuser = NULL; static $cronsession = NULL; if (empty($cronuser)) { /// ignore admins timezone, language and locale - use site default instead! $cronuser = get_admin(); $cronuser->timezone = $CFG->timezone; $cronuser->lang = ''; $cronuser->theme = ''; unset($cronuser->description); $cronsession = new stdClass(); } if (!$user) { // cached default cron user (==modified admin for now) session_set_user($cronuser); $_SESSION['SESSION'] = $cronsession; } else { // emulate real user session - needed for caps in cron if ($_SESSION['USER']->id != $user->id) { session_set_user($user); $_SESSION['SESSION'] = new stdClass(); } } // TODO MDL-19774 relying on global $PAGE in cron is a bad idea. // Temporary hack so that cron does not give fatal errors. $PAGE = new moodle_page(); if ($course) { $PAGE->set_course($course); } else { $PAGE->set_course($SITE); } // TODO: it should be possible to improve perf by caching some limited number of users here ;-) }
/** * Handle showing/processing the submission from the block editing form. * @return boolean true if the form was submitted and the new config saved. Does not * return if the editing form was displayed. False otherwise. */ public function process_url_edit() { global $CFG, $DB, $PAGE, $OUTPUT; $blockid = optional_param('bui_editid', null, PARAM_INT); if (!$blockid) { return false; } require_sesskey(); require_once $CFG->dirroot . '/blocks/edit_form.php'; $block = $this->find_instance($blockid); if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) { throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock')); } $editpage = new moodle_page(); $editpage->set_pagelayout('admin'); $editpage->set_course($this->page->course); //$editpage->set_context($block->context); $editpage->set_context($this->page->context); if ($this->page->cm) { $editpage->set_cm($this->page->cm); } $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring()); $editurlparams = $this->page->url->params(); $editurlparams['bui_editid'] = $blockid; $editpage->set_url($editurlbase, $editurlparams); $editpage->set_block_actions_done(); // At this point we are either going to redirect, or display the form, so // overwrite global $PAGE ready for this. (Formslib refers to it.) $PAGE = $editpage; //some functions like MoodleQuickForm::addHelpButton use $OUTPUT so we need to replace that to $output = $editpage->get_renderer('core'); $OUTPUT = $output; $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php'; if (is_readable($formfile)) { require_once $formfile; $classname = 'block_' . $block->name() . '_edit_form'; if (!class_exists($classname)) { $classname = 'block_edit_form'; } } else { $classname = 'block_edit_form'; } $mform = new $classname($editpage->url, $block, $this->page); $mform->set_data($block->instance); if ($mform->is_cancelled()) { redirect($this->page->url); } else { if ($data = $mform->get_data()) { $bi = new stdClass(); $bi->id = $block->instance->id; // This may get overwritten by the special case handling below. $bi->pagetypepattern = $data->bui_pagetypepattern; $bi->showinsubcontexts = (bool) $data->bui_contexts; if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') { $bi->subpagepattern = null; } else { $bi->subpagepattern = $data->bui_subpagepattern; } $systemcontext = context_system::instance(); $frontpagecontext = context_course::instance(SITEID); $parentcontext = context::instance_by_id($data->bui_parentcontextid); // Updating stickiness and contexts. See MDL-21375 for details. if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination // Explicitly set the default context $bi->parentcontextid = $parentcontext->id; if ($data->bui_editingatfrontpage) { // The block is being edited on the front page // The interface here is a special case because the pagetype pattern is // totally derived from the context menu. Here are the excpetions. MDL-30340 switch ($data->bui_contexts) { case BUI_CONTEXTS_ENTIRE_SITE: // The user wants to show the block across the entire site $bi->parentcontextid = $systemcontext->id; $bi->showinsubcontexts = true; $bi->pagetypepattern = '*'; break; case BUI_CONTEXTS_FRONTPAGE_SUBS: // The user wants the block shown on the front page and all subcontexts $bi->parentcontextid = $frontpagecontext->id; $bi->showinsubcontexts = true; $bi->pagetypepattern = '*'; break; case BUI_CONTEXTS_FRONTPAGE_ONLY: // The user want to show the front page on the frontpage only $bi->parentcontextid = $frontpagecontext->id; $bi->showinsubcontexts = false; $bi->pagetypepattern = 'site-index'; // This is the only relevant page type anyway but we'll set it explicitly just // in case the front page grows site-index-* subpages of its own later break; } } } $bits = explode('-', $bi->pagetypepattern); // hacks for some contexts if ($parentcontext->contextlevel == CONTEXT_COURSE && $parentcontext->instanceid != SITEID) { // For course context // is page type pattern is mod-*, change showinsubcontext to 1 if ($bits[0] == 'mod' || $bi->pagetypepattern == '*') { $bi->showinsubcontexts = 1; } else { $bi->showinsubcontexts = 0; } } else { if ($parentcontext->contextlevel == CONTEXT_USER) { // for user context // subpagepattern should be null if ($bits[0] == 'user' or $bits[0] == 'my') { // we don't need subpagepattern in usercontext $bi->subpagepattern = null; } } } $bi->defaultregion = $data->bui_defaultregion; $bi->defaultweight = $data->bui_defaultweight; $DB->update_record('block_instances', $bi); if (!empty($block->config)) { $config = clone $block->config; } else { $config = new stdClass(); } foreach ($data as $configfield => $value) { if (strpos($configfield, 'config_') !== 0) { continue; } $field = substr($configfield, 7); $config->{$field} = $value; } $block->instance_config_save($config); $bp = new stdClass(); $bp->visible = $data->bui_visible; $bp->region = $data->bui_region; $bp->weight = $data->bui_weight; $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion || $data->bui_weight != $data->bui_defaultweight; if ($block->instance->blockpositionid && !$needbprecord) { $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid)); } else { if ($block->instance->blockpositionid && $needbprecord) { $bp->id = $block->instance->blockpositionid; $DB->update_record('block_positions', $bp); } else { if ($needbprecord) { $bp->blockinstanceid = $block->instance->id; $bp->contextid = $this->page->context->id; $bp->pagetype = $this->page->pagetype; if ($this->page->subpage) { $bp->subpage = $this->page->subpage; } else { $bp->subpage = ''; } $DB->insert_record('block_positions', $bp); } } } redirect($this->page->url); } else { $strheading = get_string('blockconfiga', 'moodle', $block->get_title()); $editpage->set_title($strheading); $editpage->set_heading($strheading); $bits = explode('-', $this->page->pagetype); if ($bits[0] == 'tag' && !empty($this->page->subpage)) { // better navbar for tag pages $editpage->navbar->add(get_string('tags'), new moodle_url('/tag/')); $tag = tag_get('id', $this->page->subpage, '*'); // tag search page doesn't have subpageid if ($tag) { $editpage->navbar->add($tag->name, new moodle_url('/tag/index.php', array('id' => $tag->id))); } } $editpage->navbar->add($block->get_title()); $editpage->navbar->add(get_string('configuration')); echo $output->header(); echo $output->heading($strheading, 2); $mform->display(); echo $output->footer(); exit; } } }
public function test_navbar_prepend_and_add() { global $PAGE; // Unfortunate hack needed because people use global $PAGE around the place. $PAGE->set_url('/'); // We need to reset after this test because we using the generator. $this->resetAfterTest(); $generator = self::getDataGenerator(); $cat1 = $generator->create_category(); $cat2 = $generator->create_category(array('parent' => $cat1->id)); $course = $generator->create_course(array('category' => $cat2->id)); $page = new moodle_page(); $page->set_course($course); $page->set_url(new moodle_url('/course/view.php', array('id' => $course->id))); $page->navbar->prepend('test 1'); $page->navbar->prepend('test 2'); $page->navbar->add('test 3'); $page->navbar->add('test 4'); $items = $page->navbar->get_items(); foreach ($items as $item) { $this->assertInstanceOf('navigation_node', $item); } $i = 0; $this->assertSame('test 1', $items[$i++]->text); $this->assertSame('test 2', $items[$i++]->text); $this->assertSame('home', $items[$i++]->key); $this->assertSame('courses', $items[$i++]->key); $this->assertSame($cat1->id, $items[$i++]->key); $this->assertSame($cat2->id, $items[$i++]->key); $this->assertSame($course->id, $items[$i++]->key); $this->assertSame('test 3', $items[$i++]->text); $this->assertSame('test 4', $items[$i++]->text); return $page; }
/** * Sets up current user and course environment (lang, etc.) in cron. * Do not use outside of cron script! * * @param stdClass $user full user object, null means default cron user (admin), * value 'reset' means reset internal static caches. * @param stdClass $course full course record, null means $SITE * @return void */ function cron_setup_user($user = NULL, $course = NULL) { global $CFG, $SITE, $PAGE; if (!CLI_SCRIPT) { throw new coding_exception('Function cron_setup_user() cannot be used in normal requests!'); } static $cronuser = NULL; static $cronsession = NULL; if ($user === 'reset') { $cronuser = null; $cronsession = null; \core\session\manager::init_empty_session(); return; } if (empty($cronuser)) { /// ignore admins timezone, language and locale - use site default instead! $cronuser = get_admin(); $cronuser->timezone = $CFG->timezone; $cronuser->lang = ''; $cronuser->theme = ''; unset($cronuser->description); $cronsession = new stdClass(); } if (!$user) { // Cached default cron user (==modified admin for now). \core\session\manager::init_empty_session(); \core\session\manager::set_user($cronuser); $GLOBALS['SESSION'] = $cronsession; } else { // Emulate real user session - needed for caps in cron. if ($GLOBALS['USER']->id != $user->id) { \core\session\manager::init_empty_session(); \core\session\manager::set_user($user); } } // TODO MDL-19774 relying on global $PAGE in cron is a bad idea. // Temporary hack so that cron does not give fatal errors. $PAGE = new moodle_page(); if ($course) { $PAGE->set_course($course); } else { $PAGE->set_course($SITE); } // TODO: it should be possible to improve perf by caching some limited number of users here ;-) }
public static function email_digest() { global $CFG, $PERF; // Build current digest. mtrace("Beginning forum digest processing..."); if (!empty($PERF->dbqueries)) { $beforequeries = $PERF->dbqueries; } $before = microtime(true); mtrace('Initial query: ', ''); $list = new mod_forumng_digest_list(true); mtrace(round(microtime(true) - $before, 1) . 's'); $userdigests = array(); $oldcourse = null; // Forum loop. while ($list->next_forum($forum, $cm, $context, $course)) { self::debug("DEBUG: Forum " . $forum->get_name() . " on course {$course->shortname} " . "(cmid {$cm->id} contextid {$context->id})"); if (!$oldcourse || $course->id != $oldcourse->id) { // Finish off and clear users. if ($oldcourse) { self::digest_finish_course($oldcourse, $userdigests); } // Set up new course details. // Note: This code is a bit sketchy; borrowed from cron_setup_user. $PAGE = new moodle_page(); $PAGE->set_course($course); $oldcourse = clone $course; } // Count posts just for logging. $postcount = 0; // Get subscribers to forum. $subscribers = $forum->get_subscribers(); self::debug("DEBUG: Subscribers before filter " . count($subscribers), ''); self::email_filter_subscribers($course, $cm, $forum, $subscribers, true); self::debug(", after " . count($subscribers)); if (count($subscribers) == 0) { continue; } while ($list->next_discussion($discussion)) { self::debug("DEBUG: Discussion " . $discussion->get_subject() . ' (' . $discussion->get_id() . ')'); // Evaluate list of users based on this discussion (which holds // group info). Organise list by language, timezone and email // type. $discussionusers = array(); foreach ($subscribers as $subscriber) { if (self::subscriber_receives_discussion($forum, $discussion, $subscriber)) { $discussionusers[$subscriber->id] = $subscriber; } } while ($list->next_post($post, $inreplyto)) { // Loop through all digest users. foreach ($discussionusers as $user) { // Add to digest. (This will set up the user's // digest if they don't already have one). self::digest_add_post_for_user($user, $userdigests, $post, $inreplyto, $discussion, $forum, $cm, $course, $context); } $postcount++; } } } if ($oldcourse) { self::digest_finish_course($oldcourse, $userdigests); } $queryinfo = ''; if (!empty($PERF->dbqueries)) { $queryinfo = ', ' . ($PERF->dbqueries - $beforequeries) . ' queries'; } $totalpostcount = $list->get_post_count_so_far(); mtrace("Digest processing ({$totalpostcount} new digest posts) complete, total: " . round(microtime(true) - $before, 1) . 's' . $queryinfo); }
/** * Test search_courses */ public function test_search_courses() { global $DB; $this->resetAfterTest(true); $this->setAdminUser(); $generatedcourses = array(); $coursedata1['fullname'] = 'FIRST COURSE'; $course1 = self::getDataGenerator()->create_course($coursedata1); $page = new moodle_page(); $page->set_course($course1); $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*'); $coursedata2['fullname'] = 'SECOND COURSE'; $course2 = self::getDataGenerator()->create_course($coursedata2); $page = new moodle_page(); $page->set_course($course2); $page->blocks->add_blocks([BLOCK_POS_LEFT => ['news_items'], BLOCK_POS_RIGHT => []], 'course-view-*'); // Search by name. $results = core_course_external::search_courses('search', 'FIRST'); $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results); $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']); $this->assertCount(1, $results['courses']); // Create the forum. $record = new stdClass(); $record->introformat = FORMAT_HTML; $record->course = $course2->id; // Set Aggregate type = Average of ratings. $forum = self::getDataGenerator()->create_module('forum', $record); // Search by module. $results = core_course_external::search_courses('modulelist', 'forum'); $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results); $this->assertEquals(1, $results['total']); // Enable coursetag option. set_config('block_tags_showcoursetags', true); // Add tag 'TAG-LABEL ON SECOND COURSE' to Course2. core_tag_tag::set_item_tags('core', 'course', $course2->id, context_course::instance($course2->id), array('TAG-LABEL ON SECOND COURSE')); $taginstance = $DB->get_record('tag_instance', array('itemtype' => 'course', 'itemid' => $course2->id), '*', MUST_EXIST); // Search by tagid. $results = core_course_external::search_courses('tagid', $taginstance->tagid); $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results); $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']); // Search by block (use news_items default block). $blockid = $DB->get_field('block', 'id', array('name' => 'news_items')); $results = core_course_external::search_courses('blocklist', $blockid); $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results); $this->assertEquals(2, $results['total']); // Now as a normal user. $user = self::getDataGenerator()->create_user(); // Add a 3rd, hidden, course we shouldn't see, even when enrolled as student. $coursedata3['fullname'] = 'HIDDEN COURSE'; $coursedata3['visible'] = 0; $course3 = self::getDataGenerator()->create_course($coursedata3); $this->getDataGenerator()->enrol_user($user->id, $course3->id, 'student'); $this->getDataGenerator()->enrol_user($user->id, $course2->id, 'student'); $this->setUser($user); $results = core_course_external::search_courses('search', 'FIRST'); $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results); $this->assertCount(1, $results['courses']); $this->assertEquals(1, $results['total']); $this->assertEquals($coursedata1['fullname'], $results['courses'][0]['fullname']); // Check that we can see both without the limit to enrolled setting. $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 0); $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results); $this->assertCount(2, $results['courses']); $this->assertEquals(2, $results['total']); // Check that we only see our enrolled course when limiting. $results = core_course_external::search_courses('search', 'COURSE', 0, 0, array(), 1); $results = external_api::clean_returnvalue(core_course_external::search_courses_returns(), $results); $this->assertCount(1, $results['courses']); $this->assertEquals(1, $results['total']); $this->assertEquals($coursedata2['fullname'], $results['courses'][0]['fullname']); // Search by block (use news_items default block). Should fail (only admins allowed). $this->expectException('required_capability_exception'); $results = core_course_external::search_courses('blocklist', $blockid); }
/** * Handle showing/processing the submission from the block editing form. * @return boolean true if the form was submitted and the new config saved. Does not * return if the editing form was displayed. False otherwise. */ public function process_url_edit() { global $CFG, $DB, $PAGE; $blockid = optional_param('bui_editid', null, PARAM_INTEGER); if (!$blockid) { return false; } confirm_sesskey(); require_once $CFG->dirroot . '/blocks/edit_form.php'; $block = $this->find_instance($blockid); if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) { throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock')); } $editpage = new moodle_page(); $editpage->set_generaltype('form'); $editpage->set_course($this->page->course); $editpage->set_context($block->context); $editurlbase = str_replace($CFG->wwwroot . '/', '', $this->page->url->out(true)); $editurlparams = $this->page->url->params(); $editurlparams['bui_editid'] = $blockid; $editpage->set_url($editurlbase, $editurlparams); $editpage->_block_actions_done = true; // At this point we are either going to redirect, or display the form, so // overwrite global $PAGE ready for this. (Formslib refers to it.) $PAGE = $editpage; $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php'; if (is_readable($formfile)) { require_once $formfile; $classname = 'block_' . $block->name() . '_edit_form'; } else { $classname = 'block_edit_form'; } $mform = new $classname($editpage->url, $block, $this->page); $mform->set_data($block->instance); if ($mform->is_cancelled()) { redirect($this->page->url); } else { if ($data = $mform->get_data()) { $bi = new stdClass(); $bi->id = $block->instance->id; $bi->showinsubcontexts = $data->bui_showinsubcontexts; $bi->pagetypepattern = $data->bui_pagetypepattern; if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') { $bi->subpagepattern = null; } else { $bi->subpagepattern = $data->bui_subpagepattern; } $bi->defaultregion = $data->bui_defaultregion; $bi->defaultweight = $data->bui_defaultweight; $DB->update_record('block_instances', $bi); if (!empty($block->config)) { $config = clone $block->config; } else { $config = new stdClass(); } foreach ($data as $configfield => $value) { if (strpos($configfield, 'config_') !== 0) { continue; } $field = substr($configfield, 7); $config->{$field} = $value; } $block->instance_config_save($config); $bp = new stdClass(); $bp->visible = $data->bui_visible; $bp->region = $data->bui_region; $bp->weight = $data->bui_weight; $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion || $data->bui_weight != $data->bui_defaultweight; if ($block->instance->blockpositionid && !$needbprecord) { $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid)); } else { if ($block->instance->blockpositionid && $needbprecord) { $bp->id = $block->instance->blockpositionid; $DB->update_record('block_positions', $bp); } else { if ($needbprecord) { $bp->blockinstanceid = $block->instance->id; $bp->contextid = $this->page->context->id; $bp->pagetype = $this->page->pagetype; if ($this->page->subpage) { $bp->subpage = $this->page->subpage; } else { $bp->subpage = ''; } $DB->insert_record('block_positions', $bp); } } } redirect($this->page->url); } else { $strheading = get_string('editinga', $block->name()); if (strpos($strheading, '[[') === 0) { $strheading = get_string('blockconfiga', 'moodle', $block->get_title()); } $editpage->set_title($strheading); $editpage->set_heading($strheading); $output = $editpage->theme->get_renderer('core', $editpage); echo $output->header(); echo $output->heading($strheading, 2); $mform->display(); echo $output->footer(); exit; } } }
/** * Handle showing/processing the submission from the block editing form. * @return boolean true if the form was submitted and the new config saved. Does not * return if the editing form was displayed. False otherwise. */ public function process_url_edit() { global $CFG, $DB, $PAGE; $blockid = optional_param('bui_editid', null, PARAM_INTEGER); if (!$blockid) { return false; } require_sesskey(); require_once $CFG->dirroot . '/blocks/edit_form.php'; $block = $this->find_instance($blockid); if (!$block->user_can_edit() && !$this->page->user_can_edit_blocks()) { throw new moodle_exception('nopermissions', '', $this->page->url->out(), get_string('editblock')); } $editpage = new moodle_page(); $editpage->set_pagelayout('admin'); $editpage->set_course($this->page->course); $editpage->set_context($block->context); if ($this->page->cm) { $editpage->set_cm($this->page->cm); } $editurlbase = str_replace($CFG->wwwroot . '/', '/', $this->page->url->out_omit_querystring()); $editurlparams = $this->page->url->params(); $editurlparams['bui_editid'] = $blockid; $editpage->set_url($editurlbase, $editurlparams); $editpage->set_block_actions_done(); // At this point we are either going to redirect, or display the form, so // overwrite global $PAGE ready for this. (Formslib refers to it.) $PAGE = $editpage; $formfile = $CFG->dirroot . '/blocks/' . $block->name() . '/edit_form.php'; if (is_readable($formfile)) { require_once $formfile; $classname = 'block_' . $block->name() . '_edit_form'; if (!class_exists($classname)) { $classname = 'block_edit_form'; } } else { $classname = 'block_edit_form'; } $mform = new $classname($editpage->url, $block, $this->page); $mform->set_data($block->instance); if ($mform->is_cancelled()) { redirect($this->page->url); } else { if ($data = $mform->get_data()) { $bi = new stdClass(); $bi->id = $block->instance->id; $bi->pagetypepattern = $data->bui_pagetypepattern; if (empty($data->bui_subpagepattern) || $data->bui_subpagepattern == '%@NULL@%') { $bi->subpagepattern = null; } else { $bi->subpagepattern = $data->bui_subpagepattern; } $parentcontext = get_context_instance_by_id($data->bui_parentcontextid); $systemcontext = get_context_instance(CONTEXT_SYSTEM); // Updating stickiness and contexts. See MDL-21375 for details. if (has_capability('moodle/site:manageblocks', $parentcontext)) { // Check permissions in destination // Explicitly set the context $bi->parentcontextid = $parentcontext->id; // If the context type is > 0 then we'll explicitly set the block as sticky, otherwise not $bi->showinsubcontexts = (int) (!empty($data->bui_contexts)); // If the block wants to be system-wide, then explicitly set that if ($data->bui_contexts == 2) { // Only possible on a frontpage or system page $bi->parentcontextid = $systemcontext->id; } else { // The block doesn't want to be system-wide, so let's ensure that if ($parentcontext->id == $systemcontext->id) { // We need to move it to the front page $frontpagecontext = get_context_instance(CONTEXT_COURSE, SITEID); $bi->parentcontextid = $frontpagecontext->id; $bi->pagetypepattern = '*'; // Just in case } } } $bi->defaultregion = $data->bui_defaultregion; $bi->defaultweight = $data->bui_defaultweight; $DB->update_record('block_instances', $bi); if (!empty($block->config)) { $config = clone $block->config; } else { $config = new stdClass(); } foreach ($data as $configfield => $value) { if (strpos($configfield, 'config_') !== 0) { continue; } $field = substr($configfield, 7); $config->{$field} = $value; } $block->instance_config_save($config); $bp = new stdClass(); $bp->visible = $data->bui_visible; $bp->region = $data->bui_region; $bp->weight = $data->bui_weight; $needbprecord = !$data->bui_visible || $data->bui_region != $data->bui_defaultregion || $data->bui_weight != $data->bui_defaultweight; if ($block->instance->blockpositionid && !$needbprecord) { $DB->delete_records('block_positions', array('id' => $block->instance->blockpositionid)); } else { if ($block->instance->blockpositionid && $needbprecord) { $bp->id = $block->instance->blockpositionid; $DB->update_record('block_positions', $bp); } else { if ($needbprecord) { $bp->blockinstanceid = $block->instance->id; $bp->contextid = $this->page->context->id; $bp->pagetype = $this->page->pagetype; if ($this->page->subpage) { $bp->subpage = $this->page->subpage; } else { $bp->subpage = ''; } $DB->insert_record('block_positions', $bp); } } } redirect($this->page->url); } else { $strheading = get_string('blockconfiga', 'moodle', $block->get_title()); $editpage->set_title($strheading); $editpage->set_heading($strheading); $editpage->navbar->add($strheading); $output = $editpage->get_renderer('core'); echo $output->header(); echo $output->heading($strheading, 2); $mform->display(); echo $output->footer(); exit; } } }
/** * Add the default blocks to a course. * @param object $course a course object. */ function blocks_add_default_course_blocks($course) { global $CFG; if (!empty($CFG->defaultblocks_override)) { $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks_override); } else { if ($course->id == SITEID) { $blocknames = blocks_get_default_site_course_blocks(); } else { $defaultblocks = 'defaultblocks_' . $course->format; if (!empty($CFG->{$defaultblocks})) { $blocknames = blocks_parse_default_blocks_list($CFG->{$defaultblocks}); } else { $formatconfig = $CFG->dirroot . '/course/format/' . $course->format . '/config.php'; if (is_readable($formatconfig)) { require $formatconfig; } if (!empty($format['defaultblocks'])) { $blocknames = blocks_parse_default_blocks_list($format['defaultblocks']); } else { if (!empty($CFG->defaultblocks)) { $blocknames = blocks_parse_default_blocks_list($CFG->defaultblocks); } else { $blocknames = array(BLOCK_POS_LEFT => array('participants', 'activity_modules', 'search_forums', 'admin', 'course_list'), BLOCK_POS_RIGHT => array('news_items', 'calendar_upcoming', 'recent_activity')); } } } } } if ($course->id == SITEID) { $pagetypepattern = 'site-index'; } else { $pagetypepattern = 'course-view-*'; } $page = new moodle_page(); $page->set_course($course); $page->blocks->add_blocks($blocknames, $pagetypepattern); }
static function email_digest() { global $CFG, $PERF; // Do digest mails if required. Note this is based on server time not // user time. $nextdigest = get_config('forumng', 'nextdigest'); if (!$nextdigest) { // Run digest at next occurrence of the requested time $nextdigest = strtotime($CFG->digestmailtime . ':00'); if ($nextdigest <= time()) { $nextdigest = strtotime('+1 day', $nextdigest); } set_config('nextdigest', $nextdigest, 'forumng'); } if (time() < $nextdigest) { self::debug("DEBUG: Not yet time for digest"); return; } // Run digest again next day at specified time (note: best to // get time again, as they may have changed it) $nextdigest = strtotime($CFG->digestmailtime . ':00'); if ($nextdigest <= time()) { $nextdigest = strtotime('+1 day', $nextdigest); } set_config('nextdigest', $nextdigest, 'forumng'); // OK, now build current digest mtrace("Beginning forum digest processing..."); if (!empty($PERF->dbqueries)) { $beforequeries = $PERF->dbqueries; } $before = microtime(true); mtrace('Initial query: ', ''); $list = new mod_forumng_digest_list(true); mtrace(round(microtime(true) - $before, 1) . 's'); $userdigests = array(); $oldcourse = null; // Forum loop while ($list->next_forum($forum, $cm, $context, $course)) { self::debug("DEBUG: Forum " . $forum->get_name() . " on course {$course->shortname} " . "(cmid {$cm->id} contextid {$context->id})"); if (!$oldcourse || $course->id != $oldcourse->id) { // Finish off and clear users if ($oldcourse) { self::digest_finish_course($oldcourse, $userdigests); } // Set up new course details // Note: This code is a bit sketchy; borrowed from cron_setup_user $PAGE = new moodle_page(); $PAGE->set_course($course); $oldcourse = clone $course; } // Count posts just for logging $postcount = 0; // Get subscribers to forum $subscribers = $forum->get_subscribers(); self::debug("DEBUG: Subscribers before filter " . count($subscribers), ''); self::email_filter_subscribers($course, $cm, $forum, $subscribers, true); self::debug(", after " . count($subscribers)); if (count($subscribers) == 0) { continue; } while ($list->next_discussion($discussion)) { self::debug("DEBUG: Discussion " . $discussion->get_subject() . ' (' . $discussion->get_id() . ')'); // Evaluate list of users based on this discussion (which holds // group info). Organise list by language, timezone and email // type. $discussionusers = array(); foreach ($subscribers as $subscriber) { if (self::subscriber_receives_discussion($forum, $discussion, $subscriber)) { $discussionusers[$subscriber->id] = $subscriber; } } while ($list->next_post($post, $inreplyto)) { // Loop through all digest users foreach ($discussionusers as $user) { // Add to digest. (This will set up the user's // digest if they don't already have one) self::digest_add_post_for_user($user, $userdigests, $post, $inreplyto, $discussion, $forum, $cm, $course, $context); } $postcount++; } } } if ($oldcourse) { self::digest_finish_course($oldcourse, $userdigests); } $queryinfo = ''; if (!empty($PERF->dbqueries)) { $queryinfo = ', ' . ($PERF->dbqueries - $beforequeries) . ' queries'; } $totalpostcount = $list->get_post_count_so_far(); mtrace("Digest processing ({$totalpostcount} new digest posts) complete, total: " . round(microtime(true) - $before, 1) . 's' . $queryinfo); }
public function create_skillsmanagement($userid, $testing_mode) { global $DB, $CFG; require_once $CFG->dirroot . '/user/profile/lib.php'; require_once $CFG->dirroot . '/user/lib.php'; require_once $CFG->dirroot . '/blocks/exacomp/lib/lib.php'; $user = $DB->get_record('user', ['id' => $userid]); if (!$user) { throw new moodle_exception('user not found'); } /*CREATE COURSE CATEGORY*/ //check if course category has already been created $category_already_exists = false; $max_sort = 0; $categoryid = 0; $category_sortoder = 0; $categorycontext = 0; $categorycontextpath = ''; $course_categories = $DB->get_records('course_categories'); foreach ($course_categories as $category) { if (strcmp($category->name, 'Skillmanagement') == 0) { $category_already_exists = true; $categoryid = $category->id; $category_sortoder = $category->sortorder; $context = $DB->get_record('context', array('instanceid' => $categoryid, 'contextlevel' => 40)); $categorycontext = $context->id; $categorycontextpath = $context->path; } elseif ($category->sortorder > $max_sort) { $max_sort = $category->sortorder; } } //if not->create if (!$category_already_exists) { /*INSERT IN COURSE_CATEGORIES*/ $insert = new stdClass(); $insert->name = 'Skillmanagement'; $insert->description = '<p>Dieser Kursbereich wird für automatisch generierte Kurse von Skillmanagement verwendet.</p>'; $insert->descriptionformat = 1; $insert->sortorder = $max_sort + 10000; $insert->timemodified = time(); $insert->depth = 1; $insertedid = $DB->insert_record('course_categories', $insert); $inserted = $DB->get_record('course_categories', array('id' => $insertedid)); $categoryid = $inserted->id; $category_sortoder = $inserted->sortorder; $update = new stdClass(); $update->id = $inserted->id; $update->path = '/' . $inserted->id; $DB->update_record('course_categories', $update); /*INSERT IN CONTEXT*/ $insert = new stdClass(); $insert->contextlevel = 40; $insert->instanceid = $inserted->id; $insert->depth = 2; $insertedid = $DB->insert_record('context', $insert); $inserted = $DB->get_record('context', array('id' => $insertedid)); $categorycontext = $inserted->id; $categorycontextpath = '/1/' . $inserted->id; $update = new stdClass(); $update->id = $inserted->id; $update->path = '/1/' . $inserted->id; $DB->update_record('context', $update); } /*TESTED AND WORKING CORRECTLY TILL HERE*/ $user_course = $DB->get_record('course', ['shortname' => 'SKILLSMGMT-' . $user->id]); if (!$user_course) { $categorycourses = $DB->get_records_sql('SELECT * FROM {course} WHERE category=?', array($categoryid)); /*CREATE COURSE*/ //insert in course-table $insert = new stdClass(); $insert->category = $categoryid; $insert->sortorder = $category_sortoder + count($categorycourses) + 1; $insert->fullname = 'Skillsmanagement_' . $user->id . '_' . $user->lastname; $insert->shortname = 'SKILLSMGMT-' . $user->id; $insert->format = 'weeks'; $insert->summaryformat = 1; $insert->startdate = time(); $insert->timecreated = time(); $insert->timemodified = time(); $insert->cacherev = time(); $user_course = create_course($insert); /*CREATE EXABIS BLOCK INSTANCES IN COURSE*/ $page = new moodle_page(); $page->set_course($user_course); $page->blocks->add_region('side-post'); $page->blocks->add_block('exacomp', 'side-post', 4, false, 'course-view-*'); $page->blocks->add_block('exaport', 'side-post', 4, false, 'course-view-*'); $page->blocks->add_block('exastud', 'side-post', 4, false, 'course-view-*'); /*CREATE COURSE DESCRIPTION*/ $label = new stdClass(); $label->intro = get_string('course_description', 'auth_skillmanagement'); $label->intro .= html_writer::empty_tag('br'); $label->intro .= html_writer::empty_tag('img', array('src' => new moodle_url('/auth/skillmanagement/pix/intro.png'), 'alt' => 'intro')); $label->course = $user_course->id; $label->introformat = 1; $labelid = label_add_instance($label); /*CREATE COURSE MODULE*/ $label_module = $DB->get_record('modules', array('name' => 'label')); $section = $DB->get_record('course_sections', array('course' => $user_course->id, 'section' => 0)); $cm = new stdClass(); $cm->course = $user_course->id; $cm->module = $label_module->id; $cm->instance = $labelid; $cm->section = $section->id; $cm->added = time(); $cmid = $DB->insert_record('course_modules', $cm); course_add_cm_to_section($user_course->id, $cmid, 0); $course_context = context_course::instance($user_course->id); } $source = $DB->get_record(\block_exacomp\DB_DATASOURCES, ['source' => 'SKILLSMGMT-' . $user->id]); if (!$source) { // import new for this user \block_exacomp\data_importer::do_import_file(__DIR__ . '/skills_mgmt_' . ($user->lang == 'de' ? 'de' : 'en') . '.xml'); // last imported source $source = $DB->get_record_sql("SELECT * FROM {" . \block_exacomp\DB_DATASOURCES . "} ORDER BY id DESC LIMIT 1"); // change source $source->source = 'SKILLSMGMT-' . $user->id; $source->name = 'Skills Management for ' . fullname($user); $DB->update_record(\block_exacomp\DB_DATASOURCES, $source); } // last imported schooltypes $schooltype_ids = $DB->get_records_menu(\block_exacomp\DB_SCHOOLTYPES, ['source' => $source->id], null, 'sourceid AS id, id AS val'); block_exacomp_set_mdltype($schooltype_ids, $user_course->id); $subjects = block_exacomp_get_subjects_for_schooltype($user_course->id, 0); /* if ($user->lang == 'de') { $subjects = block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[72]) + block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[73]); } else { $subjects = block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[492]) + block_exacomp_get_subjects_for_schooltype($user_course->id, $schooltype_ids[493]); } */ $coursetopics = array(); foreach ($subjects as $subject) { $topics = block_exacomp_get_all_topics($subject->id); foreach ($topics as $topic) { $coursetopics[] = $topic->id; } } block_exacomp_set_coursetopics($user_course->id, $coursetopics); /*DELETE OTHER MODULES FROM COURSE*/ //delete module recent activity /*$recent_activity = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'recent_activity')); course_delete_module($recent_activity->id); $search_forum = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'search_forums')); course_delete_module($search_forum->id); $news_items = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'news_items')); course_delete_module($news_items->id); $calendar = $DB->get_record('block_instances', array('parentcontextid'=>$course_context->id, 'blockname'=>'calendar_upcoming')); course_delete_module($calendar->id); /*CREATE SECOND USER WITH SAME PW*/ $user_student = $DB->get_record('user', array('username' => 'employee_' . $user->username)); if (!$user_student) { $user_student = new stdClass(); $user_student->firstname = get_string('firstname', 'auth_skillmanagement'); $user_student->lastname = get_string('lastname', 'auth_skillmanagement'); $user_student->confirmed = 1; $user_student->password = '******'; // will be overwritten later $user_student->email = $user->email; $user_student->auth = 'skillmanagement'; $user_student->username = '******' . $user->username; $user_student->lang = $user->lang; $user_student->mnethostid = 1; $user_student->id = user_create_user($user_student, false, false); profile_save_data($user_student); } $DB->update_record('user', ['confirmed' => 1, 'password' => $user->password, 'id' => $user_student->id]); /* $DB->update_record('user', [ 'confirmed' => 1, // 'idnumber' => $user_student->id, // not sure why?!? connect student to teacher?!? 'id' => $user->id, ]); */ /*ENROL user_trainer AND user_trainee to $user_course */ $enrolment = array('roleid' => 3, 'userid' => $user->id, 'courseid' => $user_course->id, 'timestart' => time(), 'timeend' => 0, 'suspend' => 0); $enrol = enrol_get_plugin('manual'); $enrolinstances = enrol_get_instances($enrolment['courseid'], true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance = $courseenrolinstance; break; } } if (empty($instance)) { $errorparams = new stdClass(); $errorparams->courseid = $enrolment['courseid']; throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams); } // Check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin). if (!$enrol->allow_enrol($instance)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams); } $enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['suspend']); //enrol participant $enrolment = array('roleid' => 5, 'userid' => $user_student->id, 'courseid' => $user_course->id, 'timestart' => time(), 'timeend' => 0, 'suspend' => 0); $enrol = enrol_get_plugin('manual'); $enrolinstances = enrol_get_instances($enrolment['courseid'], true); foreach ($enrolinstances as $courseenrolinstance) { if ($courseenrolinstance->enrol == "manual") { $instance = $courseenrolinstance; break; } } if (empty($instance)) { $errorparams = new stdClass(); $errorparams->courseid = $enrolment['courseid']; throw new moodle_exception('wsnoinstance', 'enrol_manual', $errorparams); } // Check that the plugin accept enrolment (it should always the case, it's hard coded in the plugin). if (!$enrol->allow_enrol($instance)) { $errorparams = new stdClass(); $errorparams->roleid = $enrolment['roleid']; $errorparams->courseid = $enrolment['courseid']; $errorparams->userid = $enrolment['userid']; throw new moodle_exception('wscannotenrol', 'enrol_manual', '', $errorparams); } $enrol->enrol_user($instance, $enrolment['userid'], $enrolment['roleid'], $enrolment['timestart'], $enrolment['timeend'], $enrolment['suspend']); // elove if (!$DB->record_exists(\block_exacomp\DB_EXTERNAL_TRAINERS, array('trainerid' => $user->id, 'studentid' => $user_student->id))) { $DB->insert_record(\block_exacomp\DB_EXTERNAL_TRAINERS, array('trainerid' => $user->id, 'studentid' => $user_student->id)); } }