public function cron()
 {
     global $DB;
     $this->run_profiler();
     // Get the instances of the block
     $instances = $DB->get_records('block_instances', array('blockname' => 'itutor_profiler'));
     foreach ($instances as $instance) {
         $block = block_instance('itutor_profiler', $instance);
         $courses = $DB->get_records('course', array());
         foreach ($courses as $course) {
             $this->run_alerter($course);
         }
     }
 }
Example #2
0
 /**
  * This function makes all the necessary calls to {@link restore_decode_content_links_worker()}
  * function in order to decode contents of this block from the backup 
  * format to destination site/course in order to mantain inter-activities 
  * working in the backup/restore process. 
  * 
  * This is called from {@link restore_decode_content_links()} function in the restore process.
  *
  * NOTE: There is no block instance when this method is called.
  *
  * @param object $restore Standard restore object
  * @return boolean
  **/
 function decode_content_links_caller($restore)
 {
     global $CFG;
     if ($restored_blocks = get_records_select("backup_ids", "table_name = 'block_instance' AND backup_code = {$restore->backup_unique_code} AND new_id > 0", "", "new_id")) {
         $restored_blocks = implode(',', array_keys($restored_blocks));
         $sql = "SELECT bi.*\n                      FROM {$CFG->prefix}block_instance bi\n                           JOIN {$CFG->prefix}block b ON b.id = bi.blockid\n                     WHERE b.name = 'incrementalclient' AND bi.id IN ({$restored_blocks})";
         if ($instances = get_records_sql($sql)) {
             foreach ($instances as $instance) {
                 $blockobject = block_instance('incrementalclient', $instance);
                 $blockobject->instance_config_commit($blockobject->pinned);
             }
         }
     }
     return true;
 }
Example #3
0
 /**
  * This function makes all the necessary calls to {@link restore_decode_content_links_worker()}
  * function in order to decode contents of this block from the backup 
  * format to destination site/course in order to mantain inter-activities 
  * working in the backup/restore process. 
  * 
  * This is called from {@link restore_decode_content_links()} function in the restore process.
  *
  * NOTE: There is no block instance when this method is called.
  *
  * @param object $restore Standard restore object
  * @return boolean
  **/
 function decode_content_links_caller($restore)
 {
     global $CFG, $DB;
     if ($restored_blocks = $DB->get_records_select("backup_ids", "table_name = 'block_instance' AND backup_code = ? AND new_id > 0", array($restore->backup_unique_code), "", "new_id")) {
         $restored_blocks = implode(',', array_keys($restored_blocks));
         $sql = "SELECT bi.*\n                      FROM {block_instance} bi\n                           JOIN {block} b ON b.id = bi.blockid\n                     WHERE b.name = 'html' AND bi.id IN ({$restored_blocks})";
         if ($instances = $DB->get_records_sql($sql)) {
             foreach ($instances as $instance) {
                 $blockobject = block_instance('html', $instance);
                 $blockobject->config->text = restore_decode_absolute_links($blockobject->config->text);
                 $blockobject->config->text = restore_decode_content_links_worker($blockobject->config->text, $restore);
                 $blockobject->instance_config_commit($blockobject->pinned);
             }
         }
     }
     return true;
 }
Example #4
0
File: lib.php Project: dg711/moodle
function my_copy_page($userid, $private = MY_PAGE_PRIVATE, $pagetype = 'my-index')
{
    global $DB;
    if ($customised = $DB->get_record('my_pages', array('userid' => $userid, 'private' => $private))) {
        return $customised;
        // We're done!
    }
    // Get the system default page
    if (!($systempage = $DB->get_record('my_pages', array('userid' => null, 'private' => $private)))) {
        return false;
        // error
    }
    // Clone the basic system page record
    $page = clone $systempage;
    unset($page->id);
    $page->userid = $userid;
    $page->id = $DB->insert_record('my_pages', $page);
    // Clone ALL the associated blocks as well
    $systemcontext = context_system::instance();
    $usercontext = context_user::instance($userid);
    $blockinstances = $DB->get_records('block_instances', array('parentcontextid' => $systemcontext->id, 'pagetypepattern' => $pagetype, 'subpagepattern' => $systempage->id));
    foreach ($blockinstances as $instance) {
        $originalid = $instance->id;
        unset($instance->id);
        $instance->parentcontextid = $usercontext->id;
        $instance->subpagepattern = $page->id;
        $instance->id = $DB->insert_record('block_instances', $instance);
        $blockcontext = context_block::instance($instance->id);
        // Just creates the context record
        $block = block_instance($instance->blockname, $instance);
        if (!$block->instance_copy($originalid)) {
            debugging("Unable to copy block-specific data for original block instance: {$originalid}\n                to new block instance: {$instance->id}", DEBUG_DEVELOPER);
        }
    }
    // FIXME: block position overrides should be merged in with block instance
    //$blockpositions = $DB->get_records('block_positions', array('subpage' => $page->name));
    //foreach($blockpositions as $positions) {
    //    $positions->subpage = $page->name;
    //    $DB->insert_record('block_positions', $tc);
    //}
    return $page;
}
Example #5
0
 protected function specific_definition($mform)
 {
     global $CFG, $DB, $COURSE;
     $options = array();
     $options[1] = get_string('yes', 'block_map');
     $options[0] = get_string('no', 'block_map');
     // Fields for editing HTML block title and contents.
     $mform->addElement('header', 'configheader', get_string('blocksettings', 'block'));
     $mform->addElement('text', 'config_title', get_string('settings:titlemap', 'block_map'));
     $mform->setType('config_title', PARAM_TEXT);
     $mform->setDefault('config_title', get_string('pluginname', 'block_map'));
     $mform->addElement('select', 'config_sitemode', get_string('settings:sitemode', 'block_map'), $options);
     $mform->setDefault('config_sitemode', $CFG->map_sitemode);
     $mform->addElement('select', 'config_activate', get_string('settings:activate', 'block_map'), $options);
     $mform->setDefault('config_activate', $CFG->map_activate);
     $mform->addElement('select', 'config_editmarks', get_string('settings:editmarks', 'block_map'), $options);
     $mform->setDefault('config_editmarks', $CFG->map_editmarks);
     $mform->addElement('select', 'config_loadmarkdin', get_string('settings:loadmarkdin', 'block_map'), $options);
     $mform->setDefault('config_loadmarkdin', $CFG->map_loadmarkdin);
     $mform->addElement('select', 'config_publickmap', get_string('settings:publickmap', 'block_map'), $options);
     $mform->setDefault('config_publickmap', $CFG->map_publickmap);
     $mform->addElement('text', 'config_latitude', get_string('settings:latitude', 'block_map'));
     $mform->setType('config_latitude', PARAM_TEXT);
     $mform->setDefault('config_latitude', $CFG->map_latitude);
     $mform->addElement('text', 'config_longitude', get_string('settings:longitude', 'block_map'));
     $mform->setType('config_longitude', PARAM_TEXT);
     $mform->setDefault('config_longitude', $CFG->map_longitude);
     $mform->addElement('hidden', 'config_coursename', $COURSE->fullname);
     $mform->addElement('hidden', 'config_courseid', $COURSE->id);
     $data = $DB->get_records("block_instances", array("blockname" => "map"));
     $datares = array();
     $cm = array();
     $datares[0] = get_string("settings:shareown", "block_map");
     foreach ($data as $data_) {
         $cm = block_instance('map', $data_);
         $cm->config = unserialize(base64_decode($cm->instance->configdata));
         $datares[$cm->config->courseid] = $cm->config->coursename;
     }
     $mform->addElement('select', 'config_shareid', get_string('settings:share', 'block_map'), $datares);
     //$mform->setDefault('config_shareid', '');
 }
function content_unlock_get_block_conditions_text($unlock_system)
{
    global $DB;
    $conditions_text = array();
    $unlock_system_block_conditions = $DB->get_records('content_unlock_condition', array('unlocksystemid' => $unlock_system->id));
    foreach ($unlock_system_block_conditions as $unlock_system_block_condition) {
        if ($unlock_system_block_condition->type == 0) {
            $block_info = null;
            if (isset($unlock_system_block_condition->prpointsystemid)) {
                $block_instance_id = $DB->get_field('points_system', 'blockinstanceid', array('id' => $unlock_system_block_condition->prpointsystemid));
                $block_info = $DB->get_record('block_instances', array('id' => $block_instance_id));
                $points_system_name = $DB->get_field('points_system', 'name', array('id' => $unlock_system_block_condition->prpointsystemid));
            } else {
                $block_info = $DB->get_record('block_instances', array('id' => $unlock_system_block_condition->prblockid));
            }
            $instance = block_instance('game_points', $block_info);
            $conditions_text[] = get_string('block_conditions_reach', 'block_game_content_unlock') . ' ' . $unlock_system_block_condition->prpoints . ' ' . get_string('block_conditions_points', 'block_game_content_unlock') . ' (' . ($unlock_system_block_condition->prgrupal ? get_string('block_conditions_grupal', 'block_game_content_unlock') : get_string('block_conditions_individual', 'block_game_content_unlock')) . ') ' . get_string('block_conditions_on', 'block_game_content_unlock') . ' ' . (isset($unlock_system_block_condition->prblockid) ? get_string('block_conditions_block', 'block_game_content_unlock') . ' ' . $instance->title : get_string('block_conditions_pointsystem', 'block_game_content_unlock') . ' ' . (empty($points_system_name) ? $unlock_system_block_condition->prpointsystemid : $points_system_name . ' (' . $unlock_system_block_condition->prpointsystemid . ')') . ' (' . get_string('block_conditions_block', 'block_game_content_unlock') . ' ' . $instance->title . ')');
        } else {
            if ($unlock_system_block_condition->type == 1) {
                $condition_unlock_system = $DB->get_record('content_unlock_system', array('id' => $unlock_system_block_condition->urunlocksystemid));
                $course = $DB->get_record('course', array('id' => $this->page->course->id));
                $info = get_fast_modinfo($course);
                $cm = $info->get_cm($condition_unlock_system->coursemoduleid);
                $block_info = $DB->get_record('block_instances', array('id' => $condition_unlock_system->blockinstanceid));
                $instance = block_instance('game_content_unlock', $block_info);
                $conditions_text[] = ($unlock_system_block_condition->urmust ? get_string('block_conditions_have', 'block_game_content_unlock') : get_string('block_conditions_havenot', 'block_game_content_unlock')) . ' ' . ($condition_unlock_system->coursemodulevisibility ? get_string('block_conditions_unlocked', 'block_game_content_unlock') : get_string('block_conditions_locked', 'block_game_content_unlock')) . ' ' . get_string('block_conditions_resource', 'block_game_content_unlock') . ' ' . $cm->name . ' (' . get_string('block_conditions_block', 'block_game_content_unlock') . ' ' . $instance->title . ')';
            } else {
                $condition_achievement = $DB->get_record('achievements', array('id' => $unlock_system_block_condition->arachievementid));
                $block_info = $DB->get_record('block_instances', array('id' => $condition_achievement->blockinstanceid));
                $instance = block_instance('game_achievements', $block_info);
                $conditions_text[] = get_string('block_conditions_reach', 'block_game_content_unlock') . ' ' . get_string('block_conditions_achievement', 'block_game_content_unlock') . ' ' . (isset($condition_achievement->name) ? $condition_achievement->name . ' (' . $condition_achievement->id . ')' : $condition_achievement->id) . ' (' . get_string('block_conditions_block', 'block_game_content_unlock') . ' ' . $instance->title . ')';
            }
        }
    }
    return implode(' ' . ($unlock_system->connective == AND_CONNECTIVE ? get_string('block_conditions_and', 'block_game_content_unlock') : get_string('block_conditions_or', 'block_game_content_unlock')) . ' ', $conditions_text);
}
function backup_encode_absolute_links($content)
{
    global $CFG, $preferences;
    /// MDL-14072: Prevent NULLs, empties and numbers to be processed by the
    /// heavy interlinking. Just a few cpu cycles saved.
    if ($content === NULL) {
        return NULL;
    } else {
        if ($content === '') {
            return '';
        } else {
            if (is_numeric($content)) {
                return $content;
            }
        }
    }
    //Use one static variable to cache all the require_once calls that,
    //under PHP5 seems to increase load too much, and we are requiring
    //them here thousands of times (one per content). MDL-8700.
    //Once fixed by PHP, we'll delete this hack
    static $includedfiles;
    if (!isset($includedfiles)) {
        $includedfiles = array();
    }
    //Check if we support unicode modifiers in regular expressions. Cache it.
    static $unicoderegexp;
    if (!isset($unicoderegexp)) {
        $unicoderegexp = @preg_match('/\\pL/u', 'a');
        // This will fail silenty, returning false,
    }
    // if regexp libraries don't support unicode
    //Check if preferences is ok. If it isn't set, we are
    //in a scheduled_backup to we are able to get a copy
    //from CFG->backup_preferences
    if (!isset($preferences)) {
        $mypreferences = $CFG->backup_preferences;
    } else {
        //We are in manual backups so global preferences must exist!!
        $mypreferences = $preferences;
    }
    //First, we check for every call to file.php inside the course
    $search = array($CFG->wwwroot . '/file.php/' . $mypreferences->backup_course, $CFG->wwwroot . '/file.php?file=/' . $mypreferences->backup_course, $CFG->wwwroot . '/file.php?file=%2f' . $mypreferences->backup_course, $CFG->wwwroot . '/file.php?file=%2F' . $mypreferences->backup_course);
    $replace = array('$@FILEPHP@$', '$@FILEPHP@$', '$@FILEPHP@$', '$@FILEPHP@$');
    $result = str_replace($search, $replace, $content);
    // Now we look for any '$@FILEPHP@$' URLs, replacing:
    //     - slashes and %2F by $@SLASH@$
    //     - &forcedownload=1 &forcedownload=1 and ?forcedownload=1 by $@FORCEDOWNLOAD@$
    // This way, backup contents will be neutral and independent of slasharguments configuration. MDL-18799
    // Based in $unicoderegexp, decide the regular expression to use
    if ($unicoderegexp) {
        //We can use unicode modifiers
        $search = '/(\\$@FILEPHP@\\$)((?:(?:\\/|%2f|%2F))(?:(?:\\([-;:@#&=\\pL0-9\\$~_.+!*\',]*?\\))|[-;:@#&=\\pL0-9\\$~_.+!*\',]|%[a-fA-F0-9]{2}|\\/)*)?(\\?(?:(?:(?:\\([-;:@#&=\\pL0-9\\$~_.+!*\',]*?\\))|[-;:@#&=?\\pL0-9\\$~_.+!*\',]|%[a-fA-F0-9]{2}|\\/)*))?(?<![,.;])/u';
    } else {
        //We cannot ue unicode modifiers
        $search = '/(\\$@FILEPHP@\\$)((?:(?:\\/|%2f|%2F))(?:(?:\\([-;:@#&=a-zA-Z0-9\\$~_.+!*\',]*?\\))|[-;:@#&=a-zA-Z0-9\\$~_.+!*\',]|%[a-fA-F0-9]{2}|\\/)*)?(\\?(?:(?:(?:\\([-;:@#&=a-zA-Z0-9\\$~_.+!*\',]*?\\))|[-;:@#&=?a-zA-Z0-9\\$~_.+!*\',]|%[a-fA-F0-9]{2}|\\/)*))?(?<![,.;])/';
    }
    $result = preg_replace_callback($search, 'backup_process_filephp_uses', $result);
    foreach ($mypreferences->mods as $name => $info) {
        /// We only include the corresponding backuplib.php if it hasn't been included before
        /// This will save some load under PHP5. MDL-8700.
        /// Once fixed by PHP, we'll delete this hack
        if (!in_array($name, $includedfiles)) {
            include_once "{$CFG->dirroot}/mod/{$name}/backuplib.php";
            $includedfiles[] = $name;
        }
        //Check if the xxxx_encode_content_links exists
        $function_name = $name . "_encode_content_links";
        if (function_exists($function_name)) {
            $result = $function_name($result, $mypreferences);
        }
    }
    // For the current course format call its encode_content_links method (if it exists)
    static $format_function_name;
    if (!isset($format_function_name)) {
        $format_function_name = false;
        if ($format = get_field('course', 'format', 'id', $mypreferences->backup_course)) {
            if (file_exists("{$CFG->dirroot}/course/format/{$format}/backuplib.php")) {
                include_once "{$CFG->dirroot}/course/format/{$format}/backuplib.php";
                $function_name = $format . '_encode_format_content_links';
                if (function_exists($function_name)) {
                    $format_function_name = $function_name;
                }
            }
        }
    }
    // If the above worked - then we have a function to call
    if ($format_function_name) {
        $result = $format_function_name($result, $mypreferences);
    }
    // For each block, call its encode_content_links method.
    // This encodes forexample links to blocks/something/viewphp?id=666
    // that are stored in other activities.
    static $blockobjects = null;
    if (!isset($blockobjects)) {
        $blockobjects = array();
        if ($blocks = get_records('block', 'visible', 1)) {
            foreach ($blocks as $block) {
                if ($blockobject = block_instance($block->name)) {
                    $blockobjects[] = $blockobject;
                }
            }
        }
    }
    foreach ($blockobjects as $blockobject) {
        $result = $blockobject->encode_content_links($result, $mypreferences);
    }
    // Finally encode some well-know links to course
    $result = backup_course_encode_links($result, $mypreferences);
    if ($result != $content) {
        debugging('<br /><hr />' . s($content) . '<br />changed to<br />' . s($result) . '<hr /><br />');
    }
    return $result;
}
 /**
  * @see lib/moodleform#definition()
  */
 public function definition()
 {
     global $CFG, $COURSE, $DB, $PAGE;
     $mform = $this->_form;
     $modinfo = $this->_customdata['modinfo'];
     $course = $this->_customdata['course'];
     $activitytype = $this->_customdata['activitytype'];
     $coursehasavailability = !empty($CFG->enableavailability);
     $coursehascompletion = !empty($CFG->enablecompletion) && !empty($course->enablecompletion);
     // Context instance of the course.
     $coursecontext = context_course::instance($course->id);
     // Store current activity type.
     $mform->addElement('hidden', 'activitytype', $activitytype);
     $mform->setType('activitytype', PARAM_PLUGIN);
     // Add action button to the top of the form.
     $addactionbuttons = false;
     $this->add_action_buttons();
     // Course start date.
     $mform->addElement('header', 'coursestartdateheader', get_string('coursestartdateheader', 'report_editdates'));
     $mform->setExpanded('coursestartdateheader', false);
     $mform->addElement('date_selector', 'coursestartdate', get_string('startdate'));
     $mform->addHelpButton('coursestartdate', 'startdate');
     $mform->setDefault('coursestartdate', $course->startdate);
     // If user is not capable, make it read only.
     if (!has_capability('moodle/course:update', $coursecontext)) {
         $mform->hardFreeze('coursestartdate');
     } else {
         $addactionbuttons = true;
     }
     // Var to count the number of elements in the course/sections.
     // It will be used to decide whether to show save action button
     // at the bottom of the form page.
     $elementadded = 0;
     // Default -1 to display header for 0th section.
     $prevsectionnum = -1;
     // Cycle through all the sections in the course.
     $cms = $modinfo->get_cms();
     $sections = $modinfo->get_section_info_all();
     foreach ($sections as $sectionnum => $section) {
         $ismodadded = false;
         $sectionname = '';
         // Skip if section isn't visible to the user.
         if (!$section->uservisible) {
             continue;
         }
         // New section, create header.
         if ($prevsectionnum != $sectionnum) {
             $sectionname = get_section_name($course, $section);
             $headername = 'section' . $sectionnum . 'header';
             $mform->addElement('header', $headername, $sectionname);
             $mform->setExpanded($headername, false);
             $prevsectionnum = $sectionnum;
         }
         if ($coursehasavailability && $section->availability) {
             // If there are retricted access date settings.
             if (strpos($section->availability, '"type":"date"') !== false) {
                 $editsettingurl = new moodle_url('/course/editsection.php', array('id' => $section->id));
                 $editsettingurltext = html_writer::tag('a', get_string('editrestrictedaccess', 'report_editdates'), array('href' => $editsettingurl->out(false), 'target' => '_blank'));
                 $mform->addElement('static', '', get_string('sectionhasrestrictedaccess', 'report_editdates', get_section_name($course, $section)), $editsettingurltext);
             }
         }
         // Cycle through each module in a section.
         if (isset($modinfo->sections[$sectionnum])) {
             foreach ($modinfo->sections[$sectionnum] as $cmid) {
                 $cm = $cms[$cmid];
                 // No need to display/continue if this module is not visible to user.
                 if (!$cm->uservisible) {
                     continue;
                 }
                 // If activity filter is on, then filter module by activity type.
                 if ($activitytype && $cm->modname != $activitytype) {
                     continue;
                 }
                 // Check if the user has capability to edit this module settings.
                 $modulecontext = context_module::instance($cm->id);
                 $ismodreadonly = !has_capability('moodle/course:manageactivities', $modulecontext);
                 // Display activity name.
                 $iconmarkup = html_writer::empty_tag('img', array('src' => $cm->get_icon_url(), 'class' => 'activityicon', 'alt' => ''));
                 $stractivityname = html_writer::tag('strong', $iconmarkup . $cm->name);
                 $mform->addElement('static', 'modname' . $cm->id, $stractivityname);
                 $isdateadded = false;
                 // Call get_settings method for the acitivity/module.
                 // Get instance of the mod's date exractor class.
                 $mod = report_editdates_mod_date_extractor::make($cm->modname, $course);
                 if ($mod && ($cmdatesettings = $mod->get_settings($cm))) {
                     // Added activity name on the form.
                     foreach ($cmdatesettings as $cmdatetype => $cmdatesetting) {
                         $elname = 'date_mod_' . $cm->id . '_' . $cmdatetype;
                         $mform->addElement($cmdatesetting->type, $elname, $cmdatesetting->label, array('optional' => $cmdatesetting->isoptional, 'step' => $cmdatesetting->getstep));
                         $mform->setDefault($elname, $cmdatesetting->currentvalue);
                         if ($ismodreadonly) {
                             $mform->hardFreeze($elname);
                         }
                         $elementadded++;
                         $isdateadded = true;
                     }
                 }
                 if ($coursehasavailability && $cm->availability) {
                     // If there are retricted access date settings.
                     if (strpos($cm->availability, '"type":"date"') !== false) {
                         $editsettingurl = new moodle_url('/course/modedit.php', array('update' => $cm->id));
                         $editsettingurltext = html_writer::tag('a', get_string('editrestrictedaccess', 'report_editdates'), array('href' => $editsettingurl->out(false), 'target' => '_blank'));
                         $mform->addElement('static', '', get_string('hasrestrictedaccess', 'report_editdates', $cm->name), $editsettingurltext);
                     }
                 }
                 // Completion tracking.
                 if ($coursehascompletion && $cm->completion) {
                     $elname = 'date_mod_' . $cm->id . '_completionexpected';
                     $mform->addElement('date_selector', $elname, get_string('completionexpected', 'completion'), array('optional' => true));
                     $mform->addHelpButton($elname, 'completionexpected', 'completion');
                     $mform->setDefault($elname, $cm->completionexpected);
                     if ($ismodreadonly) {
                         $mform->hardFreeze($elname);
                     }
                     $elementadded++;
                     $isdateadded = true;
                 }
                 if ($isdateadded) {
                     $ismodadded = true;
                     $addactionbuttons = true;
                 } else {
                     $mform->removeElement('modname' . $cm->id);
                 }
             }
             // End of modules loop.
             if (!$ismodadded && $mform->elementExists($sectionname)) {
                 $mform->removeElement($sectionname);
             }
         }
     }
     // End of sections loop.
     // Fetching all the blocks added directly under the course.
     // That is, parentcontextid = coursecontextid.
     $courseblocks = $DB->get_records('block_instances', array('parentcontextid' => $coursecontext->id));
     // Check capability of current user.
     $canmanagesiteblocks = has_capability('moodle/site:manageblocks', $coursecontext);
     $anyblockadded = false;
     if ($courseblocks) {
         // Header for blocks.
         $mform->addElement('header', 'blockdatesection');
         // Iterate though blocks array.
         foreach ($courseblocks as $blockid => $block) {
             $blockdatextrator = report_editdates_block_date_extractor::make($block->blockname, $course);
             if ($blockdatextrator) {
                 // Create the block instance.
                 $blockobj = block_instance($block->blockname, $block, $PAGE);
                 // If get_settings returns a valid array.
                 if ($blockdatesettings = $blockdatextrator->get_settings($blockobj)) {
                     $anyblockadded = true;
                     $addactionbuttons = true;
                     // Adding block's Title on page.
                     $mform->addElement('static', 'blocktitle', $blockobj->title);
                     foreach ($blockdatesettings as $blockdatetype => $blockdatesetting) {
                         $elname = 'date_block_' . $block->id . '_' . $blockdatetype;
                         // Add element.
                         $mform->addElement($blockdatesetting->type, $elname, $blockdatesetting->label, array('optional' => $blockdatesetting->isoptional, 'step' => $blockdatesetting->getstep));
                         $mform->setDefault($elname, $blockdatesetting->currentvalue);
                         if (!$canmanagesiteblocks || !$blockobj->user_can_edit()) {
                             $mform->hardFreeze($elname);
                         }
                         $elementadded++;
                     }
                 }
             }
         }
     }
     if (!$anyblockadded && $mform->elementExists('blockdatesection')) {
         $mform->removeElement('blockdatesection');
     }
     // Adding submit/cancel buttons @ the end of the form.
     if ($addactionbuttons && $elementadded > 0) {
         $this->add_action_buttons();
     } else {
         // Remove top action button.
         $mform->removeElement('buttonar');
     }
 }
Example #9
0
function restore_create_block_instances($restore, $xml_file)
{
    global $CFG;
    $status = true;
    //Check it exists
    if (!file_exists($xml_file)) {
        $status = false;
    }
    //Get info from xml
    if ($status) {
        $info = restore_read_xml_blocks($restore, $xml_file);
    }
    if (empty($info->instances)) {
        return $status;
    }
    // First of all, iterate over the blocks to see which distinct pages we have
    // in our hands and arrange the blocks accordingly.
    $pageinstances = array();
    foreach ($info->instances as $instance) {
        //pagetype and pageid black magic, we have to handle the case of blocks for the
        //course, blocks from other pages in that course etc etc etc.
        if ($instance->pagetype == PAGE_COURSE_VIEW) {
            // This one's easy...
            $instance->pageid = $restore->course_id;
        } else {
            if (!empty($CFG->showblocksonmodpages)) {
                $parts = explode('-', $instance->pagetype);
                if ($parts[0] == 'mod') {
                    if (!$restore->mods[$parts[1]]->restore) {
                        continue;
                    }
                    $getid = backup_getid($restore->backup_unique_code, $parts[1], $instance->pageid);
                    if (empty($getid->new_id)) {
                        // Failed, perhaps the module was not included in the restore  MDL-13554
                        continue;
                    }
                    $instance->pageid = $getid->new_id;
                } else {
                    // Not invented here ;-)
                    continue;
                }
            } else {
                // do not restore activity blocks if disabled
                continue;
            }
        }
        if (!isset($pageinstances[$instance->pagetype])) {
            $pageinstances[$instance->pagetype] = array();
        }
        if (!isset($pageinstances[$instance->pagetype][$instance->pageid])) {
            $pageinstances[$instance->pagetype][$instance->pageid] = array();
        }
        $pageinstances[$instance->pagetype][$instance->pageid][] = $instance;
    }
    $blocks = get_records_select('block', 'visible = 1', '', 'name, id, multiple');
    // For each type of page we have restored
    foreach ($pageinstances as $thistypeinstances) {
        // For each page id of that type
        foreach ($thistypeinstances as $thisidinstances) {
            $addedblocks = array();
            $maxweights = array();
            // For each block instance in that page
            foreach ($thisidinstances as $instance) {
                if (!isset($blocks[$instance->name])) {
                    //We are trying to restore a block we don't have...
                    continue;
                }
                //If we have already added this block once and multiples aren't allowed, disregard it
                if (!$blocks[$instance->name]->multiple && isset($addedblocks[$instance->name])) {
                    continue;
                }
                //If its the first block we add to a new position, start weight counter equal to 0.
                if (empty($maxweights[$instance->position])) {
                    $maxweights[$instance->position] = 0;
                }
                //If the instance weight is greater than the weight counter (we skipped some earlier
                //blocks most probably), bring it back in line.
                if ($instance->weight > $maxweights[$instance->position]) {
                    $instance->weight = $maxweights[$instance->position];
                }
                //Add this instance
                $instance->blockid = $blocks[$instance->name]->id;
                // This will only be set if we come from 1.7 and above backups
                //  Also, must do this before insert (insert_record unsets id)
                if (!empty($instance->id)) {
                    $oldid = $instance->id;
                } else {
                    $oldid = 0;
                }
                if ($instance->id = insert_record('block_instance', $instance)) {
                    // Create block instance
                    if (!($blockobj = block_instance($instance->name, $instance))) {
                        $status = false;
                        break;
                    }
                    // Run the block restore if needed
                    if ($blockobj->backuprestore_instancedata_used()) {
                        // Get restore information
                        $data = backup_getid($restore->backup_unique_code, 'block_instance', $oldid);
                        $data->new_id = $instance->id;
                        // For completeness
                        if (!$blockobj->instance_restore($restore, $data)) {
                            $status = false;
                            break;
                        }
                    }
                    // Save oldid after block restore process because info will be over-written with blank string
                    if ($oldid) {
                        backup_putid($restore->backup_unique_code, "block_instance", $oldid, $instance->id);
                    }
                } else {
                    $status = false;
                    break;
                }
                //Get an object for the block and tell it it's been restored so it can update dates
                //etc. if necessary
                if ($blockobj = block_instance($instance->name, $instance)) {
                    $blockobj->after_restore($restore);
                }
                //Now we can increment the weight counter
                ++$maxweights[$instance->position];
                //Keep track of block types we have already added
                $addedblocks[$instance->name] = true;
            }
        }
    }
    return $status;
}
/*
 * ---------------------------------------------------------------------------------------------------------------------
 *
 * This file is part of the Course Menu block for Moodle
 *
 * The Course Menu block for Moodle software package is Copyright � 2008 onwards NetSapiensis AB and is provided under
 * the terms of the GNU GENERAL PUBLIC LICENSE Version 3 (GPL). This program is free software: you can redistribute it
 * and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation,
 * either version 3 of the License, or (at your option) any later version.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU
 * General Public License as published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version. This program is distributed in the hope that
 * it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.
 *
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public
 * License along with this program.
 * If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------------------------------------------------------
 */
defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) {
    require_once 'lib/settingslib.php';
    $block = block_instance('course_menu');
    $settings->add(new admin_setting_configtext('block_course_menu_trimlength', get_string('trimlength', 'block_course_menu'), '', block_course_menu::DEFAULT_TRIM_LENGTH, PARAM_INT, 11));
    $settings->add(new admin_setting_configtext('block_course_menu_sitetitle', get_string('namesitelevel', 'block_course_menu'), get_string('namesiteleveldescription', 'block_course_menu'), block_course_menu::DEFAULT_SITE_LEVEL_TITLE));
    $settings->add(new admin_setting_configcolourpicker('block_course_menu_docked_background', get_string('dockedbg', 'block_course_menu'), get_string('dockedbgdesc', 'block_course_menu'), block_course_menu::DEFAULT_DOCKED_BG));
    $settings->add(new block_cm_admin_setting_confightml('global_config', '', '', '', $block));
}
Example #11
0
 /**
  *  runs the survey at the specified time interval
  * @param bool $manual
  * @uses $CFG
  * @uses $DB
  */
 function cron($manual = false)
 {
     global $CFG, $DB;
     $now = time();
     $sql = "SELECT * FROM {block_instances}\n                WHERE blockname = 'enrolsurvey' ";
     // ***TBD***
     $block_instances = $DB->get_records_sql($sql);
     if (!empty($block_instances)) {
         foreach ($block_instances as $survey) {
             $block = block_instance('enrolsurvey', $survey);
             if (!empty($block->config) && !empty($block->config->cron_time)) {
                 if (!isset($block->config->last_cron)) {
                     $block->config->last_cron = 0;
                 }
                 if ($block->config->last_cron + $block->config->cron_time <= $now) {
                     $block->config->last_cron = $now;
                     $DB->delete_records('block_enrolsurvey_taken', array('blockinstanceid' => $survey->id));
                     $block->instance_config_save($block->config);
                 }
             }
         }
     }
     return true;
 }
Example #12
0
collatorlib::asort($blocknames);
foreach ($blocknames as $blockid => $strblockname) {
    $block = $blocks[$blockid];
    $blockname = $block->name;
    if (!file_exists("{$CFG->dirroot}/blocks/{$blockname}/block_{$blockname}.php")) {
        $blockobject = false;
        $strblockname = '<span class="notifyproblem">' . $strblockname . ' (' . get_string('missingfromdisk') . ')</span>';
        $plugin = new stdClass();
        $plugin->version = $block->version;
    } else {
        $plugin = new stdClass();
        $plugin->version = '???';
        if (file_exists("{$CFG->dirroot}/blocks/{$blockname}/version.php")) {
            include "{$CFG->dirroot}/blocks/{$blockname}/version.php";
        }
        if (!($blockobject = block_instance($block->name))) {
            $incompatible[] = $block;
            continue;
        }
    }
    $delete = '<a href="blocks.php?delete=' . $blockid . '&amp;sesskey=' . sesskey() . '">' . $strdelete . '</a>';
    $settings = '';
    // By default, no configuration
    if ($blockobject and $blockobject->has_config()) {
        $blocksettings = admin_get_root()->locate('blocksetting' . $block->name);
        if ($blocksettings instanceof admin_externalpage) {
            $settings = '<a href="' . $blocksettings->url . '">' . get_string('settings') . '</a>';
        } else {
            if ($blocksettings instanceof admin_settingpage) {
                $settings = '<a href="' . $CFG->wwwroot . '/' . $CFG->admin . '/settings.php?section=blocksetting' . $block->name . '">' . $strsettings . '</a>';
            } else {
Example #13
0
 /**
  * Create a set of new block instance from a record array
  *
  * @param array $birecords An array of block instance records
  * @return array An array of instantiated block_instance objects
  */
 protected function create_block_instances($birecords)
 {
     $results = array();
     foreach ($birecords as $record) {
         if ($blockobject = block_instance($record->blockname, $record, $this->page)) {
             $results[] = $blockobject;
         }
     }
     return $results;
 }
Example #14
0
/**
 * Returns the language string for the given plugin.
 *
 * @param string $plugin the plugin code name
 * @param string $type the type of plugin (mod, block, filter)
 * @return string The plugin language string
 */
function get_plugin_name($plugin, $type = 'mod')
{
    $plugin_name = '';
    switch ($type) {
        case 'mod':
            $plugin_name = get_string('modulename', $plugin);
            break;
        case 'blocks':
            $plugin_name = get_string('blockname', "block_{$plugin}");
            if (empty($plugin_name) || $plugin_name == '[[blockname]]') {
                if (($block = block_instance($plugin)) !== false) {
                    $plugin_name = $block->get_title();
                } else {
                    $plugin_name = "[[{$plugin}]]";
                }
            }
            break;
        case 'filter':
            $plugin_name = trim(get_string('filtername', $plugin));
            if (empty($plugin_name) or $plugin_name == '[[filtername]]') {
                $textlib = textlib_get_instance();
                $plugin_name = $textlib->strtotitle($plugin);
            }
            break;
        default:
            $plugin_name = $plugin;
            break;
    }
    return $plugin_name;
}
Example #15
0
/**
 * Returns the language string for the given plugin.
 *
 * @param string $plugin the plugin code name
 * @param string $type the type of plugin (mod, block, filter)
 * @return string The plugin language string
 */
function get_plugin_name($plugin, $type = 'mod')
{
    $plugin_name = '';
    switch ($type) {
        case 'mod':
            $plugin_name = get_string('modulename', $plugin);
            break;
        case 'blocks':
            $plugin_name = get_string('pluginname', "block_{$plugin}");
            if (empty($plugin_name) || $plugin_name == '[[pluginname]]') {
                if (($block = block_instance($plugin)) !== false) {
                    $plugin_name = $block->get_title();
                } else {
                    $plugin_name = "[[{$plugin}]]";
                }
            }
            break;
        case 'filter':
            $plugin_name = filter_get_name('filter/' . $plugin);
            break;
        default:
            $plugin_name = $plugin;
            break;
    }
    return $plugin_name;
}
Example #16
0
*/
require_once '../../config.php';
header('Content-Type: text/css', true);
header("X-Content-Type-Options: nosniff");
// for IE
header('Cache-Control: no-cache');
if (!isloggedin()) {
    die;
}
/* Get block instance config data outside of it's class
   https://moodle.org/mod/forum/discuss.php?d=129799
   Also check configdata encoding in C:\...\blocks\moodleblock.class.php
*/
$instance_id = required_param('instance_id', PARAM_INT);
$data = $DB->get_record('block_instances', array('id' => $instance_id), '*', MUST_EXIST);
$block_instance = block_instance('accessibility', $data);
// test it in all languages?
// if (!$block_instance) error...
// READ USER SETTINGS
// ================================================
// First, check the session to see if the user's overridden the default/saved setting
$options = $DB->get_record('block_accessibility', array('userid' => $USER->id));
// NOTE: User settings priority: 1. $USER session, 2. database
// check for fontsize user setting
if (!empty($USER->fontsize)) {
    $fontsize = $USER->fontsize;
} else {
    if (!empty($options->fontsize)) {
        $fontsize = $options->fontsize;
    }
}
Example #17
0
/**
 * Same functionality as blocks_execute_url_action()
 * Handle all block actions ourselves.
 *
 * @param boolean $redirect (Optional) Redirect after action
 * @return void
 **/
function page_blocks_execute_url_action($redirect = true)
{
    global $CFG, $COURSE, $PAGE;
    $pageitemid = optional_param('pageitemid', 0, PARAM_INT);
    $blockaction = optional_param('blockaction', '', PARAM_ALPHA);
    // Reasons to stop right meow
    if (empty($blockaction) || !$PAGE->user_allowed_editing() || !confirm_sesskey()) {
        return;
    }
    // Make sure if we have a valid pageitem.
    if ($pageitemid and !($pageitem = get_record('format_page_items', 'id', $pageitemid))) {
        return;
    }
    switch ($blockaction) {
        case 'config':
            if (empty($pageitem->blockinstance) and !empty($pageitem->cmid)) {
                // Its a module - go to module update
                redirect("{$CFG->wwwroot}/course/mod.php?update={$pageitem->cmid}&amp;sesskey=" . sesskey());
            } else {
                if (!empty($pageitem->blockinstance)) {
                    // Its a block instance - allow core routine to handle
                    redirect($PAGE->url_build('instanceid', $pageitem->blockinstance, 'blockaction', 'config', 'sesskey', sesskey()));
                } else {
                    error('Invalid page item to configure');
                }
            }
            break;
        case 'toggle':
            $update = new stdClass();
            $update->id = $pageitem->id;
            if (empty($pageitem->visible)) {
                $update->visible = 1;
            } else {
                $update->visible = 0;
            }
            update_record('format_page_items', $update);
            break;
        case 'delete':
            page_block_delete($pageitem);
            break;
        case 'moveup':
            page_block_move($pageitem, $pageitem->position, $pageitem->sortorder - 1);
            break;
        case 'movedown':
            page_block_move($pageitem, $pageitem->position, $pageitem->sortorder + 1);
            break;
        case 'moveright':
            $destposition = $PAGE->blocks_move_position($pageitem, BLOCK_MOVE_RIGHT);
            $destweight = page_get_next_weight($pageitem->pageid, $destposition);
            page_block_move($pageitem, $destposition, $destweight);
            break;
        case 'moveleft':
            $destposition = $PAGE->blocks_move_position($pageitem, BLOCK_MOVE_LEFT);
            $destweight = page_get_next_weight($pageitem->pageid, $destposition);
            page_block_move($pageitem, $destposition, $destweight);
            break;
        case 'addmod':
            // Right now, modules are added differently
            $instance = required_param('instance', PARAM_INT);
            $record = new stdClass();
            $record->pageid = $PAGE->formatpage->id;
            $record->cmid = $instance;
            $record->blockinstance = 0;
            $record->position = $PAGE->blocks_default_position();
            $record->sortorder = page_get_next_weight($record->pageid, $record->position);
            insert_record('format_page_items', $record);
            break;
        case 'add':
            // Add a block instance and a pageitem
            $blockid = required_param('blockid', PARAM_INT);
            $block = blocks_get_record($blockid);
            if (empty($block) or !$block->visible) {
                break;
            }
            if (!block_method_result($block->name, 'user_can_addto', $PAGE)) {
                break;
            }
            // Add a block instance if one does not already exist or if the block allows multiple block instances
            $exists = record_exists('block_instance', 'pageid', $PAGE->get_id(), 'pagetype', $PAGE->get_type(), 'blockid', $blockid);
            if ($block->multiple || !$exists) {
                // Get the next weight value NOTE: hard code left position
                $weight = get_record_sql('SELECT 1, MAX(weight) + 1 ' . sql_as() . ' nextfree
                                            FROM ' . $CFG->prefix . 'block_instance
                                           WHERE pageid = ' . $PAGE->get_id() . '
                                             AND pagetype = \'' . $PAGE->get_type() . '\'
                                             AND position = \'' . BLOCK_POS_LEFT . '\'');
                if (empty($weight->nextfree)) {
                    $weight->nextfree = 0;
                }
                $newinstance = new stdClass();
                $newinstance->blockid = $blockid;
                $newinstance->pageid = $PAGE->get_id();
                $newinstance->pagetype = $PAGE->get_type();
                $newinstance->position = BLOCK_POS_LEFT;
                // Make sure we keep them all in same column
                $newinstance->weight = $weight->nextfree;
                $newinstance->visible = 1;
                $newinstance->configdata = '';
                $instanceid = $newinstance->id = insert_record('block_instance', $newinstance);
                if ($newinstance and $obj = block_instance($block->name, $newinstance)) {
                    // Return value ignored
                    $obj->instance_create();
                }
            } else {
                if ($exists) {
                    // Get the existing blockinstance as the block only allows one instance.
                    $instanceid = get_field('block_instance', 'id', 'pageid', $PAGE->get_id(), 'pagetype', $PAGE->get_type(), 'blockid', $blockid);
                }
            }
            if (!empty($instanceid)) {
                // Create a new page item that links to the instance
                $record = new stdClass();
                $record->pageid = $PAGE->formatpage->id;
                $record->cmid = 0;
                $record->blockinstance = $instanceid;
                $record->position = $PAGE->blocks_default_position();
                $record->sortorder = page_get_next_weight($record->pageid, $record->position);
                insert_record('format_page_items', $record);
            }
            break;
    }
    if ($redirect) {
        // In order to prevent accidental duplicate actions, redirect to a page with a clean url
        redirect($PAGE->url_get_full());
    }
}
/**
 * Extracts the relevant capabilities given a contextid.
 * All case based, example an instance of forum context.
 * Will fetch all forum related capabilities, while course contexts
 * Will fetch all capabilities
 * @param object context
 * @return array();
 *
 *  capabilities
 * `name` varchar(150) NOT NULL,
 * `captype` varchar(50) NOT NULL,
 * `contextlevel` int(10) NOT NULL,
 * `component` varchar(100) NOT NULL,
 */
function fetch_context_capabilities($context)
{
    global $CFG;
    $sort = 'ORDER BY contextlevel,component,name';
    // To group them sensibly for display
    switch ($context->contextlevel) {
        case CONTEXT_SYSTEM:
            // all
            $SQL = "SELECT *\n                      FROM {$CFG->prefix}capabilities";
            break;
        case CONTEXT_USER:
            $extracaps = array('moodle/grade:viewall');
            foreach ($extracaps as $key => $value) {
                $extracaps[$key] = "'{$value}'";
            }
            $extra = implode(',', $extracaps);
            $SQL = "SELECT *\n                      FROM {$CFG->prefix}capabilities\n                     WHERE contextlevel = " . CONTEXT_USER . "\n                           OR name IN ({$extra})";
            break;
        case CONTEXT_COURSECAT:
            // course category context and bellow
            $SQL = "SELECT *\n                      FROM {$CFG->prefix}capabilities\n                     WHERE contextlevel IN (" . CONTEXT_COURSECAT . "," . CONTEXT_COURSE . "," . CONTEXT_MODULE . "," . CONTEXT_BLOCK . ")";
            break;
        case CONTEXT_COURSE:
            // course context and bellow
            $SQL = "SELECT *\n                      FROM {$CFG->prefix}capabilities\n                     WHERE contextlevel IN (" . CONTEXT_COURSE . "," . CONTEXT_MODULE . "," . CONTEXT_BLOCK . ")";
            break;
        case CONTEXT_MODULE:
            // mod caps
            $cm = get_record('course_modules', 'id', $context->instanceid);
            $module = get_record('modules', 'id', $cm->module);
            $modfile = "{$CFG->dirroot}/mod/{$module->name}/lib.php";
            if (file_exists($modfile)) {
                include_once $modfile;
                $modfunction = $module->name . '_get_extra_capabilities';
                if (function_exists($modfunction)) {
                    $extracaps = $modfunction();
                }
            }
            if (empty($extracaps)) {
                $extracaps = array();
            }
            // All modules allow viewhiddenactivities. This is so you can hide
            // the module then override to allow specific roles to see it.
            // The actual check is in course page so not module-specific
            $extracaps[] = "moodle/course:viewhiddenactivities";
            if (count($extracaps) == 1) {
                $extra = "OR name = '" . reset($extracaps) . "'";
            } else {
                foreach ($extracaps as $key => $value) {
                    $extracaps[$key] = "'{$value}'";
                }
                $extra = implode(',', $extracaps);
                $extra = "OR name IN ({$extra})";
            }
            $SQL = "SELECT *\n                      FROM {$CFG->prefix}capabilities\n                     WHERE (contextlevel = " . CONTEXT_MODULE . "\n                           AND component = 'mod/{$module->name}')\n                           {$extra}";
            break;
        case CONTEXT_BLOCK:
            // block caps
            $cb = get_record('block_instance', 'id', $context->instanceid);
            $block = get_record('block', 'id', $cb->blockid);
            $extra = "";
            if ($blockinstance = block_instance($block->name)) {
                if ($extracaps = $blockinstance->get_extra_capabilities()) {
                    foreach ($extracaps as $key => $value) {
                        $extracaps[$key] = "'{$value}'";
                    }
                    $extra = implode(',', $extracaps);
                    $extra = "OR name IN ({$extra})";
                }
            }
            $SQL = "SELECT *\n                      FROM {$CFG->prefix}capabilities\n                     WHERE (contextlevel = " . CONTEXT_BLOCK . "\n                           AND component = 'block/{$block->name}')\n                           {$extra}";
            break;
        default:
            return false;
    }
    if (!($records = get_records_sql($SQL . ' ' . $sort))) {
        $records = array();
    }
    return $records;
}
 */
ob_start();
include '../../config.php';
/// setting contexts
$id = required_param('id', PARAM_INT);
// course id
$instanceid = required_param('instance', PARAM_INT);
// block instance id
$action = optional_param('what', '', PARAM_TEXT);
if (!($course = $DB->get_record('course', array('id' => "{$id}")))) {
    print_error('invalidcourseid');
}
if (!($instance = $DB->get_record('block_instances', array('id' => "{$instanceid}")))) {
    print_error('badblockinstance', 'block_dashboard');
}
$theBlock = block_instance('dashboard', $instance);
// security
require_login($course);
require_capability('block/dashboard:configure', context_system::instance(0));
// get a copy of block configuration
if ($action == 'get') {
    ob_end_clean();
    header("Content-Type:text/raw\n\n");
    echo $instance->configdata;
    die;
}
// process form
include_once 'copyconfig_form.php';
$url = $CFG->wwwroot . '/blocks/dashboard/copyconfig.php?id=' . $course->id . '&instance=' . $instanceid;
$mform = new CopyConfig_Form($url);
if ($mform->is_cancelled()) {
Example #20
0
function blocks_print_adminblock(&$page, &$pageblocks)
{
    global $USER;
    $missingblocks = blocks_get_missing($page, $pageblocks);
    if (!empty($missingblocks)) {
        $strblocks = '<div class="title"><h2>';
        $strblocks .= get_string('blocks');
        $strblocks .= '</h2></div>';
        $stradd = get_string('add');
        foreach ($missingblocks as $blockid) {
            $block = blocks_get_record($blockid);
            $blockobject = block_instance($block->name);
            if ($blockobject === false) {
                continue;
            }
            if (!$blockobject->user_can_addto($page)) {
                continue;
            }
            $menu[$block->id] = $blockobject->get_title();
        }
        asort($menu);
        $target = $page->url_get_full(array('sesskey' => $USER->sesskey, 'blockaction' => 'add'));
        $content = popup_form($target . '&amp;blockid=', $menu, 'add_block', '', $stradd . '...', '', '', true);
        print_side_block($strblocks, $content, NULL, NULL, NULL, array('class' => 'block_adminblock'));
    }
}
Example #21
0
 public function load_settings(part_of_admin_tree $adminroot, $parentnodename, $hassiteconfig)
 {
     global $CFG, $USER, $DB, $OUTPUT, $PAGE;
     // in case settings.php wants to refer to them
     $ADMIN = $adminroot;
     // may be used in settings.php
     $block = $this;
     // also can be used inside settings.php
     $section = $this->get_settings_section_name();
     if (!$hassiteconfig || ($blockinstance = block_instance($this->name)) === false) {
         return;
     }
     $settings = null;
     if ($blockinstance->has_config()) {
         if (file_exists($this->full_path('settings.php'))) {
             $settings = new admin_settingpage($section, $this->displayname, 'moodle/site:config', $this->is_enabled() === false);
             include $this->full_path('settings.php');
             // this may also set $settings to null
         } else {
             $blocksinfo = self::get_blocks_info();
             $settingsurl = new moodle_url('/admin/block.php', array('block' => $blocksinfo[$this->name]->id));
             $settings = new admin_externalpage($section, $this->displayname, $settingsurl, 'moodle/site:config', $this->is_enabled() === false);
         }
     }
     if ($settings) {
         $ADMIN->add($parentnodename, $settings);
     }
 }
 // For those branches we return the alphanum key, courses and mycourses.
 $branchid = required_param('id', PARAM_ALPHANUM);
 // This identifies the type of the branch we want to get
 $branchtype = required_param('type', PARAM_INT);
 // This identifies the block instance requesting AJAX extension
 $instanceid = optional_param('instance', null, PARAM_INT);
 $PAGE->set_context(context_system::instance());
 // Create a global nav object
 $navigation = new global_navigation_for_ajax($PAGE, $branchtype, $branchid);
 $linkcategories = false;
 if ($instanceid !== null) {
     // Get the db record for the block instance
     $blockrecord = $DB->get_record('block_instances', array('id' => $instanceid, 'blockname' => 'navigation'));
     if ($blockrecord != false) {
         // Instantiate a block_instance object so we can access config
         $block = block_instance('navigation', $blockrecord);
         $trimmode = block_navigation::TRIM_RIGHT;
         $trimlength = 50;
         // Set the trim mode
         if (!empty($block->config->trimmode)) {
             $trimmode = (int) $block->config->trimmode;
         }
         // Set the trim length
         if (!empty($block->config->trimlength)) {
             $trimlength = (int) $block->config->trimlength;
         }
         if (!empty($block->config->linkcategories) && $block->config->linkcategories == 'yes') {
             $linkcategories = true;
         }
     }
 }
 public function process_block($data)
 {
     global $DB, $CFG;
     $data = (object) $data;
     // Handy
     $oldcontextid = $data->contextid;
     $oldid = $data->id;
     $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
     // Look for the parent contextid
     if (!($data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid))) {
         throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
     }
     // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
     // If there is already one block of that type in the parent context
     // and the block is not multiple, stop processing
     // Use blockslib loader / method executor
     if (!($bi = block_instance($data->blockname))) {
         return false;
     }
     if (!$bi->instance_allow_multiple()) {
         // The block cannot be added twice, so we will check if the same block is already being
         // displayed on the same page. For this, rather than mocking a page and using the block_manager
         // we use a similar query to the one in block_manager::load_blocks(), this will give us
         // a very good idea of the blocks already displayed in the context.
         $params = array('blockname' => $data->blockname);
         // Context matching test.
         $context = context::instance_by_id($data->parentcontextid);
         $contextsql = 'bi.parentcontextid = :contextid';
         $params['contextid'] = $context->id;
         $parentcontextids = $context->get_parent_context_ids();
         if ($parentcontextids) {
             list($parentcontextsql, $parentcontextparams) = $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
             $contextsql = "({$contextsql} OR (bi.showinsubcontexts = 1 AND bi.parentcontextid {$parentcontextsql}))";
             $params = array_merge($params, $parentcontextparams);
         }
         // Page type pattern test.
         $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
         list($pagetypepatternsql, $pagetypepatternparams) = $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
         $params = array_merge($params, $pagetypepatternparams);
         // Sub page pattern test.
         $subpagepatternsql = 'bi.subpagepattern IS NULL';
         if ($data->subpagepattern !== null) {
             $subpagepatternsql = "({$subpagepatternsql} OR bi.subpagepattern = :subpagepattern)";
             $params['subpagepattern'] = $data->subpagepattern;
         }
         $exists = $DB->record_exists_sql("SELECT bi.id\n                                                FROM {block_instances} bi\n                                                JOIN {block} b ON b.name = bi.blockname\n                                               WHERE bi.blockname = :blockname\n                                                 AND {$contextsql}\n                                                 AND bi.pagetypepattern {$pagetypepatternsql}\n                                                 AND {$subpagepatternsql}", $params);
         if ($exists) {
             // There is at least one very similar block visible on the page where we
             // are trying to restore the block. In these circumstances the block API
             // would not allow the user to add another instance of the block, so we
             // apply the same rule here.
             return false;
         }
     }
     // If there is already one block of that type in the parent context
     // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
     // stop processing
     $params = array('blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid, 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern, 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
     if ($birecs = $DB->get_records('block_instances', $params)) {
         foreach ($birecs as $birec) {
             if ($birec->configdata == $data->configdata) {
                 return false;
             }
         }
     }
     // Set task old contextid, blockid and blockname once we know them
     $this->task->set_old_contextid($oldcontextid);
     $this->task->set_old_blockid($oldid);
     $this->task->set_blockname($data->blockname);
     // Let's look for anything within configdata neededing processing
     // (nulls and uses of legacy file.php)
     if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
         $configdata = (array) unserialize(base64_decode($data->configdata));
         foreach ($configdata as $attribute => $value) {
             if (in_array($attribute, $attrstotransform)) {
                 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
             }
         }
         $data->configdata = base64_encode(serialize((object) $configdata));
     }
     // Create the block instance
     $newitemid = $DB->insert_record('block_instances', $data);
     // Save the mapping (with restorefiles support)
     $this->set_mapping('block_instance', $oldid, $newitemid, true);
     // Create the block context
     $newcontextid = context_block::instance($newitemid)->id;
     // Save the block contexts mapping and sent it to task
     $this->set_mapping('context', $oldcontextid, $newcontextid);
     $this->task->set_contextid($newcontextid);
     $this->task->set_blockid($newitemid);
     // Restore block fileareas if declared
     $component = 'block_' . $this->task->get_blockname();
     foreach ($this->task->get_fileareas() as $filearea) {
         // Simple match by contextid. No itemname needed
         $this->add_related_files($component, $filearea, null);
     }
     // Process block positions, creating them or accumulating for final step
     foreach ($positions as $position) {
         $position = (object) $position;
         $position->blockinstanceid = $newitemid;
         // The instance is always the restored one
         // If position is for one already mapped (known) contextid
         // process it now, creating the position
         if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
             $position->contextid = $newpositionctxid;
             // Create the block position
             $DB->insert_record('block_positions', $position);
             // The position belongs to an unknown context, send it to backup_ids
             // to process them as part of the final steps of restore. We send the
             // whole $position object there, hence use the low level method.
         } else {
             restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
         }
     }
 }
Example #24
0
 /**
  * Insert evidence into the moodle table in addition to the realsmart one
  * @author David Drummond <*****@*****.**>, Daniel Dammann <*****@*****.**>
  */
 function update_moodle_item($courseid, $raflitemid, $text)
 {
     global $CFG;
     // attempt to get correct record of corresponding moodle page_item
     $sql = "SELECT {$CFG->prefix}format_page_items.* \n                  FROM {$CFG->prefix}format_page_items \n                  JOIN {$CFG->prefix}format_page on {$CFG->prefix}format_page.id = {$CFG->prefix}format_page_items.pageid\n                 WHERE {$CFG->prefix}format_page_items.rafl_item = {$raflitemid}\n                   AND {$CFG->prefix}format_page.courseid = {$courseid}";
     if ($pageitem = get_record_sql($sql)) {
         // valid page item, now let's try to find and update the block data
         $instance = get_record('block_instance', 'id', $pageitem->blockinstance);
         $block = get_record('block', 'id', $instance->blockid);
         if ($obj = block_instance($block->name, $instance)) {
             $blockdata->title = $obj->title;
             $blockdata->text = $text;
             if (!$obj->instance_config_save($blockdata, false, false)) {
                 error('Error saving block configuration');
             }
         }
     } else {
         debugging('No matching page item found for this rafl. courseid: ' . $courseid . ' raflitemid: ' . $raflitemid);
     }
     return 1;
 }
Example #25
0
 public function process_block($data)
 {
     global $DB, $CFG;
     $data = (object) $data;
     // Handy
     $oldcontextid = $data->contextid;
     $oldid = $data->id;
     $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
     // Look for the parent contextid
     if (!($data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid))) {
         throw new restore_step_exception('restore_block_missing_parent_ctx', $data->parentcontextid);
     }
     // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
     // If there is already one block of that type in the parent context
     // and the block is not multiple, stop processing
     // Use blockslib loader / method executor
     if (!($bi = block_instance($data->blockname))) {
         return false;
     }
     if (!$bi->instance_allow_multiple()) {
         if ($DB->record_exists_sql("SELECT bi.id\n                                          FROM {block_instances} bi\n                                          JOIN {block} b ON b.name = bi.blockname\n                                         WHERE bi.parentcontextid = ?\n                                           AND bi.blockname = ?", array($data->parentcontextid, $data->blockname))) {
             return false;
         }
     }
     // If there is already one block of that type in the parent context
     // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
     // stop processing
     $params = array('blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid, 'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern, 'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
     if ($birecs = $DB->get_records('block_instances', $params)) {
         foreach ($birecs as $birec) {
             if ($birec->configdata == $data->configdata) {
                 return false;
             }
         }
     }
     // Set task old contextid, blockid and blockname once we know them
     $this->task->set_old_contextid($oldcontextid);
     $this->task->set_old_blockid($oldid);
     $this->task->set_blockname($data->blockname);
     // Let's look for anything within configdata neededing processing
     // (nulls and uses of legacy file.php)
     if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
         $configdata = (array) unserialize(base64_decode($data->configdata));
         foreach ($configdata as $attribute => $value) {
             if (in_array($attribute, $attrstotransform)) {
                 $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
             }
         }
         $data->configdata = base64_encode(serialize((object) $configdata));
     }
     // Create the block instance
     $newitemid = $DB->insert_record('block_instances', $data);
     // Save the mapping (with restorefiles support)
     $this->set_mapping('block_instance', $oldid, $newitemid, true);
     // Create the block context
     $newcontextid = context_block::instance($newitemid)->id;
     // Save the block contexts mapping and sent it to task
     $this->set_mapping('context', $oldcontextid, $newcontextid);
     $this->task->set_contextid($newcontextid);
     $this->task->set_blockid($newitemid);
     // Restore block fileareas if declared
     $component = 'block_' . $this->task->get_blockname();
     foreach ($this->task->get_fileareas() as $filearea) {
         // Simple match by contextid. No itemname needed
         $this->add_related_files($component, $filearea, null);
     }
     // Process block positions, creating them or accumulating for final step
     foreach ($positions as $position) {
         $position = (object) $position;
         $position->blockinstanceid = $newitemid;
         // The instance is always the restored one
         // If position is for one already mapped (known) contextid
         // process it now, creating the position
         if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
             $position->contextid = $newpositionctxid;
             // Create the block position
             $DB->insert_record('block_positions', $position);
             // The position belongs to an unknown context, send it to backup_ids
             // to process them as part of the final steps of restore. We send the
             // whole $position object there, hence use the low level method.
         } else {
             restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
         }
     }
 }
    function definition()
    {
        global $DB, $COURSE;
        $mform =& $this->_form;
        $mform->addElement('header', 'displayinfo', get_string('conditionadd_header', 'block_game_content_unlock'));
        $condition_types = array();
        $game_points_installed = $DB->record_exists('block', array('name' => 'game_points'));
        if ($game_points_installed) {
            $condition_types[0] = get_string('conditionadd_typebypointstext', 'block_game_content_unlock');
        }
        $condition_types[1] = get_string('conditionadd_typebyunlocktext', 'block_game_content_unlock');
        $game_achievements_installed = $DB->record_exists('block', array('name' => 'game_content_unlock'));
        if ($game_achievements_installed) {
            $condition_types[2] = get_string('conditionadd_typebyachievementtext', 'block_game_content_unlock');
        }
        $mform->addElement('select', 'condition_type', get_string('conditionadd_typetext', 'block_game_content_unlock'), $condition_types, null);
        $mform->addRule('condition_type', null, 'required', null, 'client');
        // Points system condition
        if ($game_points_installed) {
            $mform->addElement('html', '<hr></hr>');
            $points_systems_list = array();
            $blocks_info = $DB->get_records('block_instances', array('blockname' => 'game_points'));
            foreach ($blocks_info as $info) {
                $instance = block_instance('game_points', $info);
                $points_systems_list['block::' . $instance->instance->id] = '- Bloco ' . $instance->title;
                $points_systems = $DB->get_records('points_system', array('blockinstanceid' => $instance->instance->id, 'deleted' => 0));
                foreach ($points_systems as $points_system) {
                    $points_systems_list['pointsystem::' . $points_system->id] = '&nbsp;&nbsp;&nbsp;&nbsp;Sistema de pontos ' . (isset($points_system->name) ? $points_system->name . ' (' . $points_system->id . ')' : $points_system->id);
                }
            }
            $mform->addElement('select', 'points_condition_blockorpointsystemid', 'Os pontos do bloco', $points_systems_list, null);
            $mform->disabledIf('points_condition_blockorpointsystemid', 'condition_type', 'neq', 0);
            $mform->addElement('text', 'points_condition_points', 'Maiores ou iguais a');
            $mform->disabledIf('points_condition_points', 'condition_type', 'neq', 0);
            $mform->addElement('advcheckbox', 'points_condition_grupal', 'Grupal', null, null, array(0, 1));
        }
        // Content unlock system condition
        $mform->addElement('html', '<hr></hr>');
        $unlock_systems = array();
        $blocks_info = $DB->get_records('block_instances', array('blockname' => 'game_content_unlock'));
        foreach ($blocks_info as $info) {
            $instance = block_instance('game_content_unlock', $info);
            $sql = "SELECT *\n\t\t\t\t\tFROM\n\t\t\t\t\t\t{content_unlock_system} u\n\t\t\t\t\tWHERE u.deleted = 0\n\t\t\t\t\t\tAND u.blockinstanceid = :blockinstanceid";
            $params['blockinstanceid'] = $instance->instance->id;
            $us = $DB->get_records_sql($sql, $params);
            foreach ($us as $unlock_system) {
                $course = $DB->get_record('course', array('id' => $COURSE->id));
                $info = get_fast_modinfo($course);
                $cm = $info->get_cm($unlock_system->coursemoduleid);
                $unlock_systems[$unlock_system->id] = ($unlock_system->coursemodulevisibility ? 'Desbloqueado' : 'Bloqueado') . ' o recurso/atividade ' . $cm->name . ' (bloco ' . $instance->title . ')';
            }
        }
        $mform->addElement('select', 'unlock_condition_must', 'O aluno', array(0 => 'Não deve', 1 => 'Deve'), null);
        $mform->setDefault('unlock_condition_must', 1);
        $mform->disabledIf('unlock_condition_must', 'condition_type', 'neq', 1);
        $mform->addElement('select', 'unlock_condition_unlocksystemid', 'Ter', $unlock_systems, null);
        $mform->disabledIf('unlock_condition_unlocksystemid', 'condition_type', 'neq', 1);
        // Achievement condition
        if ($game_achievements_installed) {
            $mform->addElement('html', '<hr></hr>');
            $achievements = array();
            $blocks_info = $DB->get_records('block_instances', array('blockname' => 'game_achievements'));
            foreach ($blocks_info as $info) {
                $instance = block_instance('game_achievements', $info);
                $sql = 'SELECT id
							FROM {achievements}
							WHERE blockinstanceid = :blockinstanceid
								AND deleted = :deleted';
                $params['blockinstanceid'] = $instance->instance->id;
                $params['deleted'] = 0;
                $achievement_ids = $DB->get_fieldset_sql($sql, $params);
                foreach ($achievement_ids as $achievement_id) {
                    $achievement = $DB->get_record('achievements', array('id' => $achievement_id));
                    $achievements[$achievement_id] = 'Conquista ' . (isset($achievement->name) ? $achievement->name . ' (' . $achievement_id . ')' : $achievement_id) . ' (bloco ' . $instance->title . ')';
                }
            }
            $mform->addElement('select', 'achievements_condition_achievementid', 'Ter alcançado a', $achievements, null);
            $mform->disabledIf('achievements_condition_achievementid', 'condition_type', 'neq', 2);
        }
        $mform->addElement('hidden', 'unlocksystemid');
        $mform->addElement('hidden', 'courseid');
        $this->add_action_buttons();
    }
Example #27
0
/**
 * Automatically clean-up all plugin data and remove the plugin DB tables
 *
 * @param string $type The plugin type, eg. 'mod', 'qtype', 'workshopgrading' etc.
 * @param string $name The plugin name, eg. 'forum', 'multichoice', 'accumulative' etc.
 * @uses global $OUTPUT to produce notices and other messages
 * @return void
 */
function uninstall_plugin($type, $name)
{
    global $CFG, $DB, $OUTPUT;
    // recursively uninstall all module subplugins first
    if ($type === 'mod') {
        if (file_exists("{$CFG->dirroot}/mod/{$name}/db/subplugins.php")) {
            $subplugins = array();
            include "{$CFG->dirroot}/mod/{$name}/db/subplugins.php";
            foreach ($subplugins as $subplugintype => $dir) {
                $instances = get_plugin_list($subplugintype);
                foreach ($instances as $subpluginname => $notusedpluginpath) {
                    uninstall_plugin($subplugintype, $subpluginname);
                }
            }
        }
    }
    $component = $type . '_' . $name;
    // eg. 'qtype_multichoice' or 'workshopgrading_accumulative' or 'mod_forum'
    if ($type === 'mod') {
        $pluginname = $name;
        // eg. 'forum'
        if (get_string_manager()->string_exists('modulename', $component)) {
            $strpluginname = get_string('modulename', $component);
        } else {
            $strpluginname = $component;
        }
    } else {
        $pluginname = $component;
        if (get_string_manager()->string_exists('pluginname', $component)) {
            $strpluginname = get_string('pluginname', $component);
        } else {
            $strpluginname = $component;
        }
    }
    echo $OUTPUT->heading($pluginname);
    $plugindirectory = get_plugin_directory($type, $name);
    $uninstalllib = $plugindirectory . '/db/uninstall.php';
    if (file_exists($uninstalllib)) {
        require_once $uninstalllib;
        $uninstallfunction = 'xmldb_' . $pluginname . '_uninstall';
        // eg. 'xmldb_workshop_uninstall()'
        if (function_exists($uninstallfunction)) {
            if (!$uninstallfunction()) {
                echo $OUTPUT->notification('Encountered a problem running uninstall function for ' . $pluginname);
            }
        }
    }
    if ($type === 'mod') {
        // perform cleanup tasks specific for activity modules
        if (!($module = $DB->get_record('modules', array('name' => $name)))) {
            print_error('moduledoesnotexist', 'error');
        }
        // delete all the relevant instances from all course sections
        if ($coursemods = $DB->get_records('course_modules', array('module' => $module->id))) {
            foreach ($coursemods as $coursemod) {
                if (!delete_mod_from_section($coursemod->id, $coursemod->section)) {
                    echo $OUTPUT->notification("Could not delete the {$strpluginname} with id = {$coursemod->id} from section {$coursemod->section}");
                }
            }
        }
        // clear course.modinfo for courses that used this module
        $sql = "UPDATE {course}\n                   SET modinfo=''\n                 WHERE id IN (SELECT DISTINCT course\n                                FROM {course_modules}\n                               WHERE module=?)";
        $DB->execute($sql, array($module->id));
        // delete all the course module records
        $DB->delete_records('course_modules', array('module' => $module->id));
        // delete module contexts
        if ($coursemods) {
            foreach ($coursemods as $coursemod) {
                if (!delete_context(CONTEXT_MODULE, $coursemod->id)) {
                    echo $OUTPUT->notification("Could not delete the context for {$strpluginname} with id = {$coursemod->id}");
                }
            }
        }
        // delete the module entry itself
        $DB->delete_records('modules', array('name' => $module->name));
        // cleanup the gradebook
        require_once $CFG->libdir . '/gradelib.php';
        grade_uninstalled_module($module->name);
        // Perform any custom uninstall tasks
        if (file_exists($CFG->dirroot . '/mod/' . $module->name . '/lib.php')) {
            require_once $CFG->dirroot . '/mod/' . $module->name . '/lib.php';
            $uninstallfunction = $module->name . '_uninstall';
            if (function_exists($uninstallfunction)) {
                debugging("{$uninstallfunction}() has been deprecated. Use the plugin's db/uninstall.php instead", DEBUG_DEVELOPER);
                if (!$uninstallfunction()) {
                    echo $OUTPUT->notification('Encountered a problem running uninstall function for ' . $module->name . '!');
                }
            }
        }
    } else {
        if ($type === 'enrol') {
            // NOTE: this is a bit brute force way - it will not trigger events and hooks properly
            // nuke all role assignments
            role_unassign_all(array('component' => $component));
            // purge participants
            $DB->delete_records_select('user_enrolments', "enrolid IN (SELECT id FROM {enrol} WHERE enrol = ?)", array($name));
            // purge enrol instances
            $DB->delete_records('enrol', array('enrol' => $name));
            // tweak enrol settings
            if (!empty($CFG->enrol_plugins_enabled)) {
                $enabledenrols = explode(',', $CFG->enrol_plugins_enabled);
                $enabledenrols = array_unique($enabledenrols);
                $enabledenrols = array_flip($enabledenrols);
                unset($enabledenrols[$name]);
                $enabledenrols = array_flip($enabledenrols);
                if (is_array($enabledenrols)) {
                    set_config('enrol_plugins_enabled', implode(',', $enabledenrols));
                }
            }
        } else {
            if ($type === 'block') {
                if ($block = $DB->get_record('block', array('name' => $name))) {
                    // Inform block it's about to be deleted
                    if (file_exists("{$CFG->dirroot}/blocks/{$block->name}/block_{$block->name}.php")) {
                        $blockobject = block_instance($block->name);
                        if ($blockobject) {
                            $blockobject->before_delete();
                            //only if we can create instance, block might have been already removed
                        }
                    }
                    // First delete instances and related contexts
                    $instances = $DB->get_records('block_instances', array('blockname' => $block->name));
                    foreach ($instances as $instance) {
                        blocks_delete_instance($instance);
                    }
                    // Delete block
                    $DB->delete_records('block', array('id' => $block->id));
                }
            }
        }
    }
    // perform clean-up task common for all the plugin/subplugin types
    // delete calendar events
    $DB->delete_records('event', array('modulename' => $pluginname));
    // delete all the logs
    $DB->delete_records('log', array('module' => $pluginname));
    // delete log_display information
    $DB->delete_records('log_display', array('component' => $component));
    // delete the module configuration records
    unset_all_config_for_plugin($pluginname);
    // delete message provider
    message_provider_uninstall($component);
    // delete message processor
    if ($type === 'message') {
        message_processor_uninstall($name);
    }
    // delete the plugin tables
    $xmldbfilepath = $plugindirectory . '/db/install.xml';
    drop_plugin_tables($component, $xmldbfilepath, false);
    if ($type === 'mod' or $type === 'block') {
        // non-frankenstyle table prefixes
        drop_plugin_tables($name, $xmldbfilepath, false);
    }
    // delete the capabilities that were defined by this module
    capabilities_cleanup($component);
    // remove event handlers and dequeue pending events
    events_uninstall($component);
    echo $OUTPUT->notification(get_string('success'), 'notifysuccess');
}
Example #28
0
 /**
  * @see plugintype_interface::get_settings_url()
  */
 public function get_settings_url()
 {
     if (($block = block_instance($this->name)) === false) {
         return parent::get_settings_url();
     } else {
         if ($block->has_config()) {
             if (!empty($this->rootdir) and file_exists($this->rootdir . '/settings.php')) {
                 return new moodle_url('/admin/settings.php', array('section' => 'blocksetting' . $this->name));
             } else {
                 $blocksinfo = self::get_blocks_info();
                 return new moodle_url('/admin/block.php', array('block' => $blocksinfo[$this->name]->id));
             }
         } else {
             return parent::get_settings_url();
         }
     }
 }
Example #29
0
                     include $CFG->dirroot . '/mod/' . $modulename . '/settings.php';
                 }
                 $ADMIN->add('modsettings', $settings);
             }
         }
     }
 }
 // hidden script for converting journals to online assignments (or something like that) linked from elsewhere
 $ADMIN->add('modsettings', new admin_externalpage('oacleanup', 'Online Assignment Cleanup', $CFG->wwwroot . '/' . $CFG->admin . '/oacleanup.php', 'moodle/site:config', true));
 $ADMIN->add('modules', new admin_category('blocksettings', get_string('blocks')));
 $ADMIN->add('blocksettings', new admin_page_manageblocks());
 $ADMIN->add('blocksettings', new admin_externalpage('stickyblocks', get_string('stickyblocks', 'admin'), "{$CFG->wwwroot}/{$CFG->admin}/stickyblocks.php"));
 if ($blocks = $DB->get_records('block')) {
     $blockbyname = array();
     foreach ($blocks as $block) {
         if (($blockobject = block_instance($block->name)) === false) {
             // Failed to load
             continue;
         }
         $blockbyname[$blockobject->get_title()] = $block;
     }
     ksort($blockbyname);
     foreach ($blockbyname as $strblockname => $block) {
         $blockname = $block->name;
         if (file_exists($CFG->dirroot . '/blocks/' . $blockname . '/settings.php')) {
             $settings = new admin_settingpage('blocksetting' . $blockname, $strblockname, 'moodle/site:config', !$block->visible);
             if ($ADMIN->fulltree) {
                 include $CFG->dirroot . '/blocks/' . $blockname . '/settings.php';
             }
             $ADMIN->add('blocksettings', $settings);
         } else {
Example #30
0
    if ($quickmailblock = get_record('block', 'name', 'quickmail')) {
        $instance = get_record('block_instance', 'blockid', $quickmailblock->id, 'pageid', $course->id);
    }
}
/// This block of code ensures that Quickmail will run
///     whether it is in the course or not
if (empty($instance)) {
    $groupmode = groupmode($course);
    if (has_capability('block/quickmail:cansend', get_context_instance(CONTEXT_BLOCK, $instanceid))) {
        $haspermission = true;
    } else {
        $haspermission = false;
    }
} else {
    // create a quickmail block instance
    $quickmail = block_instance('quickmail', $instance);
    $groupmode = $quickmail->groupmode();
    $haspermission = $quickmail->check_permission();
}
if (!$haspermission) {
    error('Sorry, you do not have the correct permissions to use Quickmail.');
}
if (!($courseusers = get_users_by_capability($context, 'moodle/course:view', 'u.*', 'u.lastname, u.firstname', '', '', '', '', false))) {
    error('No course users found to email');
}
if ($action == 'view') {
    // viewing an old email.  Hitting the db and puting it into the object $form
    $emailid = required_param('emailid', PARAM_INT);
    $form = get_record('block_quickmail_log', 'id', $emailid);
    $form->mailto = explode(',', $form->mailto);
    // convert mailto back to an array