function poll_results_link() { global $USER; $page = page_create_object($this->instance->pagetype, $this->instance->pageid); $url = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => $USER->sesskey, 'blockaction' => 'config', 'action' => 'responses', 'pid' => $this->poll->id)); return "<hr />(<a href=\"{$url}\">" . get_string('responses', 'block_poll') . '</a>)'; }
/** * Display the resource with the course blocks. */ function display_course_blocks_start() { global $CFG; global $USER; global $THEME; require_once $CFG->libdir . '/blocklib.php'; require_once $CFG->libdir . '/pagelib.php'; require_once $CFG->dirroot . '/course/lib.php'; //required by some blocks $PAGE = page_create_object(PAGE_COURSE_VIEW, $this->course->id); $this->PAGE = $PAGE; $pageblocks = blocks_setup($PAGE); $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210); /// Print the page header $edit = optional_param('edit', -1, PARAM_BOOL); if ($edit != -1 and $PAGE->user_allowed_editing()) { $USER->editing = $edit; } $morenavlinks = array($this->strresources => 'index.php?id=' . $this->course->id, $this->resource->name => ''); $PAGE->print_header($this->course->shortname . ': %fullname%', $morenavlinks, "", "", update_module_button($this->cm->id, $this->course->id, $this->strresource)); echo '<table id="layout-table"><tr>'; $lt = empty($THEME->layouttable) ? array('left', 'middle', 'right') : $THEME->layouttable; foreach ($lt as $column) { $lt1[] = $column; if ($column == 'middle') { break; } } foreach ($lt1 as $column) { switch ($column) { case 'left': if (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $PAGE->user_is_editing()) { echo '<td style="width: ' . $blocks_preferred_width . 'px;" id="left-column">'; print_container_start(); blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT); print_container_end(); echo '</td>'; } break; case 'middle': echo '<td id="middle-column">'; print_container_start(false, 'middle-column-wrap'); echo '<div id="resource">'; break; case 'right': if (blocks_have_content($pageblocks, BLOCK_POS_RIGHT) || $PAGE->user_is_editing()) { echo '<td style="width: ' . $blocks_preferred_width . 'px;" id="right-column">'; print_container_start(); blocks_print_group($PAGE, $pageblocks, BLOCK_POS_RIGHT); print_container_end(); echo '</td>'; } break; } } }
/** * This function displays the controls to add modules and blocks to a page * * @param object $page A fully populated page object * @param object $course A fully populated course object * @uses $USER; * @uses $CFG; */ function page_print_add_mods_form($page, $course) { global $USER, $CFG, $PAGE; if (empty($PAGE)) { $PAGE = page_create_object(PAGE_COURSE_VIEW, $course->id); } print_box_start('centerpara addpageitems'); // Add drop down to add blocks if ($blocks = get_records('block', 'visible', '1', 'name')) { $format = $PAGE->get_format_name(); $options = array(); foreach ($blocks as $b) { if (in_array($b->name, array('format_page', 'page_module'))) { continue; } if (!blocks_name_allowed_in_format($b->name, $format)) { continue; } $blockobject = block_instance($b->name); if ($blockobject !== false && $blockobject->user_can_addto($PAGE)) { $options[$b->id] = $blockobject->get_title(); } } asort($options); print '<span class="addblock">'; $common = $CFG->wwwroot . '/course/format/page/format.php?id=' . $course->id . '&page=' . $page->id . '&blockaction=add&sesskey=' . sesskey() . '&blockid='; popup_form($common, $options, 'addblock', '', get_string('addblock', 'format_page')); print '</span> '; } // Add drop down to add existing module instances if ($modules = page_get_modules($course, 'name')) { // From our modules object we can build an existing module menu using separators $options = array(); foreach ($modules as $modplural => $instances) { // Sets an optgroup which can't be selected/submitted $options[$modplural . '_group_start'] = "--{$modplural}"; foreach ($instances as $cmid => $name) { $options[$cmid] = shorten_text($name); } // Ends an optgroup $options[$modplural . '_group_end'] = '--'; } print '<span class="addexistingmodule">'; $common = $CFG->wwwroot . '/course/format/page/format.php?id=' . $course->id . '&page=' . $page->id . '&blockaction=addmod&sesskey=' . sesskey() . '&instance='; popup_form($common, $options, 'addinstance', '', get_string('addexistingmodule', 'format_page')); print '</span>'; } print_box_end(); }
function get_content() { global $CFG, $USER, $COURSE; if (!empty($COURSE)) { $this->courseid = $COURSE->id; } if ($this->content !== NULL) { return $this->content; } $this->content = new stdClass(); $choices = get_records_sql("SELECT id, name FROM {$CFG->prefix}choice where course={$COURSE->id}"); if ($choices) { $this->content->text = "<SELECT id=\"selection\">"; foreach ($choices as $choice) { $this->content->text .= "<option value={$choice->id}>{$choice->name}</option>"; } $this->content->text .= '</select>'; $this->content->text .= ' <script type="text/javascript"> function submitme(){ document.getElementById("newsite").href="'; $page = page_create_object($this->instance->pagetype, $this->instance->pageid); $this->content->text .= $page->url_get_path(); $params = array('instanceid' => $this->instance->id, 'sesskey' => $USER->sesskey, 'blockaction' => 'config', 'currentaction' => 'create', 'id' => $this->courseid, 'section' => 'choice_to_group'); $first = true; foreach ($params as $var => $value) { $this->content->text .= $first ? '?' : '&'; $this->content->text .= $var . '=' . urlencode($value); $first = false; } $this->content->text .= "&selection=\""; $this->content->text .= '+document.getElementById("selection").value; return true; } </script>'; $this->content->text .= "<A ID=\"newsite\" HREF=\"\" onClick=\"return submitme()\">" . get_string("continue", "moodle") . "</A>"; } else { $this->content->text .= get_string("no_choices", "block_choice_to_group"); } $this->content->footer = ''; return $this->content; }
redirect("{$CFG->wwwroot}/"); case 'admin': redirect("{$CFG->wwwroot}/{$CFG->admin}/"); } } else { $errormsg = get_string('errorwithsettings', 'admin'); $firsterror = reset($adminroot->errors); $focus = $firsterror->id; } $adminroot =& admin_get_root(true); //reload tree $page =& $adminroot->locate($section); } /// very hacky page setup page_map_class(PAGE_ADMIN, 'page_admin'); $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number $PAGE->init_extra($section); $CFG->pagepath = 'admin/setting/' . $section; if (!isset($USER->adminediting)) { $USER->adminediting = false; } if ($PAGE->user_allowed_editing()) { if ($adminediting == 1) { $USER->adminediting = true; } elseif ($adminediting == 0) { $USER->adminediting = false; } } /// print header stuff ------------------------------------------------------------ if (empty($SITE->fullname)) {
/** * Initialise admin page - this function does require login and permission * checks specified in page definition. * This function must be called on each admin page before other code. * @param string $section name of page */ function admin_externalpage_setup($section) { global $CFG, $PAGE, $USER; require_once $CFG->libdir . '/blocklib.php'; require_once $CFG->dirroot . '/' . $CFG->admin . '/pagelib.php'; if ($site = get_site()) { require_login(); } else { redirect($CFG->wwwroot . '/' . $CFG->admin . '/index.php'); die; } $adminroot =& admin_get_root(false, false); // settings not required for external pages $extpage =& $adminroot->locate($section); if (empty($extpage) or !is_a($extpage, 'admin_externalpage')) { error(get_string('sectionerror', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/"); die; } // this eliminates our need to authenticate on the actual pages if (!$extpage->check_access()) { error(get_string('accessdenied', 'admin')); die; } page_map_class(PAGE_ADMIN, 'page_admin'); $PAGE = page_create_object(PAGE_ADMIN, 0); // there must be any constant id number $PAGE->init_extra($section); // hack alert! $adminediting = optional_param('adminedit', -1, PARAM_BOOL); if (!isset($USER->adminediting)) { $USER->adminediting = false; } if ($PAGE->user_allowed_editing()) { if ($adminediting == 1) { $USER->adminediting = true; } elseif ($adminediting == 0) { $USER->adminediting = false; } } }
$edit = optional_param('edit', -1, PARAM_BOOL); $userpage = optional_param('userpage', 0, PARAM_INT); // which page to show $perpage = optional_param('perpage', 24, PARAM_INT); if ($tagname) { $tag = tag_get('name', $tagname, '*'); } else { if ($tagid) { $tag = tag_get('id', $tagid, '*'); } } if (empty($tag)) { redirect($CFG->wwwroot . '/tag/search.php'); } //create a new page_tag object, defined in pagelib.php $PAGE = page_create_object(PAGE_TAG_INDEX, $tag->id); $pageblocks = blocks_setup($PAGE, BLOCKS_PINNED_BOTH); $PAGE->tag_object = $tag; if ($edit != -1 and $PAGE->user_allowed_editing()) { $USER->editing = $edit; } $PAGE->print_header(); // Manage all tags links $systemcontext = get_context_instance(CONTEXT_SYSTEM); if (has_capability('moodle/tag:manage', $systemcontext)) { echo '<div class="managelink"><a href="' . $CFG->wwwroot . '/tag/manage.php">' . get_string('managetags', 'tag') . '</a></div>'; } echo '<table border="0" cellpadding="3" cellspacing="0" width="100%" id="layout-table">'; echo '<tr valign="top">'; //----------------- left column ----------------- $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210);
//alhanumeric and - $pagetypes = array(PAGE_MY_MOODLE => array('id' => PAGE_MY_MOODLE, 'lib' => '/my/pagelib.php', 'name' => get_string('mymoodle', 'admin')), PAGE_COURSE_VIEW => array('id' => PAGE_COURSE_VIEW, 'lib' => '/lib/pagelib.php', 'name' => get_string('stickyblockscourseview', 'admin'))); // for choose_from_menu $options = array(); foreach ($pagetypes as $p) { $options[$p['id']] = $p['name']; } require_login(); require_capability('moodle/site:manageblocks', get_context_instance(CONTEXT_SYSTEM, SITEID)); // first thing to do is print the dropdown menu $strtitle = get_string('stickyblocks', 'admin'); $strheading = get_string('adminhelpstickyblocks'); if (!empty($pt)) { require_once $CFG->dirroot . $pagetypes[$pt]['lib']; define('ADMIN_STICKYBLOCKS', $pt); $PAGE = page_create_object($pt, SITEID); $blocks = blocks_setup($PAGE, BLOCKS_PINNED_TRUE); $blocks_preferred_width = bounded_number(180, blocks_preferred_width($blocks[BLOCK_POS_LEFT]), 210); $navlinks = array(array('name' => get_string('administration'), 'link' => "{$CFG->wwwroot}/{$CFG->admin}/index.php", 'type' => 'misc')); $navlinks[] = array('name' => $strtitle, 'link' => null, 'type' => 'misc'); $navigation = build_navigation($navlinks); print_header($strtitle, $strtitle, $navigation); echo '<table border="0" cellpadding="3" cellspacing="0" width="100%" id="layout-table">'; echo '<tr valign="top">'; echo '<td valign="top" style="width: ' . $blocks_preferred_width . 'px;" id="left-column">'; if (!empty($THEME->customcorners)) { print_custom_corners_start(); } blocks_print_group($PAGE, $blocks, BLOCK_POS_LEFT); if (!empty($THEME->customcorners)) { print_custom_corners_end();
$rmax = empty($THEME->block_r_max_width) ? 210 : $THEME->block_r_max_width; define('BLOCK_L_MIN_WIDTH', $lmin); define('BLOCK_L_MAX_WIDTH', $lmax); define('BLOCK_R_MIN_WIDTH', $rmin); define('BLOCK_R_MAX_WIDTH', $rmax); //_____________ new page class code ________ $pagetype = PAGE_BLOG_VIEW; $pageclass = 'page_blog'; // map our page identifier to the actual name // of the class which will be handling its operations. page_map_class($pagetype, $pageclass); // Now, create our page object. if (empty($USER->id)) { $PAGE = page_create_object($pagetype); } else { $PAGE = page_create_object($pagetype, $USER->id); } $PAGE->courseid = $courseid; $PAGE->filtertype = $filtertype; $PAGE->filterselect = $filterselect; $PAGE->tagid = $tagid; $PAGE->init_full(); //init the BlogInfo object and the courserecord object $editing = false; if ($PAGE->user_allowed_editing()) { $editing = $PAGE->user_is_editing(); } // Calculate the preferred width for left, right and center (both center positions will use the same) $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), BLOCK_L_MAX_WIDTH); $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), BLOCK_R_MAX_WIDTH); // Display the blocks and allow blocklib to handle any block action requested
function backup_course_blocks($bf, $preferences) { global $CFG; $status = true; // Read all of the block table $blocks = blocks_get_record(); $pages = array(); $pages[] = page_create_object(PAGE_COURSE_VIEW, $preferences->backup_course); if (!empty($CFG->showblocksonmodpages)) { // get course structure $course = get_record('course', 'id', $preferences->backup_course); $modinfo =& get_fast_modinfo($course); foreach ($preferences->mods as $module) { if (!$module->backup) { continue; } if (empty($modinfo->instances[$module->name])) { continue; } $pagetypes = page_import_types('mod/' . $module->name . '/'); if (empty($pagetypes)) { continue; } foreach ($pagetypes as $pagetype) { foreach ($modinfo->instances[$module->name] as $cm) { if (!empty($module->instances[$cm->instance]->backup)) { $pages[] = page_create_object($pagetype, $cm->instance); } } } } } //Blocks open tag fwrite($bf, start_tag('BLOCKS', 2, true)); foreach ($pages as $page) { if ($instances = blocks_get_by_page($page)) { //Iterate over every block foreach ($instances as $position) { foreach ($position as $instance) { //If we somehow have a block with an invalid id, skip it if (empty($blocks[$instance->blockid]->name)) { continue; } $blockname = $blocks[$instance->blockid]->name; if (!($blockobj = block_instance($blockname, $instance))) { // Invalid block continue; } // encode absolute links in block config $instance->configdata = $blockobj->get_backup_encoded_config(); //Begin Block fwrite($bf, start_tag('BLOCK', 3, true)); fwrite($bf, full_tag('ID', 4, false, $instance->id)); fwrite($bf, full_tag('NAME', 4, false, $blockname)); fwrite($bf, full_tag('PAGEID', 4, false, $instance->pageid)); fwrite($bf, full_tag('PAGETYPE', 4, false, $instance->pagetype)); fwrite($bf, full_tag('POSITION', 4, false, $instance->position)); fwrite($bf, full_tag('WEIGHT', 4, false, $instance->weight)); fwrite($bf, full_tag('VISIBLE', 4, false, $instance->visible)); fwrite($bf, full_tag('CONFIGDATA', 4, false, $instance->configdata)); // Write instance data if needed if ($blockobj->backuprestore_instancedata_used()) { fwrite($bf, start_tag('INSTANCEDATA', 4, true)); $status = $blockobj->instance_backup($bf, $preferences); fwrite($bf, end_tag('INSTANCEDATA', 4, true)); } $context = get_context_instance(CONTEXT_BLOCK, $instance->id); write_role_overrides_xml($bf, $context, 4); /// write role_assign code here write_role_assignments_xml($bf, $preferences, $context, 4); //End Block fwrite($bf, end_tag('BLOCK', 3, true)); } } } } //Blocks close tag $status = fwrite($bf, end_tag('BLOCKS', 2, true)); return $status; }
function upgrade_blocks_plugins($continueto) { global $CFG, $db; $blocktitles = array(); $invalidblocks = array(); $validblocks = array(); $notices = array(); //Count the number of blocks in db $blockcount = count_records('block'); //If there isn't records. This is the first install, so I remember it if ($blockcount == 0) { $first_install = true; } else { $first_install = false; } $site = get_site(); if (!($blocks = get_list_of_plugins('blocks', 'db'))) { error('No blocks installed!'); } include_once $CFG->dirroot . '/blocks/moodleblock.class.php'; if (!class_exists('block_base')) { error('Class block_base is not defined or file not found for /blocks/moodleblock.class.php'); } foreach ($blocks as $blockname) { if ($blockname == 'NEWBLOCK') { // Someone has unzipped the template, ignore it continue; } if (!block_is_compatible($blockname)) { // This is an old-style block //$notices[] = 'Block '. $blockname .' is not compatible with the current version of Mooodle and needs to be updated by a programmer.'; $invalidblocks[] = $blockname; continue; } $fullblock = $CFG->dirroot . '/blocks/' . $blockname; if (is_readable($fullblock . '/block_' . $blockname . '.php')) { include_once $fullblock . '/block_' . $blockname . '.php'; } else { $notices[] = 'Block ' . $blockname . ': ' . $fullblock . '/block_' . $blockname . '.php was not readable'; continue; } $oldupgrade = false; $newupgrade = false; if (@is_dir($fullblock . '/db/')) { if (@is_readable($fullblock . '/db/' . $CFG->dbtype . '.php')) { include_once $fullblock . '/db/' . $CFG->dbtype . '.php'; // defines old upgrading function $oldupgrade = true; } if (@is_readable($fullblock . '/db/upgrade.php')) { include_once $fullblock . '/db/upgrade.php'; // defines new upgrading function $newupgrade = true; } } $classname = 'block_' . $blockname; if (!class_exists($classname)) { $notices[] = 'Block ' . $blockname . ': ' . $classname . ' not implemented'; continue; } // Here is the place to see if the block implements a constructor (old style), // an init() function (new style) or nothing at all (error time). $constructor = get_class_constructor($classname); if (empty($constructor)) { // No constructor $notices[] = 'Block ' . $blockname . ': class does not have a constructor'; $invalidblocks[] = $blockname; continue; } $block = new stdClass(); // This may be used to update the db below $blockobj = new $classname(); // This is what we 'll be testing // Inherits from block_base? if (!is_subclass_of($blockobj, 'block_base')) { $notices[] = 'Block ' . $blockname . ': class does not inherit from block_base'; continue; } // OK, it's as we all hoped. For further tests, the object will do them itself. if (!$blockobj->_self_test()) { $notices[] = 'Block ' . $blockname . ': self test failed'; continue; } $block->version = $blockobj->get_version(); if (!isset($block->version)) { $notices[] = 'Block ' . $blockname . ': has no version support. It must be updated by a programmer.'; continue; } $block->name = $blockname; // The name MUST match the directory $blocktitle = $blockobj->get_title(); if ($currblock = get_record('block', 'name', $block->name)) { if ($currblock->version == $block->version) { // do nothing } else { if ($currblock->version < $block->version) { if (empty($updated_blocks)) { $strblocksetup = get_string('blocksetup'); print_header($strblocksetup, $strblocksetup, build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); } $updated_blocks = true; upgrade_log_start(); print_heading('New version of ' . $blocktitle . ' (' . $block->name . ') exists'); @set_time_limit(0); // To allow slow databases to complete the long SQL /// Run de old and new upgrade functions for the module $oldupgrade_function = $block->name . '_upgrade'; $newupgrade_function = 'xmldb_block_' . $block->name . '_upgrade'; /// First, the old function if exists $oldupgrade_status = true; if ($oldupgrade && function_exists($oldupgrade_function)) { $db->debug = true; $oldupgrade_status = $oldupgrade_function($currblock->version, $block); } else { if ($oldupgrade) { notify('Upgrade function ' . $oldupgrade_function . ' was not available in ' . $fullblock . '/db/' . $CFG->dbtype . '.php'); } } /// Then, the new function if exists and the old one was ok $newupgrade_status = true; if ($newupgrade && function_exists($newupgrade_function) && $oldupgrade_status) { $db->debug = true; $newupgrade_status = $newupgrade_function($currblock->version, $block); } else { if ($newupgrade) { notify('Upgrade function ' . $newupgrade_function . ' was not available in ' . $fullblock . '/db/upgrade.php'); } } $db->debug = false; /// Now analyze upgrade results if ($oldupgrade_status && $newupgrade_status) { // No upgrading failed // Set the block cron on upgrade $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0; // OK so far, now update the block record $block->id = $currblock->id; if (!update_record('block', $block)) { error('Could not update block ' . $block->name . ' record in block table!'); } $component = 'block/' . $block->name; if (!update_capabilities($component)) { error('Could not update ' . $block->name . ' capabilities!'); } events_update_definition($component); notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess'); } else { notify('Upgrading block ' . $block->name . ' from ' . $currblock->version . ' to ' . $block->version . ' FAILED!'); } echo '<hr />'; } else { upgrade_log_start(); error('Version mismatch: block ' . $block->name . ' can\'t downgrade ' . $currblock->version . ' -> ' . $block->version . '!'); } } } else { // block not installed yet, so install it // If it allows multiples, start with it enabled if ($blockobj->instance_allow_multiple()) { $block->multiple = 1; } // Set the block cron on install $block->cron = !empty($blockobj->cron) ? $blockobj->cron : 0; // [pj] Normally this would be inline in the if, but we need to // check for NULL (necessary for 4.0.5 <= PHP < 4.2.0) $conflictblock = array_search($blocktitle, $blocktitles); if ($conflictblock !== false && $conflictblock !== NULL) { // Duplicate block titles are not allowed, they confuse people // AND PHP's associative arrays ;) error('<strong>Naming conflict</strong>: block <strong>' . $block->name . '</strong> has the same title with an existing block, <strong>' . $conflictblock . '</strong>!'); } if (empty($updated_blocks)) { $strblocksetup = get_string('blocksetup'); print_header($strblocksetup, $strblocksetup, build_navigation(array(array('name' => $strblocksetup, 'link' => null, 'type' => 'misc'))), '', upgrade_get_javascript(), false, ' ', ' '); } $updated_blocks = true; upgrade_log_start(); print_heading($block->name); $db->debug = true; @set_time_limit(0); // To allow slow databases to complete the long SQL /// Both old .sql files and new install.xml are supported /// but we priorize install.xml (XMLDB) if present $status = false; if (file_exists($fullblock . '/db/install.xml')) { $status = install_from_xmldb_file($fullblock . '/db/install.xml'); //New method } else { if (file_exists($fullblock . '/db/' . $CFG->dbtype . '.sql')) { $status = modify_database($fullblock . '/db/' . $CFG->dbtype . '.sql'); //Old method } else { $status = true; } } $db->debug = false; if ($status) { if ($block->id = insert_record('block', $block)) { $blockobj->after_install(); $component = 'block/' . $block->name; if (!update_capabilities($component)) { notify('Could not set up ' . $block->name . ' capabilities!'); } events_update_definition($component); notify(get_string('blocksuccess', '', $blocktitle), 'notifysuccess'); echo '<hr />'; } else { error($block->name . ' block could not be added to the block list!'); } } else { error('Block ' . $block->name . ' tables could NOT be set up successfully!'); } } $blocktitles[$block->name] = $blocktitle; } if (!empty($notices)) { upgrade_log_start(); foreach ($notices as $notice) { notify($notice); } } // Finally, if we are in the first_install of BLOCKS (this means that we are // upgrading from Moodle < 1.3), put blocks in all existing courses. if ($first_install) { upgrade_log_start(); //Iterate over each course if ($courses = get_records('course')) { foreach ($courses as $course) { $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_repopulate_page($page); } } } if (!empty($CFG->siteblocksadded)) { /// This is a once-off hack to make a proper upgrade upgrade_log_start(); $page = page_create_object(PAGE_COURSE_VIEW, SITEID); blocks_repopulate_page($page); delete_records('config', 'name', 'siteblocksadded'); } upgrade_log_finish(); if (!empty($updated_blocks)) { print_continue($continueto); print_footer('none'); die; } }
/** * Process the group tag. This defines a Moodle course. * @param string $tagconents The raw contents of the XML element */ function process_group_tag($tagcontents) { global $CFG; // Process tag contents unset($group); if (preg_match('{<sourcedid>.*?<id>(.+?)</id>.*?</sourcedid>}is', $tagcontents, $matches)) { $group->coursecode = trim($matches[1]); } if (preg_match('{<description>.*?<short>(.*?)</short>.*?</description>}is', $tagcontents, $matches)) { $group->description = trim($matches[1]); } if (preg_match('{<org>.*?<orgunit>(.*?)</orgunit>.*?</org>}is', $tagcontents, $matches)) { $group->category = trim($matches[1]); } $recstatus = $this->get_recstatus($tagcontents, 'group'); //echo "<p>get_recstatus for this group returned $recstatus</p>"; if (!(strlen($group->coursecode) > 0)) { $this->log_line('Error at line ' . $line . ': Unable to find course code in \'group\' element.'); } else { // First, truncate the course code if desired if (intval($CFG->enrol_truncatecoursecodes) > 0) { $group->coursecode = $CFG->enrol_truncatecoursecodes > 0 ? substr($group->coursecode, 0, intval($CFG->enrol_truncatecoursecodes)) : $group->coursecode; } /* -----------Course aliasing is DEACTIVATED until a more general method is in place--------------- // Second, look in the course alias table to see if the code should be translated to something else if($aliases = get_field('enrol_coursealias', 'toids', 'fromid', $group->coursecode)){ $this->log_line("Found alias of course code: Translated $group->coursecode to $aliases"); // Alias is allowed to be a comma-separated list, so let's split it $group->coursecode = explode(',', $aliases); } */ // For compatibility with the (currently inactive) course aliasing, we need this to be an array $group->coursecode = array($group->coursecode); // Third, check if the course(s) exist foreach ($group->coursecode as $coursecode) { $coursecode = trim($coursecode); if (!get_field('course', 'id', 'idnumber', $coursecode)) { if (!$CFG->enrol_createnewcourses) { $this->log_line("Course {$coursecode} not found in Moodle's course idnumbers."); } else { // Create the (hidden) course(s) if not found $course = new object(); $course->fullname = $group->description; $course->shortname = $coursecode; $course->idnumber = $coursecode; $course->format = 'topics'; $course->visible = 0; // Insert default names for teachers/students, from the current language $site = get_site(); if (current_language() == $CFG->lang) { $course->teacher = $site->teacher; $course->teachers = $site->teachers; $course->student = $site->student; $course->students = $site->students; } else { $course->teacher = get_string("defaultcourseteacher"); $course->teachers = get_string("defaultcourseteachers"); $course->student = get_string("defaultcoursestudent"); $course->students = get_string("defaultcoursestudents"); } // Handle course categorisation (taken from the group.org.orgunit field if present) if (strlen($group->category) > 0) { // If the category is defined and exists in Moodle, we want to store it in that one if ($catid = get_field('course_categories', 'id', 'name', addslashes($group->category))) { $course->category = $catid; } elseif ($CFG->enrol_createnewcategories) { // Else if we're allowed to create new categories, let's create this one $newcat->name = $group->category; $newcat->visible = 0; if ($catid = insert_record('course_categories', $newcat)) { $course->category = $catid; $this->log_line("Created new (hidden) category, #{$catid}: {$newcat->name}"); } else { $this->log_line('Failed to create new category: ' . $newcat->name); } } else { // If not found and not allowed to create, stick with default $this->log_line('Category ' . $group->category . ' not found in Moodle database, so using default category instead.'); $course->category = 1; } } else { $course->category = 1; } $course->timecreated = time(); $course->startdate = time(); $course->numsections = 1; // Choose a sort order that puts us at the start of the list! $sortinfo = get_record_sql('SELECT MIN(sortorder) AS min, MAX(sortorder) AS max FROM ' . $CFG->prefix . 'course WHERE category<>0'); if (is_object($sortinfo)) { // no courses? $max = $sortinfo->max; $min = $sortinfo->min; unset($sortinfo); $course->sortorder = $min - 1; } else { $course->sortorder = 1000; } if ($course->id = insert_record('course', addslashes_object($course))) { // Setup the blocks $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_repopulate_page($page); // Return value not checked because you can always edit later $section = new object(); $section->course = $course->id; // Create a default section. $section->section = 0; $section->id = insert_record("course_sections", $section); add_to_log(SITEID, "course", "new", "view.php?id={$course->id}", "{$course->fullname} (ID {$course->id})"); $this->log_line("Created course {$coursecode} in Moodle (Moodle ID is {$course->id})"); } else { $this->log_line('Failed to create course ' . $coursecode . ' in Moodle'); } } } elseif ($recstatus == 3 && ($courseid = get_field('course', 'id', 'idnumber', $coursecode))) { // If course does exist, but recstatus==3 (delete), then set the course as hidden set_field('course', 'visible', '0', 'id', $courseid); } } // End of foreach(coursecode) } }
function create_course($course, $skip_fix_course_sortorder = 0) { global $CFG; // define a template if (!empty($CFG->enrol_db_template)) { $template = get_record("course", 'shortname', $CFG->enrol_db_template); $template = (array) $template; } else { $site = get_site(); $template = array('startdate' => time() + 3600 * 24, 'summary' => get_string("defaultcoursesummary"), 'format' => "weeks", 'password' => "", 'guest' => 0, 'numsections' => 10, 'idnumber' => '', 'cost' => '', 'newsitems' => 5, 'showgrades' => 1, 'groupmode' => 0, 'groupmodeforce' => 0, 'student' => $site->student, 'students' => $site->students, 'teacher' => $site->teacher, 'teachers' => $site->teachers); } // overlay template foreach (array_keys($template) as $key) { if (empty($course->{$key})) { $course->{$key} = $template[$key]; } } $course->category = 1; // the misc 'catch-all' category if (!empty($CFG->enrol_db_category)) { //category = 0 or undef will break moodle $course->category = $CFG->enrol_db_category; } // define the sortorder $sort = get_field_sql('SELECT COALESCE(MAX(sortorder)+1, 100) AS max ' . ' FROM ' . $CFG->prefix . 'course ' . ' WHERE category=' . $course->category); $course->sortorder = $sort; // override with local data $course->startdate = time() + 3600 * 24; $course->timecreated = time(); $course->visible = 1; // clear out id just in case unset($course->id); // truncate a few key fields $course->idnumber = substr($course->idnumber, 0, 100); $course->shortname = substr($course->shortname, 0, 100); // store it and log if ($newcourseid = insert_record("course", addslashes_object($course))) { // Set up new course $section = NULL; $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = insert_record("course_sections", $section); $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid); blocks_repopulate_page($page); // Return value no if (!$skip_fix_course_sortorder) { fix_course_sortorder(); } add_to_log($newcourseid, "course", "new", "view.php?id={$newcourseid}", "enrol/database auto-creation"); } else { trigger_error("Could not create new course {$extcourse} from from database"); notify("Serious Error! Could not create the new course!"); return false; } return $newcourseid; }
/** * Factory function page_create_object(). Called with a numeric ID for a page, it autodetects * the page type, constructs the correct object and returns it. */ function page_create_instance($instance) { page_id_and_class($id, $class); return page_create_object($id, $instance); }
function backup_course_blocks($bf, $preferences) { global $CFG; $status = true; // Read all of the block table $blocks = blocks_get_record(); $pages = array(); $pages[] = page_create_object(PAGE_COURSE_VIEW, $preferences->backup_course); // Let's see if we have to backup blocks from modules $modulerecords = get_records_sql('SELECT name, id FROM ' . $CFG->prefix . 'modules'); foreach ($preferences->mods as $module) { if (!$module->backup) { continue; } $cmods = get_records_select('course_modules', 'course = ' . $preferences->backup_course . ' AND module = ' . $modulerecords[$module->name]->id); if (empty($cmods)) { continue; } $pagetypes = page_import_types('mod/' . $module->name . '/'); if (empty($pagetypes)) { continue; } foreach ($pagetypes as $pagetype) { foreach ($cmods as $cmod) { $pages[] = page_create_object($pagetype, $cmod->instance); } } } //Blocks open tag fwrite($bf, start_tag('BLOCKS', 2, true)); while ($page = array_pop($pages)) { if ($instances = blocks_get_by_page($page)) { //Iterate over every block foreach ($instances as $position) { foreach ($position as $instance) { //If we somehow have a block with an invalid id, skip it if (empty($blocks[$instance->blockid]->name)) { continue; } //Begin Block fwrite($bf, start_tag('BLOCK', 3, true)); fwrite($bf, full_tag('ID', 4, false, $instance->id)); fwrite($bf, full_tag('NAME', 4, false, $blocks[$instance->blockid]->name)); fwrite($bf, full_tag('PAGEID', 4, false, $instance->pageid)); fwrite($bf, full_tag('PAGETYPE', 4, false, $instance->pagetype)); fwrite($bf, full_tag('POSITION', 4, false, $instance->position)); fwrite($bf, full_tag('WEIGHT', 4, false, $instance->weight)); fwrite($bf, full_tag('VISIBLE', 4, false, $instance->visible)); fwrite($bf, full_tag('CONFIGDATA', 4, false, $instance->configdata)); $context = get_context_instance(CONTEXT_BLOCK, $instance->id); write_role_overrides_xml($bf, $context, 4); /// write role_assign code here write_role_assignments_xml($bf, $preferences, $context, 4); //End Block fwrite($bf, end_tag('BLOCK', 3, true)); } } } } //Blocks close tag $status = fwrite($bf, end_tag('BLOCKS', 2, true)); return $status; }
function get_content() { global $CFG, $editing, $COURSE, $USER; if (!empty($COURSE)) { $this->courseid = $COURSE->id; } /// When displaying feeds in block, we double $CFG->block_rss_client_timeout /// so those feeds retrieved and cached by the cron() process will have a /// better chance to be used if (!empty($CFG->block_rss_client_timeout)) { $CFG->block_rss_client_timeout *= 2; } require_once $CFG->libdir . '/rsslib.php'; if ($this->content !== NULL) { return $this->content; } $this->content = new stdClass(); $this->content->text = ''; $this->content->footer = ''; if (empty($this->instance)) { // We're being asked for content without an associated instance return $this->content; } $output = ''; $rssid = -1; $display_description = false; if (isset($CFG->block_rss_client_num_entries) && is_numeric($CFG->block_rss_client_num_entries)) { $shownumentries = intval($CFG->block_rss_client_num_entries); } else { $shownumentries = 5; //default to 5 entries is not specified in admin section or instance } if (!empty($this->config)) { if (!empty($this->config->rssid)) { if (is_array($this->config->rssid)) { $rssidarray = $this->config->rssid; } else { // Make an array of the single value $rssidarray = array($this->config->rssid); } } if (!empty($this->config->display_description)) { $display_description = intval($this->config->display_description); } if (!empty($this->config->shownumentries)) { $shownumentries = intval($this->config->shownumentries); } } if (empty($this->instance->pinned)) { $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id); } else { $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context } if (has_capability('block/rss_client:createsharedfeeds', $context) || has_capability('block/rss_client:createprivatefeeds', $context)) { $page = page_create_object($this->instance->pagetype, $this->instance->pageid); //if ($page->user_allowed_editing()) { // for SUBMITTERS_ALL_ACCOUNT_HOLDERS we're going to run into trouble later if we show it and then they don't have write access to the page. if (isset($this->config)) { // This instance is configured - show Add/Edit feeds link. $script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => $USER->sesskey, 'blockaction' => 'config', 'currentaction' => 'managefeeds', 'id' => $this->courseid, 'section' => 'rss')); $output .= '<div class="info"><a title="' . get_string('feedsaddedit', 'block_rss_client') . '" href="' . $script . '">' . get_string('feedsaddedit', 'block_rss_client') . '</a></div>'; } else { // This instance has not been configured yet - show configure link? if (has_capability('block/rss_client:manageanyfeeds', $context)) { $script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => $USER->sesskey, 'blockaction' => 'config', 'currentaction' => 'configblock', 'id' => $this->courseid, 'section' => 'rss')); $output .= '<div class="info"><a title="' . get_string('feedsconfigurenewinstance', 'block_rss_client') . '" href="' . $script . '">' . get_string('feedsconfigurenewinstance', 'block_rss_client') . '</a></div>'; } } //} } // Daryl Hawes note: if count of rssidarray is greater than 1 // we should possibly display a drop down menu of selected feed titles // so user can select a single feed to view (similar to RSSFeed) if (!empty($rssidarray)) { $numids = count($rssidarray); $count = 0; foreach ($rssidarray as $rssid) { $output .= $this->get_rss_by_id($rssid, $display_description, $shownumentries, $numids > 1 ? true : false); if ($numids > 1 && $count != $numids - 1 && !empty($rssfeedstring)) { $output .= '<hr style="width=:80%" />'; } $count++; } } $this->content->text = $output; return $this->content; }
/** * Update a course and return true or false * * @param object $data - all the data needed for an entry in the 'course' table */ function update_course($data) { global $USER, $CFG; // Preprocess allowed mods $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods; unset($data->allowedmods); // Normal teachers can't change setting if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { unset($data->restrictmodules); } $movecat = false; $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category)) or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) { // can not move to new category, keep the old one unset($data->category); } elseif ($oldcourse->category != $data->category) { $movecat = true; } // Update with the new data if (update_record('course', $data)) { $course = get_record('course', 'id', $data->id); add_to_log($course->id, "course", "update", "edit.php?id={$course->id}", $course->id); // "Admins" can change allowed mods for a course if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { update_restricted_mods($course, $allowedmods); } if ($movecat) { $context = get_context_instance(CONTEXT_COURSE, $course->id); $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category); context_moved($context, $newparent); } fix_course_sortorder(); // Test for and remove blocks which aren't appropriate anymore $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_remove_inappropriate($page); // put custom role names into db $context = get_context_instance(CONTEXT_COURSE, $course->id); foreach ($data as $dname => $dvalue) { // is this the right param? $dvalue = clean_param($dvalue, PARAM_NOTAGS); if (!strstr($dname, 'role_')) { continue; } $dt = explode('_', $dname); $roleid = $dt[1]; // make up our mind whether we want to delete, update or insert if (empty($dvalue)) { delete_records('role_names', 'contextid', $context->id, 'roleid', $roleid); } else { if ($t = get_record('role_names', 'contextid', $context->id, 'roleid', $roleid)) { $t->name = $dvalue; update_record('role_names', $t); } else { $t->contextid = $context->id; $t->roleid = $roleid; $t->name = $dvalue; insert_record('role_names', $t); } } } //trigger events events_trigger('course_updated', $course); return true; } return false; }
/** * Display the resource with the course blocks. */ function display_course_blocks_start() { global $CFG; global $USER; require_once $CFG->libdir . '/blocklib.php'; require_once $CFG->libdir . '/pagelib.php'; require_once $CFG->dirroot . '/course/lib.php'; //required by some blocks $PAGE = page_create_object(PAGE_COURSE_VIEW, $this->course->id); $this->PAGE = $PAGE; $pageblocks = blocks_setup($PAGE); $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210); /// Print the page header $edit = optional_param('edit', -1, PARAM_BOOL); if ($edit != -1 and $PAGE->user_allowed_editing()) { $USER->editing = $edit; } $morenavlinks = array($this->strresources => 'index.php?id=' . $this->course->id, $this->resource->name => ''); $PAGE->print_header($this->course->shortname . ': %fullname%', $morenavlinks); echo '<table id="layout-table"><tr>'; if (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $PAGE->user_is_editing()) { echo '<td style="width: ' . $blocks_preferred_width . 'px;" id="left-column">'; if (!empty($THEME->customcorners)) { print_custom_corners_start(); } blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT); if (!empty($THEME->customcorners)) { print_custom_corners_end(); } echo '</td>'; } echo '<td id="middle-column">'; if (!empty($THEME->customcorners)) { print_custom_corners_start(); } echo '<div id="resource">'; }
/** * Sets class $edit_controls var with correct block manipulation links. * * @uses $CFG * @uses $USER * @param stdObject $options ? * @todo complete documenting this function. Define $options. */ function _add_edit_controls($options) { global $CFG, $USER, $PAGE; if (empty($this->instance->pinned)) { $context = get_context_instance(CONTEXT_BLOCK, $this->instance->id); } else { $context = get_context_instance(CONTEXT_SYSTEM); // pinned blocks do not have own context } // context for site or course, i.e. participant list etc // check to see if user can edit site or course blocks. // blocks can appear on other pages such as mod and blog pages... switch ($this->instance->pagetype) { case 'course-view': if (!has_capability('moodle/site:manageblocks', $context)) { return null; } break; default: break; } if (!isset($this->str)) { $this->str->delete = get_string('delete'); $this->str->moveup = get_string('moveup'); $this->str->movedown = get_string('movedown'); $this->str->moveright = get_string('moveright'); $this->str->moveleft = get_string('moveleft'); $this->str->hide = get_string('hide'); $this->str->show = get_string('show'); $this->str->configure = get_string('configuration'); $this->str->assignroles = get_string('assignroles', 'role'); } // RTL support - exchange right and left arrows if (right_to_left()) { $rightarrow = 'left.gif'; $leftarrow = 'right.gif'; } else { $rightarrow = 'right.gif'; $leftarrow = 'left.gif'; } $movebuttons = '<div class="commands">'; if ($this->instance->visible) { $icon = '/t/hide.gif'; $title = $this->str->hide; } else { $icon = '/t/show.gif'; $title = $this->str->show; } if (empty($this->instance->pageid)) { $this->instance->pageid = 0; } if (!empty($PAGE->type) and $this->instance->pagetype == $PAGE->type and $this->instance->pageid == $PAGE->id) { $page = $PAGE; } else { $page = page_create_object($this->instance->pagetype, $this->instance->pageid); } $script = $page->url_get_full(array('instanceid' => $this->instance->id, 'sesskey' => $USER->sesskey)); if (empty($this->instance->pinned)) { $movebuttons .= '<a class="icon roles" title="' . $this->str->assignroles . '" href="' . $CFG->wwwroot . '/' . $CFG->admin . '/roles/assign.php?contextid=' . $context->id . '">' . '<img src="' . $CFG->pixpath . '/i/roles.gif" alt="' . $this->str->assignroles . '" /></a>'; } if ($this->user_can_edit()) { $movebuttons .= '<a class="icon hide" title="' . $title . '" href="' . $script . '&blockaction=toggle">' . '<img src="' . $CFG->pixpath . $icon . '" alt="' . $title . '" /></a>'; } if ($options & BLOCK_CONFIGURE && $this->user_can_edit()) { $movebuttons .= '<a class="icon edit" title="' . $this->str->configure . '" href="' . $script . '&blockaction=config">' . '<img src="' . $CFG->pixpath . '/t/edit.gif" alt="' . $this->str->configure . '" /></a>'; } if ($this->user_can_addto($page)) { $movebuttons .= '<a class="icon delete" title="' . $this->str->delete . '" href="' . $script . '&blockaction=delete">' . '<img src="' . $CFG->pixpath . '/t/delete.gif" alt="' . $this->str->delete . '" /></a>'; } if ($options & BLOCK_MOVE_LEFT) { $movebuttons .= '<a class="icon left" title="' . $this->str->moveleft . '" href="' . $script . '&blockaction=moveleft">' . '<img src="' . $CFG->pixpath . '/t/' . $leftarrow . '" alt="' . $this->str->moveleft . '" /></a>'; } if ($options & BLOCK_MOVE_UP) { $movebuttons .= '<a class="icon up" title="' . $this->str->moveup . '" href="' . $script . '&blockaction=moveup">' . '<img src="' . $CFG->pixpath . '/t/up.gif" alt="' . $this->str->moveup . '" /></a>'; } if ($options & BLOCK_MOVE_DOWN) { $movebuttons .= '<a class="icon down" title="' . $this->str->movedown . '" href="' . $script . '&blockaction=movedown">' . '<img src="' . $CFG->pixpath . '/t/down.gif" alt="' . $this->str->movedown . '" /></a>'; } if ($options & BLOCK_MOVE_RIGHT) { $movebuttons .= '<a class="icon right" title="' . $this->str->moveright . '" href="' . $script . '&blockaction=moveright">' . '<img src="' . $CFG->pixpath . '/t/' . $rightarrow . '" alt="' . $this->str->moveright . '" /></a>'; } $movebuttons .= '</div>'; $this->edit_controls = $movebuttons; }
include $CFG->dirroot . '/course/externservercourse.php'; if (function_exists('extern_server_course')) { if ($extern_url = extern_server_course($course)) { redirect($extern_url); } } } require_once $CFG->dirroot . '/calendar/lib.php'; /// This is after login because it needs $USER add_to_log($course->id, 'course', 'view', "view.php?id={$course->id}", "{$course->id}"); $course->format = clean_param($course->format, PARAM_ALPHA); if (!file_exists($CFG->dirroot . '/course/format/' . $course->format . '/format.php')) { $course->format = 'weeks'; // Default format is weeks } $PAGE = page_create_object(PAGE_COURSE_VIEW, $course->id); $pageblocks = blocks_setup($PAGE, BLOCKS_PINNED_BOTH); if (!isset($USER->editing)) { $USER->editing = 0; } if ($PAGE->user_allowed_editing()) { if ($edit == 1 and confirm_sesskey()) { $USER->editing = 1; } else { if ($edit == 0 and confirm_sesskey()) { $USER->editing = 0; if (!empty($USER->activitycopy) && $USER->activitycopycourse == $course->id) { $USER->activitycopy = false; $USER->activitycopycourse = NULL; } }
function restore_create_blocks($restore, $backup_block_format, $blockinfo, $xml_file) { global $CFG; $status = true; blocks_delete_all_on_page(PAGE_COURSE_VIEW, $restore->course_id); if (empty($backup_block_format)) { // This is a backup from Moodle < 1.5 if (empty($blockinfo)) { // Looks like it's from Moodle < 1.3. Let's give the course default blocks... $newpage = page_create_object(PAGE_COURSE_VIEW, $restore->course_id); blocks_repopulate_page($newpage); } else { // We just have a blockinfo field, this is a legacy 1.4 or 1.3 backup $blockrecords = get_records_select('block', '', '', 'name, id'); $temp_blocks_l = array(); $temp_blocks_r = array(); @(list($temp_blocks_l, $temp_blocks_r) = explode(':', $blockinfo)); $temp_blocks = array(BLOCK_POS_LEFT => explode(',', $temp_blocks_l), BLOCK_POS_RIGHT => explode(',', $temp_blocks_r)); foreach ($temp_blocks as $blockposition => $blocks) { $blockweight = 0; foreach ($blocks as $blockname) { if (!isset($blockrecords[$blockname])) { // We don't know anything about this block! continue; } $blockinstance = new stdClass(); // Remove any - prefix before doing the name-to-id mapping if (substr($blockname, 0, 1) == '-') { $blockname = substr($blockname, 1); $blockinstance->visible = 0; } else { $blockinstance->visible = 1; } $blockinstance->blockid = $blockrecords[$blockname]->id; $blockinstance->pageid = $restore->course_id; $blockinstance->pagetype = PAGE_COURSE_VIEW; $blockinstance->position = $blockposition; $blockinstance->weight = $blockweight; if (!($status = insert_record('block_instance', $blockinstance))) { $status = false; } ++$blockweight; } } } } else { if ($backup_block_format == 'instances') { $status = restore_create_block_instances($restore, $xml_file); } } return $status; }
function fastcreatecourse_ex($hcategory, $course, $header, $validate) { if (!is_array($course) || !is_array($header) || !is_array($validate)) { return -2; } global $CFG; // declaring as static prevents object pointers being continually created and destroyed, saving time in theory static $courseid; static $mysqlresource1; static $mysqlresource2; static $mysqlresource3; static $mysqlresource4; static $dcomma; // Creating SQL for composite fields static $dtopics; static $dtopicno; static $dtopicname; static $dteachers; static $dteacherno; static $dteacherdata; // Dynamically Create Query Based on number of headings excluding Teacher[1,2,...] and Topic[1,2,...] // Added for increased functionality with newer versions of moodle // Author: Ashley Gooding & Cole Spicer static $tempstring; $query = 'INSERT INTO `' . $CFG->prefix . 'course` (`category`,'; foreach ($header as $i => $col) { $col = strtolower($col); if (preg_match(TOPIC_FIELD, $col) || preg_match(TEACHER_FIELD, $col) || $col == 'category' || $col == 'template') { continue; } $query = $query . '`' . $col . '`,'; } $query = $query . '`modinfo`) VALUES (' . $hcategory . ','; foreach ($header as $i => $col) { $col = strtolower($col); if (preg_match(TOPIC_FIELD, $col) || preg_match(TEACHER_FIELD, $col) || $col == 'category' || $col == 'template') { continue; } if ($col == 'expirythreshold') { $course[$col] = $course[$col] * 86400; } $temparray = explode(',', $validate[$col][1]); if ($validate[$col][0] == 1 || $validate[$col][0] == 4 && !checkisint($temparray[0])) { //String or Domain with strings $query = $query . '' . mystr($course[$col]) . ', '; } else { $query = $query . '' . $course[$col] . ', '; } } $query = $query . ' \'\');'; // End Dynamic Query if (!($mysqlresource2 = mysql_query($query))) { return -2; } $courseid = mysql_insert_id(); if (isset($course['template']) && $course['template'] != '') { if (!($mysqlresource6 = mysql_query('SELECT `id` FROM `' . $CFG->prefix . 'course` WHERE `shortname`=\'' . $course['template'] . '\';'))) { return -7; } if (!mysql_num_rows($mysqlresource6)) { return -7; } $row = mysql_fetch_row($mysqlresource6); $id = $row[0]; if (!($mysqlresource7 = mysql_query(' INSERT INTO `' . $CFG->prefix . 'block_instance` ( `blockid` , `pageid` , `pagetype` , `position` , `weight` , `visible` , `configdata` ) SELECT `blockid` , ' . $courseid . ', `pagetype` , `position` , `weight` , `visible` , `configdata` FROM `' . $CFG->prefix . 'block_instance` WHERE `pageid` = ' . $id . ';'))) { return -8; } } else { $page = page_create_object(PAGE_COURSE_VIEW, $courseid); blocks_repopulate_page($page); // Setup blocks } $dtopics = ''; // String concatenation for topic INSERT $dcomma = false; // Should we add a comma before the next item? if (isset($course['topics'])) { // Any topic headings specified ? foreach ($course['topics'] as $dtopicno => $dtopicname) { if ($dtopicno <= $course['numsections']) { // Avoid overflowing topic headings if ($dcomma == true) { $dtopics .= ','; } else { $dcomma = true; } $dtopics .= '(' . $courseid . ',' . mystr($dtopicno) . ',' . mystr($dtopicname) . ',\'\',\'1\')'; } } } if (!isset($course['topics'][0])) { // Ensure at least default topic section exists if ($dcomma == true) { $dtopics .= ','; } else { $dcomma = true; } $dtopics .= '(\'' . $courseid . '\',\'0\',\'\',\'\',\'1\');'; } else { $dtopics .= ';'; } if (!($mysqlresource3 = mysql_query('INSERT INTO `' . $CFG->prefix . 'course_sections` (`course`,`section`,`summary`,`sequence`,`visible`) VALUES ' . $dtopics))) { return -3; } $dteachers = ''; // String concatenation for topic INSERT $dcomma = false; // Should we add a comma before the next item? // SELECT id FROM mdl_role WHERE name = blah // use that id and change insert to: // mdl_role_assignments // roleid contextid userid timemodified modifierid enrol // courseshit 0 'manual' // If SELECT id... doesnt work (returns false or contians no items) then throw error $roleid; if (!($context = get_context_instance(CONTEXT_COURSE, $courseid))) { return -6; } if (isset($course['teachers_enrol']) && count($course['teachers_enrol']) > 0) { // Any teachers specified? foreach ($course['teachers_enrol'] as $dteacherno => $dteacherdata) { if (isset($dteacherdata['_account'])) { if ($dcomma == true) { $dteachers .= ','; } else { $dcomma = true; } if (!($mysqlresource5 = mysql_query('SELECT `id` FROM `' . $CFG->prefix . 'role` WHERE `shortname`=\'' . $dteacherdata['_role'] . '\';'))) { return -5; } if (!mysql_num_rows($mysqlresource5)) { return -5; } $row = mysql_fetch_row($mysqlresource5); $dteachers .= '(' . $row[0] . ',' . $context->id . ',' . $dteacherdata['_account'] . ',' . $course['timecreated'] . ',0,\'manual\');'; } } if ($dteachers != '') { if (!($mysqlresource4 = mysql_query('INSERT INTO `' . $CFG->prefix . 'role_assignments` (`roleid`,`contextid`,`userid`,`timemodified`,`modifierid`,`enrol`) VALUES ' . $dteachers))) { return -4; } } } return 1; }
function create_course($course_ext, $skip_fix_course_sortorder = 0) { global $CFG; // override defaults with template course if (!empty($CFG->enrol_ldap_template)) { $course = get_record("course", 'shortname', $CFG->enrol_ldap_template); unset($course->id); // so we are clear to reinsert the record unset($course->sortorder); } else { // set defaults $course = new object(); $course->student = get_string('defaultcoursestudent'); $course->students = get_string('defaultcoursestudents'); $course->teacher = get_string('defaultcourseteacher'); $course->teachers = get_string('defaultcourseteachers'); $course->format = 'topics'; } // override with required ext data $course->idnumber = $course_ext[$CFG->enrol_ldap_course_idnumber][0]; $course->fullname = $course_ext[$CFG->enrol_ldap_course_fullname][0]; $course->shortname = $course_ext[$CFG->enrol_ldap_course_shortname][0]; if (empty($course->idnumber) || empty($course->fullname) || empty($course->shortname)) { // we are in trouble! error_log("Cannot create course: missing required data from the LDAP record!"); error_log(var_export($course, true)); return false; } $course->summary = empty($CFG->enrol_ldap_course_summary) || empty($course_ext[$CFG->enrol_ldap_course_summary][0]) ? '' : $course_ext[$CFG->enrol_ldap_course_summary][0]; if (!empty($CFG->enrol_ldap_category)) { // optional ... but ensure it is set! $course->category = $CFG->enrol_ldap_category; } if ($course->category == 0) { // must be avoided as it'll break moodle $course->category = 1; // the misc 'catch-all' category } // define the sortorder (yuck) $sort = get_record_sql('SELECT MAX(sortorder) AS max, 1 FROM ' . $CFG->prefix . 'course WHERE category=' . $course->category); $sort = $sort->max; $sort++; $course->sortorder = $sort; // override with local data $course->startdate = time(); $course->timecreated = time(); $course->visible = 1; $course = addslashes_recursive($course); // store it and log if ($newcourseid = insert_record("course", $course)) { // Set up new course $section = new object(); $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = insert_record("course_sections", $section); $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid); blocks_repopulate_page($page); // Return value no if (!$skip_fix_course_sortorder) { fix_course_sortorder(); } add_to_log($newcourseid, "course", "new", "view.php?id={$newcourseid}", "enrol/ldap auto-creation"); } else { error_log("Could not create new course from LDAP from DN:" . $course_ext['dn']); notify("Serious Error! Could not create the new course!"); return false; } return $newcourseid; }
public function importCourses($xml, $catID, $catName) { //DOM parsing and validating $dom = new DOMDocument(); $dom->loadXML($xml); if (!@$dom->schemaValidate($this->courses_schema)) { throw new MoodlePluginException("ERROR, not valid XML data...", 2); } //Check if category exists if (!record_exists($this->categories_table, "id", $catID, "name", $catName)) { throw new MoodlePluginException("ERROR, category not found...", 1); } $this->error[$this->courses_table] = array(); //Create new courses $count = 0; $courses = $dom->getElementsByTagName("course"); foreach ($courses as $course) { $newcourse = null; while ($child = $course->firstChild) { $course->removeChild($child); switch ($key = $child->nodeName) { case "id": //ID must be assigned later break; case "category": $newcourse->{$key} = $catID; break; default: $newcourse->{$key} = $child->textContent; break; } } //Try to give an ID to the new course and then insert it in database if ($newcourseid = insert_record($this->courses_table, $newcourse)) { $page = page_create_object(PAGE_COURSE_VIEW, $newcourseid); blocks_repopulate_page($page); // Set up new course $section = NULL; $section->course = $newcourseid; // Create a default section. $section->section = 0; $section->id = insert_record($this->course_sections_table, $section); $count++; } else { array_push($this->error[$this->courses_table], $newcourse->shortname); } } return $count; }
/** * @deprecated since Moodle 2.0 * Do not use this any more. The global $PAGE is automatically created for you. * If you need custom behaviour, you should just set properties of that object. * @param integer $instance legacy page instance id. * @return the global $PAGE object. */ function page_create_instance($instance) { global $PAGE; return page_create_object($PAGE->pagetype, $instance); }
/** * Module Blocked Format for Moodle * * @author DFWiki LABS * @author Marc Alier i Forment * @author David Castro, Ferran Recio, Jordi Piguillem, UPC, * and members of DFWikiteam listed at http://morfeo.upc.edu/crom * @version $Id: web.lib.php,v 1.5 2008/05/05 09:10:43 pigui Exp $ * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package Activity_Format */ function wiki_header() { global $COURSE, $CFG, $WS; //define block sizes define('BLOCK_L_MIN_WIDTH', 100); define('BLOCK_L_MAX_WIDTH', 210); define('BLOCK_R_MIN_WIDTH', 100); define('BLOCK_R_MAX_WIDTH', 210); $edit = optional_param('edit', NULL, PARAM_ALPHA); //This structure is used to use blocks //Standard blocks: $dfwiki = wiki_param('dfwiki'); //$PAGE = page_create_instance($dfwiki->id); $PAGE = page_create_object('mod-wiki-view', $dfwiki->id); //little patch: if body class is a subtype od mod-wiki, class is mod-wiki if (substr($PAGE->body_class, 0, 8) == 'mod-wiki') { $PAGE->body_class = 'mod-wiki'; } wiki_page_info('PAGE', $PAGE); //Needed function to make blocks work properly $pageblocks = blocks_setup($PAGE); wiki_page_info('pageblocks', $pageblocks); //Function that checks the edit permissions of the wiki wiki_check_edition($PAGE, $edit); //setup the module /// Print the page header if ($COURSE->category) { $navigation = "<a href=\"../../course/view.php?id={$COURSE->id}\">{$COURSE->shortname}</a> ->"; } //get names in both singular and plural $strdfwikis = get_string("modulenameplural", 'wiki'); $strdfwiki = get_string("modulename", 'wiki'); $PAGE->print_header($COURSE->shortname . ': %fullname%'); /// Print the main part of the page $prop = new stdClass(); $prop->class = "course-content"; wiki_div_start($prop); // course wrapper start //to work out the default widths need to check all blocks $preferred_width_left = optional_param('preferred_width_left', blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), PARAM_INT); //preferred_width_left sizes //should be between BLOCK_x_MAX_WIDTH and BLOCK_x_MIN_WIDTH. $preferred_width_left = min($preferred_width_left, BLOCK_L_MAX_WIDTH); $preferred_width_left = max($preferred_width_left, BLOCK_L_MIN_WIDTH); $cm = wiki_param('cm'); $context = get_context_instance(CONTEXT_MODULE, $cm->id); //shows a specific topic if (has_capability('mod/wiki:editawiki', $context) and isset($marker) and confirm_sesskey()) { $COURSE->marker = $marker; if (!set_field("course", "marker", $marker, "id", $COURSE->id)) { error("Could not mark that topic for this course"); } } //load strings $streditsummary = get_string('editsummary'); $stradd = get_string('add'); $stractivities = get_string('activities'); $strshowalltopics = get_string('showalltopics'); $strtopic = get_string('topic'); $strgroups = get_string('groups'); $strgroupmy = get_string('groupmy'); //checks if the user is editing $editing = $PAGE->user_is_editing(); //load editing strings if ($editing) { $strstudents = moodle_strtolower($COURSE->students); $strtopichide = get_string('topichide', '', $strstudents); $strtopicshow = get_string('topicshow', '', $strstudents); $strmarkthistopic = get_string('markthistopic'); $strmarkedthistopic = get_string('markedthistopic'); $strmoveup = get_string('moveup'); $strmovedown = get_string('movedown'); } //--------------------------------------------- INTERFACES BEGINS HERE /// Layout the whole page as three big columns. /// The left column ... //checks if there are blocks to place on the left-hand side if (!empty($CFG->showblocksonmodpages) && (blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $editing)) { $prop = new stdClass(); $prop->id = "layout-table"; $prop->idtd = "left-column"; $prop->classtd = "blockcourse"; wiki_table_start($prop); $prop = new stdClass(); $prop->width = $preferred_width_left . 'px'; wiki_table_start($prop); blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT); wiki_table_end(); $prop = new stdClass(); $prop->id = "middle-column"; wiki_change_column($prop); } else { $prop = new stdClass(); $prop->id = "layout-table"; $prop->idtd = "middle-column"; wiki_table_start($prop); } /// Start main column //central block title //print_heading_block(get_string('wiki','wiki'), 'outline'); echo "<br />"; print_box($dfwiki->intro, "generalbox", "intro"); //begin the content table $prop = new stdClass(); $prop->class = "topics"; $prop->width = "100%"; wiki_table_start($prop); //print_tabs //TODO: clean it when all functionalities are parts global $CFG; //this function is the responsable of printing the content of the module. $dfcontent = wiki_param('dfcontent'); $dfcontentf = wiki_param('dfcontentf'); if (isset($dfcontent) && $dfcontent >= 0 && $dfcontent < count($dfcontentf)) { //we won't print tabs cause is an special situation (this comprobation will be removed when all ead are passed to parts) } else { wiki_print_tabs(); } }
$course->sortorder = 1000; } $course->requested = 1; unset($course->reason); unset($course->id); $teacherid = $course->requester; unset($course->requester); $course->teacher = get_string("defaultcourseteacher"); $course->teachers = get_string("defaultcourseteachers"); $course->student = get_string("defaultcoursestudent"); $course->students = get_string("defaultcoursestudents"); if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) { $course->restrictmodules = 1; } if ($courseid = insert_record("course", $course)) { $page = page_create_object(PAGE_COURSE_VIEW, $courseid); blocks_repopulate_page($page); // Return value not checked because you can always edit later add_teacher($teacherid, $courseid); $course->id = $courseid; if (!empty($CFG->restrictmodulesfor) && $CFG->restrictmodulesfor != 'none' && !empty($CFG->restrictbydefault)) { // if we're all or requested we're ok. $allowedmods = explode(',', $CFG->defaultallowedmodules); update_restricted_mods($course, $allowedmods); } delete_records('course_request', 'id', $approve); $success = 1; } if (!empty($success)) { $user = get_record('user', 'id', $teacherid); $a->name = $course->fullname;
/** * Update a course and return true or false * * @param object $data - all the data needed for an entry in the 'course' table */ function update_course($data) { global $USER, $CFG; // Preprocess allowed mods $allowedmods = empty($data->allowedmods) ? array() : $data->allowedmods; unset($data->allowedmods); // Normal teachers can't change setting if (!has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { unset($data->restrictmodules); } $movecat = false; $oldcourse = get_record('course', 'id', $data->id); // should not fail, already tested above if (!has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $oldcourse->category)) or !has_capability('moodle/course:create', get_context_instance(CONTEXT_COURSECAT, $data->category))) { // can not move to new category, keep the old one unset($data->category); } elseif ($oldcourse->category != $data->category) { $movecat = true; } // Update with the new data if (update_record('course', $data)) { $course = get_record('course', 'id', $data->id); add_to_log($course->id, "course", "update", "edit.php?id={$course->id}", $course->id); // "Admins" can change allowed mods for a course if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { update_restricted_mods($course, $allowedmods); } if ($movecat) { $context = get_context_instance(CONTEXT_COURSE, $course->id); $newparent = get_context_instance(CONTEXT_COURSECAT, $course->category); context_moved($context, $newparent); } fix_course_sortorder(); // Test for and remove blocks which aren't appropriate anymore $page = page_create_object(PAGE_COURSE_VIEW, $course->id); blocks_remove_inappropriate($page); // Save any custom role names. save_local_role_names($course->id, $data); // Trigger events events_trigger('course_updated', $course); return true; } return false; }
if (get_moodle_cookie() == '') { set_moodle_cookie('nobody'); // To help search for cookies on login page } if (!empty($USER->id)) { add_to_log(SITEID, 'course', 'view', 'view.php?id=' . SITEID, SITEID); } if (empty($CFG->langmenu)) { $langmenu = ''; } else { $currlang = current_language(); $langs = get_list_of_languages(); $langlabel = get_accesshide(get_string('language')); $langmenu = popup_form($CFG->wwwroot . '/index.php?lang=', $langs, 'chooselang', $currlang, '', '', '', true, 'self', $langlabel); } $PAGE = page_create_object(PAGE_COURSE_VIEW, SITEID); $pageblocks = blocks_setup($PAGE); $editing = $PAGE->user_is_editing(); $preferred_width_left = bounded_number(BLOCK_L_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), BLOCK_L_MAX_WIDTH); $preferred_width_right = bounded_number(BLOCK_R_MIN_WIDTH, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), BLOCK_R_MAX_WIDTH); print_header($SITE->fullname, $SITE->fullname, 'home', '', '<meta name="description" content="' . strip_tags(format_text($SITE->summary, FORMAT_HTML)) . '" />', true, '', user_login_string($SITE) . $langmenu); ?> <table id="layout-table" summary="layout"> <tr> <?php $lt = empty($THEME->layouttable) ? array('left', 'middle', 'right') : $THEME->layouttable; foreach ($lt as $column) { switch ($column) { case 'left':
if ($nodefaultresponse) { // Don't display feedback redirect("{$CFG->wwwroot}/mod/lesson/view.php?id={$cm->id}&pageid={$newpageid}"); } /// Set Messages // This is the warning msg for teachers to inform them that cluster and unseen does not work while logged in as a teacher if (has_capability('mod/lesson:manage', $context) and lesson_display_teacher_warning($lesson->id)) { $warningvars->cluster = get_string("clusterjump", "lesson"); $warningvars->unseen = get_string("unseenpageinbranch", "lesson"); lesson_set_message(get_string("teacherjumpwarning", "lesson", $warningvars)); } // Inform teacher that s/he will not see the timer if ($lesson->timed and has_capability('mod/lesson:manage', $context)) { lesson_set_message(get_string("teachertimerwarning", "lesson")); } // Report attempts remaining if ($attemptsremaining != 0) { lesson_set_message(get_string('attemptsremaining', 'lesson', $attemptsremaining)); } // Report if max attempts reached if ($maxattemptsreached != 0) { lesson_set_message('(' . get_string("maximumnumberofattemptsreached", "lesson") . ')'); } $PAGE = page_create_object('mod-lesson-view', $lesson->id); $PAGE->set_lessonpageid($page->id); $pageblocks = blocks_setup($PAGE); $leftcolumnwidth = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_LEFT]), 210); $rightcolumnwidth = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), 210); /// Print the header, heading and tabs $PAGE->print_header(); include dirname(__FILE__) . '/continue.html';