diff --git a/blocks/activity_modules/block_activity_modules.php b/blocks/activity_modules/block_activity_modules.php index 85469902e870d..3126ea28558aa 100644 --- a/blocks/activity_modules/block_activity_modules.php +++ b/blocks/activity_modules/block_activity_modules.php @@ -25,17 +25,34 @@ function get_content() { $modinfo = get_fast_modinfo($course); $modfullnames = array(); + $archetypes = array(); + foreach($modinfo->cms as $cm) { - if (!$cm->uservisible) { + if (!$cm->uservisible or $cm->modname === 'label') { + continue; + } + if (array_key_exists($cm->modname, $modfullnames)) { continue; } - $modfullnames[$cm->modname] = $cm->modplural; + if (!array_key_exists($cm->modname, $archetypes)) { + $archetypes[$cm->modname] = plugin_supports('mod', $cm->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER); + } + if ($archetypes[$cm->modname] == MOD_ARCHETYPE_RESOURCE) { + if (!array_key_exists('resources', $modfullnames)) { + $modfullnames['resources'] = get_string('resources'); + } + } else { + $modfullnames[$cm->modname] = $cm->modplural; + } } asort($modfullnames, SORT_LOCALE_STRING); foreach ($modfullnames as $modname => $modfullname) { - if ($modname != 'label') { + if ($modname === 'resources') { + $this->content->items[] = ''.$modfullname.''; + $this->content->icons[] = ''; + } else { $this->content->items[] = ''.$modfullname.''; $this->content->icons[] = ''; } diff --git a/course/lib.php b/course/lib.php index 144ac281fbf7b..2e1b6187209e1 100644 --- a/course/lib.php +++ b/course/lib.php @@ -1343,25 +1343,23 @@ function print_section($course, $section, $mods, $modnamesused, $absolute=false, $icon = $OUTPUT->old_icon_url(str_replace(array('.gif', '.png'), '', $customicon)); } } else { - $icon = "" . $OUTPUT->mod_icon_url('icon', $mod->modname) . ""; + $icon = $OUTPUT->mod_icon_url('icon', $mod->modname); } - //Accessibility: for files get description via icon. + //Accessibility: for files get description via icon, this is very ugly hack! $altname = ''; - if ('resource'==$mod->modname) { - if (!empty($customicon)) { - $possaltname = $customicon; + $altname = $mod->modfullname; + if (!empty($customicon)) { + $archetype = plugin_supports('mod', $mod->modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER); + if ($archetype == MOD_ARCHETYPE_RESOURCE) { + $possaltname = str_replace(array('.gif', '.png'), '', $customicon).'.gif'; $mimetype = mimeinfo_from_icon('type', $possaltname); $altname = get_mimetype_description($mimetype); - } else { - $altname = $mod->modfullname; } - } else { - $altname = $mod->modfullname; } // Avoid unnecessary duplication. - if (false!==stripos($instancename, $altname)) { + if (false !== stripos($instancename, $altname)) { $altname = ''; } // File type after name, for alphabetic lists (screen reader). @@ -1587,8 +1585,13 @@ function print_section_add_menus($course, $section, $modnames, $vertical=false, } } } else { - // all mods without type are considered activity - $activities[$modname] = $modnamestr; + $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER); + if ($archetype == MOD_ARCHETYPE_RESOURCE) { + $resources[$modname] = $modnamestr; + } else { + // all other archetypes are considered activity + $activities[$modname] = $modnamestr; + } } } } @@ -3535,5 +3538,3 @@ function get_course_by_idnumber ($idnumber) { global $DB; return $DB->get_record('course', array('idnumber' => $idnumber)); } - -?> diff --git a/course/modedit.php b/course/modedit.php index 912268ccd9c15..edc42c2899ae2 100644 --- a/course/modedit.php +++ b/course/modedit.php @@ -1,6 +1,27 @@ -. + +/** + * Adds or updates modules in a course using new formslib + * + * @package moodlecore + * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ require_once("../config.php"); require_once("lib.php"); @@ -9,15 +30,13 @@ require_once($CFG->libdir.'/completionlib.php'); require_once($CFG->libdir.'/conditionlib.php'); - $add = optional_param('add', 0, PARAM_ALPHA); + $add = optional_param('add', '', PARAM_ALPHA); // module name $update = optional_param('update', 0, PARAM_INT); - $return = optional_param('return', 0, PARAM_BOOL); //return to course/view.php if false or mod/modname/view.php if true - $type = optional_param('type', '', PARAM_ALPHANUM); + $return = optional_param('return', 0, PARAM_BOOL); //return to course/view.php if false or mod/modname/view.php if true + $type = optional_param('type', '', PARAM_ALPHANUM); //TODO: hopefully will be removed in 2.0 $PAGE->set_generaltype('form'); - require_login(); - if (!empty($add)) { $section = required_param('section', PARAM_INT); $course = required_param('course', PARAM_INT); @@ -42,48 +61,45 @@ $cm = null; - $form = new object(); - $form->section = $section; // The section number itself - relative!!! (section column in course_sections) - $form->visible = $cw->visible; - $form->course = $course->id; - $form->module = $module->id; - $form->modulename = $module->name; - $form->groupmode = $course->groupmode; - $form->groupingid = $course->defaultgroupingid; - $form->groupmembersonly = 0; - $form->instance = ''; - $form->coursemodule = ''; - $form->add = $add; - $form->return = 0; //must be false if this is an add, go back to course view on cancel - - if (plugin_supports('mod', $form->modulename, FEATURE_MOD_INTRO, true)) { + $data = new object(); + $data->section = $section; // The section number itself - relative!!! (section column in course_sections) + $data->visible = $cw->visible; + $data->course = $course->id; + $data->module = $module->id; + $data->modulename = $module->name; + $data->groupmode = $course->groupmode; + $data->groupingid = $course->defaultgroupingid; + $data->groupmembersonly = 0; + $data->id = ''; + $data->instance = ''; + $data->coursemodule = ''; + $data->add = $add; + $data->return = 0; //must be false if this is an add, go back to course view on cancel + + if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) { $draftid_editor = file_get_submitted_draft_itemid('introeditor'); file_prepare_draft_area($draftid_editor, null, null, null); - $form->introeditor = array('text'=>'', 'format'=>FORMAT_HTML, 'itemid'=>$draftid_editor); // TODO: add better default + $data->introeditor = array('text'=>'', 'format'=>FORMAT_HTML, 'itemid'=>$draftid_editor); // TODO: add better default } - // Turn off default grouping for modules that don't provide group mode - if ($add=='resource' || $add=='glossary' || $add=='label') { - $form->groupingid = 0; - } - - if (!empty($type)) { - $form->type = $type; + if (!empty($type)) { //TODO: hopefully will be removed in 2.0 + $data->type = $type; } $sectionname = get_section_name($course->format); $fullmodulename = get_string('modulename', $module->name); - if ($form->section && $course->format != 'site') { + if ($data->section && $course->format != 'site') { + $heading = new object(); $heading->what = $fullmodulename; - $heading->to = "$sectionname $form->section"; + $heading->to = "$sectionname $data->section"; $pageheading = get_string('addinganewto', 'moodle', $heading); } else { $pageheading = get_string('addinganew', 'moodle', $fullmodulename); } $pagepath = 'mod-' . $module->name . '-'; - if (!empty($type)) { + if (!empty($type)) { //TODO: hopefully will be removed in 2.0 $pagepath .= $type; } else { $pagepath .= 'mod'; @@ -101,7 +117,7 @@ print_error('invalidcourseid'); } - require_login($course); // needed to setup proper $COURSE + require_login($course, false, $cm); // needed to setup proper $COURSE $context = get_context_instance(CONTEXT_MODULE, $cm->id); require_capability('moodle/course:manageactivities', $context); @@ -109,7 +125,7 @@ print_error('moduledoesnotexist'); } - if (!$form = $DB->get_record($module->name, array('id'=>$cm->instance))) { + if (!$data = $DB->get_record($module->name, array('id'=>$cm->instance))) { print_error('moduleinstancedoesnotexist'); } @@ -117,41 +133,41 @@ print_error('sectionnotexist'); } - $form->coursemodule = $cm->id; - $form->section = $cw->section; // The section number itself - relative!!! (section column in course_sections) - $form->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides - $form->cmidnumber = $cm->idnumber; // The cm IDnumber - $form->groupmode = groups_get_activity_groupmode($cm); // locked later if forced - $form->groupingid = $cm->groupingid; - $form->groupmembersonly = $cm->groupmembersonly; - $form->course = $course->id; - $form->module = $module->id; - $form->modulename = $module->name; - $form->instance = $cm->instance; - $form->return = $return; - $form->update = $update; - $form->completion = $cm->completion; - $form->completionview = $cm->completionview; - $form->completionexpected = $cm->completionexpected; - $form->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1; - if(!empty($CFG->enableavailability)) { - $form->availablefrom = $cm->availablefrom; - $form->availableuntil = $cm->availableuntil; - $form->showavailability = $cm->showavailability; - } - - if (plugin_supports('mod', $form->modulename, FEATURE_MOD_INTRO, true)) { + $data->coursemodule = $cm->id; + $data->section = $cw->section; // The section number itself - relative!!! (section column in course_sections) + $data->visible = $cm->visible; //?? $cw->visible ? $cm->visible : 0; // section hiding overrides + $data->cmidnumber = $cm->idnumber; // The cm IDnumber + $data->groupmode = groups_get_activity_groupmode($cm); // locked later if forced + $data->groupingid = $cm->groupingid; + $data->groupmembersonly = $cm->groupmembersonly; + $data->course = $course->id; + $data->module = $module->id; + $data->modulename = $module->name; + $data->instance = $cm->instance; + $data->return = $return; + $data->update = $update; + $data->completion = $cm->completion; + $data->completionview = $cm->completionview; + $data->completionexpected = $cm->completionexpected; + $data->completionusegrade = is_null($cm->completiongradeitemnumber) ? 0 : 1; + if (!empty($CFG->enableavailability)) { + $data->availablefrom = $cm->availablefrom; + $data->availableuntil = $cm->availableuntil; + $data->showavailability = $cm->showavailability; + } + + if (plugin_supports('mod', $data->modulename, FEATURE_MOD_INTRO, true)) { $draftid_editor = file_get_submitted_draft_itemid('introeditor'); - $currentintro = file_prepare_draft_area($draftid_editor, $context->id, $form->modulename.'_intro', 0, array('subdirs'=>true), $form->intro); - $form->introeditor = array('text'=>$currentintro, 'format'=>$form->introformat, 'itemid'=>$draftid_editor); + $currentintro = file_prepare_draft_area($draftid_editor, $context->id, $data->modulename.'_intro', 0, array('subdirs'=>true), $data->intro); + $data->introeditor = array('text'=>$currentintro, 'format'=>$data->introformat, 'itemid'=>$draftid_editor); } - if ($items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$form->modulename, - 'iteminstance'=>$form->instance, 'courseid'=>$course->id))) { + if ($items = grade_item::fetch_all(array('itemtype'=>'mod', 'itemmodule'=>$data->modulename, + 'iteminstance'=>$data->instance, 'courseid'=>$course->id))) { // add existing outcomes foreach ($items as $item) { if (!empty($item->outcomeid)) { - $form->{'outcome_'.$item->outcomeid} = 1; + $data->{'outcome_'.$item->outcomeid} = 1; } } @@ -170,14 +186,15 @@ } if ($gradecat !== false) { // do not set if mixed categories present - $form->gradecat = $gradecat; + $data->gradecat = $gradecat; } } $sectionname = get_section_name($course->format); $fullmodulename = get_string('modulename', $module->name); - if ($form->section && $course->format != 'site') { + if ($data->section && $course->format != 'site') { + $heading = new object(); $heading->what = $fullmodulename; $heading->in = "$sectionname $cw->section"; $pageheading = get_string('updatingain', 'moodle', $heading); @@ -185,7 +202,7 @@ $pageheading = get_string('updatinga', 'moodle', $fullmodulename); } - $navlinksinstancename = array('name' => format_string($form->name, true), 'link' => "$CFG->wwwroot/mod/$module->name/view.php?id=$cm->id", 'type' => 'activityinstance'); + $navlinksinstancename = array('name' => format_string($data->name, true), 'link' => "$CFG->wwwroot/mod/$module->name/view.php?id=$cm->id", 'type' => 'activityinstance'); $pagetype = 'mod-' . $module->name . '-'; if (!empty($type)) { @@ -195,6 +212,7 @@ } $PAGE->set_pagetype($pagetype); } else { + require_login(); print_error('invalidaction'); } @@ -214,8 +232,8 @@ } $mformclassname = 'mod_'.$module->name.'_mod_form'; - $mform = new $mformclassname($form, $cw->section, $cm, $course); - $mform->set_data($form); + $mform = new $mformclassname($data, $cw->section, $cm, $course); + $mform->set_data($data); if ($mform->is_cancelled()) { if ($return && !empty($cm->id)) { @@ -268,7 +286,7 @@ if (!isset($fromform->name)) { //label $fromform->name = $fromform->modulename; } - + if (!isset($fromform->completion)) { $fromform->completion = COMPLETION_DISABLED; } @@ -292,6 +310,7 @@ $cm->groupmode = $fromform->groupmode; $cm->groupingid = $fromform->groupingid; $cm->groupmembersonly = $fromform->groupmembersonly; + $completion = new completion_info($course); if ($completion->is_enabled()) { // Handle completion settings. If necessary, wipe existing completion @@ -306,13 +325,13 @@ $cm->completionview = $fromform->completionview; $cm->completionexpected = $fromform->completionexpected; } - if(!empty($CFG->enableavailability)) { + if (!empty($CFG->enableavailability)) { $cm->availablefrom = $fromform->availablefrom; $cm->availableuntil = $fromform->availableuntil; - // The form time is midnight, but because we want it to be + // The form time is midnight, but because we want it to be // inclusive, set it to 23:59:59 on that day. if ($cm->availableuntil) { - $cm->availableuntil = strtotime('23:59:59', + $cm->availableuntil = strtotime('23:59:59', $cm->availableuntil); } $cm->showavailability = $fromform->showavailability; @@ -322,7 +341,7 @@ $DB->update_record('course_modules', $cm); $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule); - + // update embedded links and save files if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) { $fromform->intro = file_save_draft_area_files($fromform->introeditor['itemid'], $modcontext->id, @@ -331,7 +350,7 @@ $fromform->introformat = $fromform->introeditor['format']; unset($fromform->introeditor); } - + if (!$updateinstancefunction($fromform, $mform)) { print_error('cannotupdatemod', '', 'view.php?id=$course->id', $fromform->modulename); } @@ -380,10 +399,10 @@ if(!empty($CFG->enableavailability)) { $newcm->availablefrom = $fromform->availablefrom; $newcm->availableuntil = $fromform->availableuntil; - // The form time is midnight, but because we want it to be + // The form time is midnight, but because we want it to be // inclusive, set it to 23:59:59 on that day. if ($newcm->availableuntil) { - $newcm->availableuntil = strtotime('23:59:59', + $newcm->availableuntil = strtotime('23:59:59', $newcm->availableuntil); } $newcm->showavailability = $fromform->showavailability; @@ -393,24 +412,16 @@ print_error('cannotaddcoursemodule'); } - $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule); - - // update embedded links and save files - if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) { - $fromform->intro = file_save_draft_area_files($fromform->introeditor['itemid'], $modcontext->id, - $fromform->modulename.'_intro', 0, - array('subdirs'=>true), $fromform->introeditor['text']); - $fromform->introformat = $fromform->introeditor['format']; - unset($fromform->introeditor); - } + $introeditor = $fromform->introeditor; + unset($fromform->introeditor); + $fromform->intro = $introeditor['text']; + $fromform->introformat = $introeditor['format']; $returnfromfunc = $addinstancefunction($fromform, $mform); if (!$returnfromfunc or !is_number($returnfromfunc)) { // undo everything we can $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule); - $fs = get_file_storage(); - $fs->delete_area_files($modcontext->id); delete_context(CONTEXT_MODULE, $fromform->coursemodule); $DB->delete_records('course_modules', array('id'=>$fromform->coursemodule)); @@ -425,6 +436,15 @@ $DB->set_field('course_modules', 'instance', $returnfromfunc, array('id'=>$fromform->coursemodule)); + // update embedded links and save files + $modcontext = get_context_instance(CONTEXT_MODULE, $fromform->coursemodule); + if (plugin_supports('mod', $fromform->modulename, FEATURE_MOD_INTRO, true)) { + $fromform->intro = file_save_draft_area_files($introeditor['itemid'], $modcontext->id, + $fromform->modulename.'_intro', 0, + array('subdirs'=>true), $introeditor['text']); + $DB->set_field($fromform->modulename, 'intro', $fromform->intro, array('id'=>$fromform->instance)); + } + // course_modules and course_sections each contain a reference // to each other, so we have to update one of them twice. $sectionid = add_mod_to_section($fromform); @@ -545,7 +565,7 @@ rebuild_course_cache($course->id); grade_regrade_final_grades($course->id); - if (isset($fromform->submitbutton)) { + if (isset($fromform->submitbutton)) { redirect("$CFG->wwwroot/mod/$module->name/view.php?id=$fromform->coursemodule"); } else { redirect("$CFG->wwwroot/course/view.php?id=$course->id"); diff --git a/course/resources.php b/course/resources.php new file mode 100644 index 0000000000000..4c64b44fab095 --- /dev/null +++ b/course/resources.php @@ -0,0 +1,142 @@ +. + +/** + * List of all resource type modules in course + * + * @package moodlecore + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once('../config.php'); +require_once("$CFG->libdir/resourcelib.php"); + +$id = required_param('id', PARAM_INT); // course id + +$course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); + +require_course_login($course, true); + +// get list of all resource-like modules +$allmodules = $DB->get_records('modules', array('visible'=>1)); +$modules = array(); +foreach ($allmodules as $key=>$module) { + $modname = $module->name; + $libfile = "$CFG->dirroot/mod/$modname/lib.php"; + if (!file_exists($libfile)) { + continue; + } + $archetype = plugin_supports('mod', $modname, FEATURE_MOD_ARCHETYPE, MOD_ARCHETYPE_OTHER); + if ($archetype != MOD_ARCHETYPE_RESOURCE) { + continue; + } + + $modules[$modname] = get_string('modulename', $modname); + //some hacky nasic logging + add_to_log($course->id, $modname, 'view all', "index.php?id=$course->id", ''); +} + +$strresources = get_string('resources'); +$strweek = get_string('week'); +$strtopic = get_string('topic'); +$strname = get_string('name'); +$strintro = get_string('moduleintro'); +$strlastmodified = get_string('lastmodified'); + +$PAGE->set_url('course/resources.php', array('id' => $course->id)); +$PAGE->set_title($course->shortname.': '.$strresources); +$PAGE->set_heading($course->fullname); +$navlinks = array(array('name' => $strresources, 'link' => '', 'type' => 'activityinstance')); +echo $OUTPUT->header(build_navigation($navlinks), navmenu($course)); + +$modinfo = get_fast_modinfo($course); +$cms = array(); +$resources = array(); +foreach ($modinfo->cms as $cm) { + if (!$cm->uservisible) { + continue; + } + if (!array_key_exists($cm->modname, $modules)) { + continue; + } + $cms[$cm->id] = $cm; + $resources[$cm->modname][] = $cm->instance; +} + +// preload instances +foreach ($resources as $modname=>$instances) { + $resources[$modname] = $DB->get_records_list($modname, 'id', $instances, 'id', 'id,name,intro,introformat,timemodified'); +} + +if (!$cms) { + notice(get_string('thereareno', 'moodle', $strresources), "$CFG->wwwroot/course/view.php?id=$course->id"); + exit; +} + +$table = new html_table(); +$table->set_classes(array('generaltable', 'mod_index')); + +if ($course->format == 'weeks') { + $table->head = array ($strweek, $strname, $strintro); + $table->align = array ('center', 'left', 'left'); +} else if ($course->format == 'topics') { + $table->head = array ($strtopic, $strname, $strintro); + $table->align = array ('center', 'left', 'left'); +} else { + $table->head = array ($strlastmodified, $strname, $strintro); + $table->align = array ('left', 'left', 'left'); +} + +$currentsection = ''; +foreach ($cms as $cm) { + if (!isset($resources[$cm->modname][$cm->instance])) { + continue; + } + $resource = $resources[$cm->modname][$cm->instance]; + if ($course->format == 'weeks' or $course->format == 'topics') { + $printsection = ''; + if ($cm->sectionnum !== $currentsection) { + if ($cm->sectionnum) { + $printsection = $cm->sectionnum; + } + if ($currentsection !== '') { + $table->data[] = 'hr'; + } + $currentsection = $cm->sectionnum; + } + } else { + $printsection = ''.userdate($resource->timemodified).""; + } + + $extra = empty($cm->extra) ? '' : $cm->extra; + if (!empty($cm->icon)) { + $icon = ' '; + } else { + $icon = ' '; + } + + $class = $cm->visible ? '' : 'class="dimmed"'; // hidden modules are dimmed + $table->data[] = array ( + $printsection, + "wwwroot/mod/$cm->modname/view.php?id=$cm->id\">".$icon.format_string($resource->name)."", + format_module_intro('resource', $resource, $cm->id)); +} + +echo $OUTPUT->table($table); + +echo $OUTPUT->footer(); diff --git a/help.php b/help.php index 97c4913af7594..36d9c22be094d 100644 --- a/help.php +++ b/help.php @@ -48,9 +48,6 @@ } // The remaining horrible hardcoded special cases should be delegated to modules somehow. - if ($module == 'moodle'&& $file == 'resource/types.html') { // RESOURCES - include_help_for_each_resource($forcelang, $skiplocal); - } if ($module == 'moodle' && $file == 'assignment/types.html') { // ASSIGNMENTS include_help_for_each_assignment_type($forcelang, $skiplocal); } @@ -182,30 +179,6 @@ function include_help_for_qtype($qtype, $localizedname) { echo '

' . get_string($qtype . 'summary', 'qtype_' . $qtype) . "

\n\n"; } -function include_help_for_each_resource($forcelang, $skiplocal) { - global $CFG; - - require_once($CFG->dirroot .'/mod/resource/lib.php'); - $typelist = resource_get_types(); - - //add label type - $labelType = new object(); - $labelType->modclass = MOD_CLASS_RESOURCE; - $resourcetype = 'label'; - $labelType->name = $resourcetype; - $labelType->type = "resource&type=$resourcetype"; - $labelType->typestr = get_string("resourcetype$resourcetype", 'resource'); - $typelist[] = $labelType; - - foreach ($typelist as $type) { - list($filepath, $foundlang) = string_manager::instance()->find_help_file('type/' . $type->name . '.html', 'resource', $forcelang, $skiplocal); - if ($filepath) { - echo '
'; - include($filepath); - } - } -} - function include_help_for_each_assignment_type() { global $CFG; diff --git a/lang/en_utf8/admin.php b/lang/en_utf8/admin.php index b4ca3b02f9645..73601f1f31e6e 100644 --- a/lang/en_utf8/admin.php +++ b/lang/en_utf8/admin.php @@ -208,6 +208,7 @@ $string['configminpasswordlower'] = 'Passwords must have at least these many lower case letters.'; $string['configminpasswordnonalphanum'] = 'Passwords must have at least these many non-alphanumeric characters.'; $string['configminpasswordupper'] = 'Passwords must have at least these many upper case letters.'; +$string['condifmodeditdefaults'] = 'The values you set here define the default values that are used in the activity settings form when you create a new activity. You can also configure which activity settings are considered advanced.'; $string['configmycoursesperpage'] = 'Maximum number of courses to display in any list of a user\'s own courses'; $string['configmymoodleredirect'] = 'This setting forces redirects to /my on login for non-admins and replaces the top level site navigation with /my'; $string['confignodefaultuserrolelists'] = 'This setting prevents all users from being returned from the database from deprecated calls of get_course_user, etc., for the site course if the default role provides that access. Check this, if you suffer a performance hit.'; @@ -600,6 +601,7 @@ $string['mnetrestore_extusers_mismatch'] = 'Note: This backup file apparently originates from a different Moodle installation and contains remote Moodle Network user accounts that may fail to restore. This operation is unsupported. If you are certain that it was created on this Moodle installation, or you can ensure that all the needed Moodle Network Hosts are configured, you may want to still try the restore.'; $string['mnetrestore_extusers_noadmin'] = 'Note: This backup file seems to come from a different Moodle installation and contains remote Moodle Network user accounts. You are not allowed to execute this type of restore. Contact the administrator of the site or, alternatively, restore this course without any user information (modules, files...)'; $string['mnetrestore_extusers_switchuserauth'] = 'Remote Moodle Network user $a->username (coming from $a->mnethosturl) switched to local $a->auth authenticated user.'; +$string['modeditdefaults'] = 'Default values for activity settings'; $string['modsettings'] = 'Manage activities'; $string['modulesecurity'] = 'Module security'; $string['multilangforceold'] = 'Force old multilang syntax: <span> without the class=\"multilang\" and <lang>'; @@ -738,6 +740,8 @@ $string['remotelangnotavailable'] = 'Because Moodle can not connect to download.moodle.org, we are unable to do language pack installation automatically. Please download the appropriate zip file(s) from the list below, copy them to your $a directory and unzip them manually.'; $string['renameerrors'] = 'Rename errors'; $string['requiredtemplate'] = 'Required. You may use template syntax here (%%l = lastname, %%f = firstname, %%u = username). See help for details and examples.'; +$string['requiremodintro'] = 'Require activity description'; +$string['configrequiremodintro'] = 'Disable this option if you do not want to force users to enter description of each activity.'; $string['requires'] = 'Requires'; $string['requiredentrieschanged'] = 'IMPORTANT - PLEASE READ
(This warning message will only be displayed during this upgrade)

Due to a bug fix, the behaviour of database activities using the \'Required entries\' and \'Required entries before viewing settings\' settings will change. A more detailed explaination of the changes can be read on the database module forum. The expected behavior of these settings can also be read on Moodle Docs.

This change affects the following databases in your system: (Please save this list now, and after the upgrade, check that these activities still work the way that the teacher intends.)
$a->text
'; diff --git a/lang/en_utf8/resource.php b/lang/en_utf8/resource.php index 31feddfcdadd2..2b45d8ab09f1b 100644 --- a/lang/en_utf8/resource.php +++ b/lang/en_utf8/resource.php @@ -1,8 +1,47 @@ -getFilename(), PARAM_FILE); if ($filename === '') { + //unsupported chars, sorry continue; } @@ -140,7 +141,12 @@ function upgrade_migrate_files_course($context, $path, $delete) { continue; // modules are responsible } - $filepath = clean_param($filepath.$item->getFilename().'/', PARAM_PATH); + $dirname = clean_param($item->getFilename(), PARAM_PATH); + if ($dirname === '') { + //unsupported chars, sorry + continue; + } + $filepath = ($filepath.$dirname.'/'); if ($filepath !== '/backupdata/') { $fs->create_directory($context->id, $filearea, 0, $filepath); } diff --git a/lib/moodlelib.php b/lib/moodlelib.php index 91feafc091b93..a1c2f6f9a1b6d 100644 --- a/lib/moodlelib.php +++ b/lib/moodlelib.php @@ -300,6 +300,8 @@ /** True if module supports groupmembersonly */ define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly'); +/** Type of module */ +define('FEATURE_MOD_ARCHETYPE', 'mod_archetype'); /** True if module supports intro editor */ define('FEATURE_MOD_INTRO', 'mod_intro'); /** True if module supports subplugins */ @@ -309,6 +311,13 @@ define('FEATURE_COMMENT', 'comment'); +/** Unspecified module archetype */ +define('MOD_ARCHETYPE_OTHER', 0); +/** Resource-like type module */ +define('MOD_ARCHETYPE_RESOURCE', 1); +/** Assignemnt module archetype */ +define('MOD_ARCHETYPE_ASSIGNMENT', 2); + /// PARAMETER HANDLING //////////////////////////////////////////////////// diff --git a/lib/resourcelib.php b/lib/resourcelib.php new file mode 100644 index 0000000000000..23e5d9fbfad7b --- /dev/null +++ b/lib/resourcelib.php @@ -0,0 +1,426 @@ +. + +/** + * Recourse module like helper functions + * + * @package moodlecore + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** Try the best way */ +define('RESOURCELIB_DISPLAY_AUTO', 0); +/** Display using object tag */ +define('RESOURCELIB_DISPLAY_EMBED', 1); +/** Display inside frame */ +define('RESOURCELIB_DISPLAY_FRAME', 2); +/** Display normal link in new window */ +define('RESOURCELIB_DISPLAY_NEW', 3); +/** Force download of file instead of display */ +define('RESOURCELIB_DISPLAY_DOWNLOAD', 4); +/** Open directly */ +define('RESOURCELIB_DISPLAY_OPEN', 5); +/** Open in "emulated" pop-up without navigation */ +define('RESOURCELIB_DISPLAY_POPUP', 6); + +/** Legacy files not needed or new resource */ +define('RESOURCELIB_LEGACYFILES_NO', 0); +/** Legacy files conversion marked as completed */ +define('RESOURCE_LEGACYYFILES_DONE', 1); +/** Legacy files conversion in progress*/ +define('RESOURCELIB_LEGACYFILES_ACTIVE', 2); + + +/** + * Returns list of available display options + * @param array $enabled list of options enabled in module configuration + * @param int $current current dispaly options for existing instances + * @return array of key=>name pairs + */ +function resourcelib_get_displayoptions(array $enabled, $current=null) { + if (is_number($current)) { + $enabled[] = $current; + } + + $options = array(RESOURCELIB_DISPLAY_AUTO => get_string('displayauto', 'resource'), + RESOURCELIB_DISPLAY_EMBED => get_string('displayembed', 'resource'), + RESOURCELIB_DISPLAY_FRAME => get_string('displayframe', 'resource'), + RESOURCELIB_DISPLAY_NEW => get_string('displaynew', 'resource'), + RESOURCELIB_DISPLAY_DOWNLOAD => get_string('displaydownload', 'resource'), + RESOURCELIB_DISPLAY_OPEN => get_string('displayopen', 'resource'), + RESOURCELIB_DISPLAY_POPUP => get_string('displaypopup', 'resource')); + + $result = array(); + + foreach ($options as $key=>$value) { + if (in_array($key, $enabled)) { + $result[$key] = $value; + } + } + + if (empty($result)) { + // there should be always something in case admin misconfigures module + $result[RESOURCELIB_DISPLAY_OPEN] = $options[RESOURCELIB_DISPLAY_OPEN]; + } + + return $result; +} + +/** + * Tries to guess correct mimetype for arbitrary URL + * @param string $fullurl + * @return string mimetype + */ +function resourcelib_guess_url_mimetype($fullurl) { + global $CFG; + require_once("$CFG->libdir/filelib.php"); + + if (preg_match("|^(.*)/[a-z]*file.php(\?file=)?(/[^&\?]*)|", $fullurl, $matches)) { + // remove the special moodle file serving hacks so that the *file.php is ignored + $fullurl = $matches[1].$matches[3]; + } + + if (strpos($fullurl, '.php')){ + // we do not really know what is in general php script + return 'text/html'; + + } else if (substr($fullurl, -1) === '/') { + // directory index (http://example.com/smaples/) + return 'text/html'; + + } else if (strpos($fullurl, '//') !== false and substr_count($fullurl, '/') == 2) { + // just a host name (http://example.com), solves Australian servers "audio" problem too + return 'text/html'; + + } else { + // ok, this finally looks like a real file + return mimeinfo('type', $fullurl); + } +} + +/** + * Returns image embedding html. + * @param string $fullurl + * @param string $title + * @return string html + */ +function resourcelib_embed_image($fullurl, $title) { + $code = ''; + $code .= '
'; + $code .= "\"\""; + $code .= '
'; + + return $code; +} + +/** + * Returns mp3 embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_mp3($fullurl, $title, $clicktoopen) { + global $CFG, $THEME, $PAGE; + + if (!empty($THEME->resource_mp3player_colors)) { + $c = $THEME->resource_mp3player_colors; // You can set this up in your theme/xxx/config.php + } else { + $c = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&'. + 'iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&'. + 'font=Arial&fontColour=FF33FF&buffer=10&waitForPlay=no&autoPlay=yes'; + } + $c .= '&volText='.get_string('vol', 'resource').'&panText='.get_string('pan','resource'); + $id = 'filter_mp3_'.time(); //we need something unique because it might be stored in text cache + + $ufoargs = array('movie' => $CFG->wwwroot.'/lib/mp3player/mp3player.swf?src='.addslashes_js($fullurl), + 'width' => 600, + 'height' => 70, + 'majorversion' => 6, + 'build' => 40, + 'flashvars' => $c, + 'quality' => 'high'); + + // If we have Javascript, use UFO to embed the MP3 player, otherwise depend on plugins + $code = << + + + +OET; + + $PAGE->requires->yui_lib('dom')->in_head(); + $PAGE->requires->js('lib/ufo.js')->in_head(); + $PAGE->requires->js('lib/resourcelib.js')->in_head(); + $code .= $PAGE->requires->data_for_js('FO', $ufoargs)->asap(); + $code .= $PAGE->requires->js_function_call('resourcelib_create_UFO_object', array($id))->asap(); + return $code; +} + +/** + * Returns flash video embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_flashvideo($fullurl, $title, $clicktoopen) { + global $CFG, $PAGE; + + $id = 'filter_flv_'.time(); //we need something unique because it might be stored in text cache + + $ufoargs = array('movie' => $CFG->wwwroot.'/filter/mediaplugin/flvplayer.swf?file='.addslashes_js($fullurl), + 'width' => 600, + 'height' => 400, + 'majorversion' => 6, + 'build' => 40, + 'allowscriptaccess' => 'never', + 'allowfullscreen' => 'true', + 'quality' => 'high'); + + // If we have Javascript, use UFO to embed the FLV player, otherwise depend on plugins + + $code = << + + + +EOT; + + $PAGE->requires->yui_lib('dom')->in_head(); + $PAGE->requires->js('lib/ufo.js')->in_head(); + $PAGE->requires->js('lib/resourcelib.js')->in_head(); + $code .= $PAGE->requires->data_for_js('FO', $ufoargs)->asap(); + $code .= $PAGE->requires->js_function_call('resourcelib_create_UFO_object', array($id))->asap(); + return $code; +} + +/** + * Returns flash embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_flash($fullurl, $title, $clicktoopen) { + $code = << + + + + + + + + + + + + + + + +$clicktoopen + + + + + +EOT; + + return $code; +} + +/** + * Returns ms media embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_mediaplayer($fullurl, $title, $clicktoopen) { + $code = << + + + + + + $clicktoopen + + +EOT; + + return $code; +} + +/** + * Returns quicktime embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_quicktime($fullurl, $title, $clicktoopen) { + $code = << + + + + + + + + + + + + + +$clicktoopen + + + + + +EOT; + + return $code; +} + +/** + * Returns mpeg embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_mpeg($fullurl, $title, $clicktoopen) { + $code = << + + + + + + + + + + + + + +$clicktoopen + + + + + +EOT; + + return $code; +} + +/** + * Returns real media embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_real($fullurl, $title, $clicktoopen) { + $code = << + + + + + + + +$clicktoopen + + + + + +EOT; + + return $code; +} + +/** + * Returns general link or file embedding html. + * @param string $fullurl + * @param string $title + * @param string $clicktoopen + * @return string html + */ +function resourcelib_embed_general($fullurl, $title, $clicktoopen, $mimetype) { + global $CFG, $PAGE; + + $iframe = false; + // IE can not embed stuff properly if stored on different server + // that is why we use iframe instead, unfortunately this tag does not validate + // in xhtml strict mode + if ($mimetype === 'text/html' and check_browser_version('MSIE', 5)) { + if (preg_match('(^https?://[^/]*)', $fullurl, $matches)) { + if (strpos($CFG->wwwroot, $matches[0]) !== 0) { + $iframe = true; + } + } + } + + if ($iframe) { + $code = << + + +EOT; + } else { + $code = << + + + $clicktoopen + + +EOT; + } + + return $code; +} diff --git a/mod/resource/backuplib.php b/mod/resource/backuplib.php deleted file mode 100644 index fdd9d373b220a..0000000000000 --- a/mod/resource/backuplib.php +++ /dev/null @@ -1,176 +0,0 @@ -id,files) - // - // Meaning: pk->primary key field of the table - // fk->foreign key to link with parent - // nt->nested field (recursive data) - // CL->course level info - // UL->user level info - // files->table may have files) - // - //----------------------------------------------------------- - - //This function executes all the backup procedure about this mod - function resource_backup_mods($bf,$preferences) { - global $CFG, $DB; - - $status = true; - - ////Iterate over resource table - $resources = $DB->get_records ("resource", array("course"=>$preferences->backup_course),"id"); - if ($resources) { - foreach ($resources as $resource) { - if (backup_mod_selected($preferences,'resource',$resource->id)) { - $status = resource_backup_one_mod($bf,$preferences,$resource); - } - } - } - return $status; - } - - function resource_backup_one_mod($bf,$preferences,$resource) { - global $CFG, $DB; - - if (is_numeric($resource)) { - $resource = $DB->get_record('resource', array('id'=>$resource)); - } - - $status = true; - - //Start mod - fwrite ($bf,start_tag("MOD",3,true)); - //Print assignment data - fwrite ($bf,full_tag("ID",4,false,$resource->id)); - fwrite ($bf,full_tag("MODTYPE",4,false,"resource")); - fwrite ($bf,full_tag("NAME",4,false,$resource->name)); - fwrite ($bf,full_tag("TYPE",4,false,$resource->type)); - fwrite ($bf,full_tag("REFERENCE",4,false,$resource->reference)); - fwrite ($bf,full_tag("SUMMARY",4,false,$resource->intro)); - fwrite ($bf,full_tag("ALLTEXT",4,false,$resource->alltext)); - fwrite ($bf,full_tag("POPUP",4,false,$resource->popup)); - fwrite ($bf,full_tag("OPTIONS",4,false,$resource->options)); - fwrite ($bf,full_tag("TIMEMODIFIED",4,false,$resource->timemodified)); - //End mod - $status = fwrite ($bf,end_tag("MOD",3,true)); - - if ($status && ($resource->type == 'file' || $resource->type == 'directory' || $resource->type == 'ims')) { // more should go here later! - // backup files for this resource. - $status = resource_backup_files($bf,$preferences,$resource); - } - - return $status; - } - - ////Return an array of info (name,value) - function resource_check_backup_mods($course,$user_data=false,$backup_unique_code,$instances=null) { - if (!empty($instances) && is_array($instances) && count($instances)) { - $info = array(); - foreach ($instances as $id => $instance) { - $info += resource_check_backup_mods_instances($instance,$backup_unique_code); - } - return $info; - } - //First the course data - $info[0][0] = get_string("modulenameplural","resource"); - if ($ids = resource_ids ($course)) { - $info[0][1] = count($ids); - } else { - $info[0][1] = 0; - } - - return $info; - } - - ////Return an array of info (name,value) - function resource_check_backup_mods_instances($instance,$backup_unique_code) { - //First the course data - $info[$instance->id.'0'][0] = ''.$instance->name.''; - $info[$instance->id.'0'][1] = ''; - - return $info; - } - - //Return a content encoded to support interactivities linking. Every module - //should have its own. They are called automatically from the backup procedure. - function resource_encode_content_links ($content,$preferences) { - - global $CFG; - - $base = preg_quote($CFG->wwwroot,"/"); - - //Link to the list of resources - $buscar="/(".$base."\/mod\/resource\/index.php\?id\=)([0-9]+)/"; - $result= preg_replace($buscar,'$@RESOURCEINDEX*$2@$',$content); - - //Link to resource view by moduleid - $buscar="/(".$base."\/mod\/resource\/view.php\?id\=)([0-9]+)/"; - $result= preg_replace($buscar,'$@RESOURCEVIEWBYID*$2@$',$result); - - //Link to resource view by resourceid - $buscar="/(".$base."\/mod\/resource\/view.php\?r\=)([0-9]+)/"; - $result= preg_replace($buscar,'$@RESOURCEVIEWBYR*$2@$',$result); - - return $result; - } - - // INTERNAL FUNCTIONS. BASED IN THE MOD STRUCTURE - - //Returns an array of resources id - function resource_ids ($course) { - global $CFG, $DB; - - return $DB->get_records_sql("SELECT a.id, a.course - FROM {resource} a - WHERE a.course = ?", array($course)); - } - - function resource_backup_files($bf,$preferences,$resource) { - global $CFG; - $status = true; - - if (!file_exists($CFG->dataroot.'/'.$preferences->backup_course.'/'.$resource->reference)) { - return true ; // doesn't exist but we don't want to halt the entire process so still return true. - } - - $status = $status && check_and_create_course_files_dir($preferences->backup_unique_code); - - // if this is somewhere deeply nested we need to do all the structure stuff first..... - $bits = explode('/',$resource->reference); - $newbit = ''; - for ($i = 0; $i< count($bits)-1; $i++) { - $newbit .= $bits[$i].'/'; - $status = $status && check_dir_exists($CFG->dataroot.'/temp/backup/'.$preferences->backup_unique_code.'/course_files/'.$newbit,true); - } - - if ($resource->reference === '') { - $status = $status && backup_copy_course_files($preferences); // copy while ignoring backupdata and moddata!!! - } else if (strpos($resource->reference, 'backupdata') === 0 or strpos($resource->reference, $CFG->moddata) === 0) { - // no copying - these directories must not be shared anyway! - } else { - $status = $status && backup_copy_file($CFG->dataroot."/".$preferences->backup_course."/".$resource->reference, - $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/course_files/".$resource->reference); - } - - // now, just in case we check moddata ( going forwards, resources should use this ) - $status = $status && check_and_create_moddata_dir($preferences->backup_unique_code); - $status = $status && check_dir_exists($CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/".$CFG->moddata."/resource/",true); - - if ($status) { - //Only if it exists !! Thanks to Daniel Miksik. - $instanceid = $resource->id; - if (is_dir($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/resource/".$instanceid)) { - $status = backup_copy_file($CFG->dataroot."/".$preferences->backup_course."/".$CFG->moddata."/resource/".$instanceid, - $CFG->dataroot."/temp/backup/".$preferences->backup_unique_code."/moddata/resource/".$instanceid); - } - } - - return $status; - } - -?> diff --git a/mod/resource/db/access.php b/mod/resource/db/access.php index a68a38249b8de..7a849104895e7 100644 --- a/mod/resource/db/access.php +++ b/mod/resource/db/access.php @@ -1,49 +1,38 @@ : -// -// component_name should be the same as the directory name of the mod or block. -// -// Core moodle capabilities are defined thus: -// moodle/: -// -// Examples: mod/forum:viewpost -// block/recent_activity:view -// moodle/site:deleteuser +// Moodle 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. // -// The variable name for the capability definitions array follows the format -// $__capabilities +// Moodle 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. // -// For the core capabilities, the variable is $moodle_capabilities. +// You should have received a copy of the GNU General Public License +// along with Moodle. If not, see . +/** + * Resource module capability definition + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ $mod_resource_capabilities = array( - - 'mod/resource:exportresource' => array( +/* TODO: review public portfolio API first! + 'mod/resource:portfolioexport' => array( 'captype' => 'read', 'contextlevel' => CONTEXT_MODULE, 'legacy' => array( - 'admin' => CAP_ALLOW, 'teacher' => CAP_ALLOW, 'editingteacher' => CAP_ALLOW, ) ), - +*/ ); - -?> diff --git a/mod/resource/db/install.php b/mod/resource/db/install.php index 06408c46f0835..cabec481e0d63 100644 --- a/mod/resource/db/install.php +++ b/mod/resource/db/install.php @@ -1,18 +1,40 @@ -. + +/** + * Resource module post install function + * + * This file replaces: + * - STATEMENTS section in db/install.xml + * - lib.php/modulename_install() post installation hook + * - partially defaults.php + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ function xmldb_resource_install() { global $DB; -/// Install logging support - + // Install logging support update_log_display_entry('resource', 'view', 'resource', 'name'); + update_log_display_entry('resource', 'view all', 'resource', 'name'); update_log_display_entry('resource', 'update', 'resource', 'name'); update_log_display_entry('resource', 'add', 'resource', 'name'); - set_config("resource_hide_repository", "1"); } diff --git a/mod/resource/db/install.xml b/mod/resource/db/install.xml index 27fd6b7a4d39c..5c607d7a568e6 100644 --- a/mod/resource/db/install.xml +++ b/mod/resource/db/install.xml @@ -1,10 +1,34 @@ - - +
+ + + + + + + + + + + + + + + + + + + + + + +
+ @@ -16,13 +40,19 @@ - + + + + + + - + +
diff --git a/mod/resource/db/upgrade.php b/mod/resource/db/upgrade.php index 4709051f283f3..94ee5c8d9c466 100644 --- a/mod/resource/db/upgrade.php +++ b/mod/resource/db/upgrade.php @@ -1,27 +1,52 @@ -. + +/** + * Resource module upgrade code + * + * This file keeps track of upgrades to + * the resource module + * + * Sometimes, changes between versions involve + * alterations to database structures and other + * major things that may break installations. + * + * The upgrade function in this file will attempt + * to perform all the necessary actions to upgrade + * your older installtion to the current version. + * + * If there's something it cannot do itself, it + * will tell you what you need to do. + * + * The commands in here will all be database-neutral, + * using the methods of database_manager class + * + * Please do not forget to use upgrade_set_timeout() + * before any action that may take longer time to finish. + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + function xmldb_resource_upgrade($oldversion) { global $CFG, $DB; + require_once("$CFG->dirroot/mod/resource/db/upgradelib.php"); $dbman = $DB->get_manager(); $result = true; @@ -29,35 +54,162 @@ function xmldb_resource_upgrade($oldversion) { //===== 1.9.0 upgrade line ======// if ($result && $oldversion < 2009042000) { - - /// Rename field summary on table resource to intro + // Rename field summary on table resource to intro $table = new xmldb_table('resource'); $field = new xmldb_field('summary', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'reference'); - /// Launch rename field summary + // Launch rename field summary $dbman->rename_field($table, $field, 'intro'); - /// resource savepoint reached + // resource savepoint reached upgrade_mod_savepoint($result, 2009042000, 'resource'); } if ($result && $oldversion < 2009042001) { - - /// Define field introformat to be added to resource + // Define field introformat to be added to resource $table = new xmldb_table('resource'); $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro'); - /// Launch add field introformat + // Launch add field introformat $dbman->add_field($table, $field); - /// set format to current + // set format to current $DB->set_field('resource', 'introformat', FORMAT_MOODLE, array()); - /// resource savepoint reached + // resource savepoint reached upgrade_mod_savepoint($result, 2009042001, 'resource'); } + if ($result && $oldversion < 2009062500) { + // fix log actions + update_log_display_entry('resource', 'view all', 'resource', 'name'); + // resource savepoint reached + upgrade_mod_savepoint($result, 2009062500, 'resource'); + } + + if ($result && $oldversion < 2009062501) { + resource_20_prepare_migration(); + // resource savepoint reached + upgrade_mod_savepoint($result, 2009062501, 'resource'); + } + + if ($result && $oldversion < 2009062600) { + $res_count = $DB->count_records('resource'); + $old_count = $DB->count_records('resource_old', array('migrated'=>0)); + if ($res_count != $old_count) { + //we can not continue, something is very wrong!! + upgrade_log(UPGRADE_LOG_ERROR, null, 'Resource migration failed.'); + upgrade_mod_savepoint(false, 2009062600, 'resource'); + } + + // Drop obsoleted fields from resource table + $table = new xmldb_table('resource'); + $fields = array('type', 'reference', 'alltext', 'popup', 'options'); + foreach ($fields as $fname) { + $field = new xmldb_field($fname); + $dbman->drop_field($table, $field); + } + + // resource savepoint reached + upgrade_mod_savepoint($result, 2009062600, 'resource'); + } + + if ($result && $oldversion < 2009062601) { + $table = new xmldb_table('resource'); + // Define field tobemigrated to be added to resource + $field = new xmldb_field('tobemigrated', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'introformat'); + // Conditionally launch add field tobemigrated + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + // Define field mainfile to be added to resource + $field = new xmldb_field('mainfile', XMLDB_TYPE_CHAR, '255', null, null, null, null, 'tobemigrated'); + // Conditionally launch add field mainfile + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + // Define field legacyfiles to be added to resource + $field = new xmldb_field('legacyfiles', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'mainfile'); + // Conditionally launch add field legacyfiles + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + // Define field legacyfileslast to be added to resource + $field = new xmldb_field('legacyfileslast', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null, 'legacyfiles'); + // Conditionally launch add field legacyfileslast + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + // Define field display to be added to resource + $field = new xmldb_field('display', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'legacyfileslast'); + // Conditionally launch add field display + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + // Define field displayoptions to be added to resource + $field = new xmldb_field('displayoptions', XMLDB_TYPE_TEXT, 'small', null, null, null, null, 'display'); + // Conditionally launch add field displayoptions + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + // Define field filterfiles to be added to resource + $field = new xmldb_field('filterfiles', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'displayoptions'); + // Conditionally launch add field filterfiles + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + // Define field revision to be added to resource + $field = new xmldb_field('revision', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'filterfiles'); + // Conditionally launch add field revision + if (!$dbman->field_exists($table, $field)) { + $dbman->add_field($table, $field); + } + + //mark all records as awaiting migration + $DB->set_field('resource', 'tobemigrated', 1, array()); + + // resource savepoint reached + upgrade_mod_savepoint($result, 2009062601, 'resource'); + } + + if ($result && $oldversion < 2009062603) { + resource_20_migrate(); + upgrade_mod_savepoint($result, 2009062603, 'resource'); + } + + if ($result && $oldversion < 2009063000) { + //migrate and prune old settings - admins need to review and set up all module settings anyway + if (!empty($CFG->resource_framesize)) { + set_config('framesize', $CFG->resource_framesize, 'resource'); + } + if (!empty($CFG->resource_popupheight)) { + set_config('popupheight', $CFG->resource_popupheight, 'resource'); + } + if (!empty($CFG->resource_popupwidth)) { + set_config('popupwidth', $CFG->resource_popupwidth, 'resource'); + } + + $cleanupsettings = array( + // migrated settings + 'resource_framesize', 'resource_popupheight', 'resource_popupwidth', 'resource_popupmenubar', + + // obsoleted settings + 'resource_websearch', 'resource_defaulturl', 'resource_allowlocalfiles', + 'resource_popup', 'resource_popupresizable', 'resource_popupscrollbars', + 'resource_popupdirectories', 'resource_popuplocation', + 'resource_popuptoolbar', 'resource_popupstatus', + + //waiting for some other modules or plugins to pick these up + /* + 'resource_secretphrase', + */ + ); + foreach ($cleanupsettings as $setting) { + unset_config($setting); + } + + upgrade_mod_savepoint($result, 2009063000, 'resource'); + } + return $result; } - -?> diff --git a/mod/resource/db/upgradelib.php b/mod/resource/db/upgradelib.php new file mode 100644 index 0000000000000..f4d8a84a834c0 --- /dev/null +++ b/mod/resource/db/upgradelib.php @@ -0,0 +1,337 @@ +. + +/** + * Resource module upgrade related helper functions + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +/** + * Try on demand migration of file from old course files + * @param string $filepath old file path + * @param int $cmid migrated course module if + * @param int $courseid + * @param string $filearea new file area + * @param int $itemid migrated file item id + * @return mixed, false if not found, stored_file instance if migrated to new area + */ +function resource_try_file_migration($filepath, $cmid, $courseid, $filearea, $itemid) { + $fs = get_file_storage(); + + if (stripos($filepath, '/backupdata/') === 0 or stripos($filepath, '/moddata/') === 0) { + // do not steal protected files! + return false; + } + + if (!$context = get_context_instance(CONTEXT_MODULE, $cmid)) { + return false; + } + if (!$coursecontext = get_context_instance(CONTEXT_COURSE, $courseid)) { + return false; + } + + $pathnamehash = sha1($coursecontext->id.'course_content0'.$filepath); + if (!$file = $fs->get_file_by_hash($pathnamehash)) { + return false; + } + + // copy and keep the same path, name, etc. + $file_record = array('contextid'=>$context->id, 'filearea'=>$filearea, 'itemid'=>$itemid); + try { + return $fs->create_file_from_storedfile($file_record, $file); + } catch (Exception $e) { + // file may exist - highly unlikely, we do not want upgrades to stop here + return false; + } +} + +/** + * Migrate resource module data from 1.9 resource_old table to new resource table + * @return void + */ +function resource_20_migrate() { + global $CFG, $DB; + + require_once("$CFG->libdir/filelib.php"); + require_once("$CFG->libdir/resourcelib.php"); + require_once("$CFG->dirroot/course/lib.php"); + + $fs = get_file_storage(); + + $withrelativelinks = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/x-shockwave-flash'); + // note: pdf doc and other types may contain links too, but we do not support relative links there + + if (!$candidates = $DB->get_recordset('resource_old', array('type'=>'file', 'migrated'=>0))) { + return; + } + + foreach ($candidates as $candidate) { + upgrade_set_timeout(); + + $path = $candidate->reference; + $siteid = get_site()->id; + $fs = get_file_storage(); + + if (strpos($path, 'LOCALPATH') === 0) { + // ignore not maintained local files - sorry + continue; + + } else if (preg_match("|$CFG->wwwroot/file.php(\?file=)?/$siteid(/[^\s'\"&\?#]+)|", $path, $matches)) { + // public site files + $path = $matches[2]; + + $resource = new object(); + $resource->id = $candidate->oldid; + $resource->tobemigrated = 0; + $resource->mainfile = $path; + $resource->filterfiles = $CFG->filteruploadedfiles; + $resource->legacyfiles = RESOURCELIB_LEGACYFILES_NO; // on-demand-migration not possible for site files, sorry + + $context = get_context_instance(CONTEXT_MODULE, $candidate->cmid); + $sitecontext = get_context_instance(CONTEXT_COURSE, $siteid); + $file_record = array('contextid'=>$context->id, 'filearea'=>'resource_content', 'itemid'=>0); + if ($file = $fs->get_file_by_hash(sha1($sitecontext->id.'course_content0'.$path))) { + try { + $fs->create_file_from_storedfile($file_record, $file); + } catch (Exception $x) { + } + $resource->mainfile = $file->get_filepath().$file->get_filename(); + } + + } else if (preg_match("|$CFG->wwwroot/file.php(\?file=)?/$candidate->course(/[^\s'\"&\?#]+)|", $path, $matches)) { + // current course files + $path = $matches[2]; + + $resource = new object(); + $resource->id = $candidate->oldid; + $resource->tobemigrated = 0; + $resource->mainfile = $path; + $resource->filterfiles = $CFG->filteruploadedfiles; + $mimetype = mimeinfo('type', $resource->mainfile); + if (in_array($mimetype, $withrelativelinks)) { + $resource->legacyfiles = RESOURCELIB_LEGACYFILES_ACTIVE; + } else { + $resource->legacyfiles = RESOURCELIB_LEGACYFILES_NO; + } + + // try migration of main file - ignore if does not exist + if ($file = resource_try_file_migration($resource->mainfile, $candidate->cmid, $candidate->course, 'resource_content', 0)) { + $resource->mainfile = $file->get_filepath().$file->get_filename(); + } + + } else if (strpos($path, '://') or strpos($path, '/') === 0) { + // http:// https:// ftp:// OR starts with slash - to be converted to link resource + continue; + + } else { + // current course files + // cleanup old path first + $path = '/'.trim(trim($path), '/'); + if (strpos($path, '?forcedownload=1') !== false) { + // eliminate old force download tricks + $candidate->options = 'forcedownload'; + $path = str_replace('?forcedownload=1', '', $path); + } + // get rid of any extra url parameters, sorry we can not support these + preg_match("/^[^?#]+/", $path, $matches); + $parts = $matches[0]; + + $resource = new object(); + $resource->id = $candidate->oldid; + $resource->tobemigrated = 0; + $resource->mainfile = $path; + $resource->filterfiles = $CFG->filteruploadedfiles; + $mimetype = mimeinfo('type', $resource->mainfile); + if (in_array($mimetype, $withrelativelinks)) { + $resource->legacyfiles = RESOURCELIB_LEGACYFILES_ACTIVE; + } else { + $resource->legacyfiles = RESOURCELIB_LEGACYFILES_NO; + } + + // try migration of main file - ignore if does not exist + if ($file = resource_try_file_migration($resource->mainfile, $candidate->cmid, $candidate->course, 'resource_content', 0)) { + $resource->mainfile = $file->get_filepath().$file->get_filename(); + } + } + + $options = array('printheading'=>0, 'printintro'=>1); + if ($candidate->options == 'frame') { + $resource->display = RESOURCELIB_DISPLAY_FRAME; + + } else if ($candidate->options == 'objectframe') { + $resource->display = RESOURCELIB_DISPLAY_EMBED; + + } else if ($candidate->options == 'forcedownload') { + $resource->display = RESOURCELIB_DISPLAY_DOWNLOAD; + + } else if ($candidate->popup) { + $resource->display = RESOURCELIB_DISPLAY_POPUP; + if ($candidate->popup) { + $rawoptions = explode(',', $candidate->popup); + foreach ($rawoptions as $rawoption) { + list($name, $value) = explode('=', trim($rawoption), 2); + if ($value > 0 and ($name == 'width' or $name == 'height')) { + $options['popup'.$name] = $value; + continue; + } + } + } + + } else { + $resource->display = RESOURCELIB_DISPLAY_AUTO; + } + $resource->displayoptions = serialize($options); + + // update resource instance and mark as migrated + $DB->update_record('resource', $resource); + $candidate->newmodule = 'resource'; + $candidate->newid = $candidate->oldid; + $candidate->migrated = time(); + $DB->update_record('resource_old', $candidate); + } + + $candidates->close(); + + // clear all course modinfo caches + rebuild_course_cache(0, true); +} + +/** + * This function creates resource_old table adn copies all data + * from resource table, this functions has to be called from + * all modules that are sucessors of old resource module types. + * @return bool true if migration required, false if not + */ +function resource_20_prepare_migration() { + global $DB; + + $dbman = $DB->get_manager(); + + // If tresource not created yet, this is probably a new install + $table = new xmldb_table('resource'); + if (!$dbman->table_exists($table)) { + return false; + } + + // Define table resource_old to be created + $table = new xmldb_table('resource_old'); + + if ($dbman->table_exists($table)) { + //already executed + return true; + } + + // Adding fields to table resource_old + $table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null); + $table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); + $table->add_field('type', XMLDB_TYPE_CHAR, '30', null, XMLDB_NOTNULL, null, null); + $table->add_field('reference', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); + $table->add_field('intro', XMLDB_TYPE_TEXT, 'small', null, null, null, null); + $table->add_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('alltext', XMLDB_TYPE_TEXT, 'medium', null, XMLDB_NOTNULL, null, null); + $table->add_field('popup', XMLDB_TYPE_TEXT, 'small', null, XMLDB_NOTNULL, null, null); + $table->add_field('options', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null); + $table->add_field('timemodified', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + $table->add_field('oldid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null); + $table->add_field('cmid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); + $table->add_field('newmodule', XMLDB_TYPE_CHAR, '50', null, null, null, null); + $table->add_field('newid', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, null, null, null); + $table->add_field('migrated', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0'); + + // Adding keys to table resource_old + $table->add_key('primary', XMLDB_KEY_PRIMARY, array('id')); + + // Adding indexes to table resource_old + $table->add_index('oldid', XMLDB_INDEX_UNIQUE, array('oldid')); + $table->add_index('cmid', XMLDB_INDEX_NOTUNIQUE, array('cmid')); + + // Launch create table for resource_old + $dbman->create_table($table); + + $module = $DB->get_field('modules', 'id', array('name'=>'resource')); + + if (!$DB->count_records('resource')) { + // upgrade of fresh new server from 1.9 - no upgrade needed + return false; + } + + // find out if resource contains new 2.0dev fields already + $table = new xmldb_table('resource'); + $field = new xmldb_field('introformat', XMLDB_TYPE_INTEGER, '4', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, '0', 'intro'); + if ($dbman->field_exists($table, $field)) { + $sql = "INSERT INTO {resource_old} (oldid, course, name, type, reference, intro, introformat, alltext, popup, options, timemodified, cmid) + SELECT r.id, r.course, r.name, r.type, r.reference, r.intro, r.introformat, r.alltext, r.popup, r.options, r.timemodified, cm.id + FROM {resource} r + LEFT JOIN {course_modules} cm ON (r.id = cm.instance AND cm.module = :module)"; + } else { + $sql = "INSERT INTO {resource_old} (oldid, course, name, type, reference, intro, introformat, alltext, popup, options, timemodified, cmid) + SELECT r.id, r.course, r.name, r.type, r.reference, r.summary, 0, r.alltext, r.popup, r.options, r.timemodified, cm.id + FROM {resource} r + LEFT JOIN {course_modules} cm ON (r.id = cm.instance AND cm.module = :module)"; + } + + $DB->execute($sql, array('module'=>$module)); + + return true; +} + +/** + * Migrate old resource type to new module, updates all related info, keeps the context id. + * @param string $modname name of new module + * @param object $candidate old instance from resource_old + * @param object $newinstance new module instance to be insterted into db + * @return mixed false if error, object new instance with id if success + */ +function resource_migrate_to_module($modname, $candidate, $newinstance) { + global $DB; + + if (!$cm = get_coursemodule_from_id('resource', $candidate->cmid)) { + return false; + } + + if (!$module = $DB->get_record('modules', array('name'=>$modname))) { + return false; + } + + if (!$resource = $DB->get_record('resource', array('id'=>$candidate->oldid))) { + return false; + } + + // insert new instance + $newinstance->id = $DB->insert_record($modname, $newinstance); + + // update course modules + $cm->module = $module->id; + $cm->instance = $newinstance->id; + $DB->update_record('course_modules', $cm); + + //delete old record + $DB->delete_records('resource', array('id'=>$resource->id)); + + //mark as migrated + $candidate->newmodule = $modname; + $candidate->newid = $newinstance->id; + $candidate->migrated = time(); + $DB->update_record('resource_old', $candidate); + + //no need to upgrade data in logs because resource module is able to redirect to migrated instances + return $newinstance; +} diff --git a/mod/resource/filter.php b/mod/resource/filter.php deleted file mode 100644 index 6ecfcc7594cf8..0000000000000 --- a/mod/resource/filter.php +++ /dev/null @@ -1,79 +0,0 @@ -sql_length('r.name') . " DESC, cm.section ASC"; - - if (!$resources = $DB->get_records_sql($resource_sql, array($courseid)) ){ - $nothingtodo = true; - return $text; - } - - $resourcelist = array(); - - foreach ($resources as $resource) { - $currentname = trim($resource->name); - $entitisedname = s($currentname); - $strippedname = strip_tags($currentname); - /// Avoid empty or unlinkable resource names - if (!empty($strippedname)) { - $resourcelist[] = new filterobject($currentname, - 'frametarget.'>', - '', false, true); - if ($currentname != $entitisedname) { /// If name has some entity (& " < >) add that filter too. MDL-17518 - $resourcelist[] = new filterobject($entitisedname, - 'frametarget.'>', - '', false, true); - - } - } - } - - } - return filter_phrases($text, $resourcelist); // Look for all these links in the text - } - -?> diff --git a/mod/resource/functions.js b/mod/resource/functions.js new file mode 100644 index 0000000000000..6025cfa02e08a --- /dev/null +++ b/mod/resource/functions.js @@ -0,0 +1,69 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see . + +/** + * Javascript helper function for Resource module + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +function resource_init_object() { + YAHOO.util.Event.onDOMReady(function () { + imscp_setup_object(); + }); +} + +function imscp_setup_object() { + resource_resize_object(); + + // fix layout if window resized too + window.onresize = function() { + resource_resize_object(); + }; +} + +function resource_resize_object() { + var obj = YAHOO.util.Dom.get('resourceobject'); + obj.style.width = '0px'; + obj.style.height = '0px'; + var newwidth = resource_get_htmlelement_size('content', 'width') - 15; + if (newwidth > 600) { + obj.style.width = newwidth + 'px'; + } else { + obj.style.width = '600px'; + } + var pageheight = resource_get_htmlelement_size('page', 'height'); + var objheight = resource_get_htmlelement_size(obj, 'height'); + var newheight = objheight + parseInt(YAHOO.util.Dom.getViewportHeight()) - pageheight - 30; + if (newheight > 400) { + obj.style.height = newheight + 'px'; + } else { + obj.style.height = '400px'; + } +} + + +function resource_get_htmlelement_size(el, prop) { + var val = YAHOO.util.Dom.getStyle(el, prop); + if (val == 'auto') { + if (el.get) { + el = el.get('element'); // get real HTMLElement from YUI element + } + val = YAHOO.util.Dom.getComputedStyle(YAHOO.util.Dom.get(el), prop); + } + return parseInt(val); +} diff --git a/mod/resource/icon.gif b/mod/resource/icon.gif index 745ef3462c71e..41edc0e95df8e 100644 Binary files a/mod/resource/icon.gif and b/mod/resource/icon.gif differ diff --git a/mod/resource/index.php b/mod/resource/index.php index 63e968f6ef5c5..a81b0d1a65c44 100644 --- a/mod/resource/index.php +++ b/mod/resource/index.php @@ -1,88 +1,104 @@ -get_record('course', array('id'=>$id))) { - print_error('invalidcourseid'); - } - - require_course_login($course, true); - - if ($course->id != SITEID) { - require_login($course->id); - } - add_to_log($course->id, "resource", "view all", "index.php?id=$course->id", ""); - - $strresource = get_string("modulename", "resource"); - $strresources = get_string("modulenameplural", "resource"); - $strweek = get_string("week"); - $strtopic = get_string("topic"); - $strname = get_string("name"); - $strsummary = get_string("summary"); - $strlastmodified = get_string("lastmodified"); - - $navlinks = array(); - $navlinks[] = array('name' => $strresources, 'link' => '', 'type' => 'activityinstance'); - $navigation = build_navigation($navlinks); - - print_header("$course->shortname: $strresources", $course->fullname, $navigation, - "", "", true, "", navmenu($course)); - - if (! $resources = get_all_instances_in_course("resource", $course)) { - notice(get_string('thereareno', 'moodle', $strresources), "../../course/view.php?id=$course->id"); - exit; - } - - if ($course->format == "weeks") { - $table->head = array ($strweek, $strname, $strsummary); - $table->align = array ("center", "left", "left"); - } else if ($course->format == "topics") { - $table->head = array ($strtopic, $strname, $strsummary); - $table->align = array ("center", "left", "left"); - } else { - $table->head = array ($strlastmodified, $strname, $strsummary); - $table->align = array ("left", "left", "left"); - } - - $currentsection = ""; - foreach ($resources as $resource) { - if ($course->format == "weeks" or $course->format == "topics") { - $printsection = ""; - if ($resource->section !== $currentsection) { - if ($resource->section) { - $printsection = $resource->section; - } - if ($currentsection !== "") { - $table->data[] = 'hr'; - } - $currentsection = $resource->section; +. + +/** + * List of all resources in course + * + * @package mod-resource + * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require('../../config.php'); + +$id = required_param('id', PARAM_INT); // course id + +$course = $DB->get_record('course', array('id'=>$id), '*', MUST_EXIST); + +require_course_login($course, true); + +add_to_log($course->id, 'resource', 'view all', "index.php?id=$course->id", ''); + +$strresource = get_string('modulename', 'resource'); +$strresources = get_string('modulenameplural', 'resource'); +$strweek = get_string('week'); +$strtopic = get_string('topic'); +$strname = get_string('name'); +$strintro = get_string('moduleintro'); +$strlastmodified = get_string('lastmodified'); + +$PAGE->set_url('mod/resource/index.php', array('id' => $course->id)); +$PAGE->set_title($course->shortname.': '.$strresources); +$PAGE->set_heading($course->fullname); +$navlinks = array(array('name' => $strresources, 'link' => '', 'type' => 'activityinstance')); +echo $OUTPUT->header(build_navigation($navlinks), navmenu($course)); + +if (!$resources = get_all_instances_in_course('resource', $course)) { + notice(get_string('thereareno', 'moodle', $strresources), "$CFG->wwwroot/course/view.php?id=$course->id"); + exit; +} + +$table = new html_table(); +$table->set_classes(array('generaltable', 'mod_index')); + +if ($course->format == 'weeks') { + $table->head = array ($strweek, $strname, $strintro); + $table->align = array ('center', 'left', 'left'); +} else if ($course->format == 'topics') { + $table->head = array ($strtopic, $strname, $strintro); + $table->align = array ('center', 'left', 'left'); +} else { + $table->head = array ($strlastmodified, $strname, $strintro); + $table->align = array ('left', 'left', 'left'); +} + +$modinfo = get_fast_modinfo($course); +$currentsection = ''; +foreach ($resources as $resource) { + $cm = $modinfo->cms[$resource->coursemodule]; + if ($course->format == 'weeks' or $course->format == 'topics') { + $printsection = ''; + if ($resource->section !== $currentsection) { + if ($resource->section) { + $printsection = $resource->section; } - } else { - $printsection = ''.userdate($resource->timemodified).""; - } - if (!empty($resource->extra)) { - $extra = urldecode($resource->extra); - } else { - $extra = ""; - } - if (!$resource->visible) { // Show dimmed if the mod is hidden - $table->data[] = array ($printsection, - "coursemodule\">".format_string($resource->name,true)."", - format_module_intro('resource', $resource, $resource->coursemodule)); - - } else { //Show normal if the mod is visible - $table->data[] = array ($printsection, - "coursemodule\">".format_string($resource->name,true)."", - format_module_intro('resource', $resource, $resource->coursemodule)); + if ($currentsection !== '') { + $table->data[] = 'hr'; + } + $currentsection = $resource->section; } + } else { + $printsection = ''.userdate($resource->timemodified).""; } - echo "
"; + $extra = empty($cm->extra) ? '' : $cm->extra; + $icon = ''; + if (!empty($cm->icon)) { + // each resource file has an icon in 2.0 + $icon = ' '; + } - print_table($table); + $class = $resource->visible ? '' : 'class="dimmed"'; // hidden modules are dimmed + $table->data[] = array ( + $printsection, + "id\">".$icon.format_string($resource->name)."", + format_module_intro('resource', $resource, $cm->id)); +} - print_footer($course); +echo $OUTPUT->table($table); -?> +echo $OUTPUT->footer(); diff --git a/mod/resource/lib.php b/mod/resource/lib.php index 62a84e9161091..0ccd7a357e79e 100644 --- a/mod/resource/lib.php +++ b/mod/resource/lib.php @@ -17,349 +17,182 @@ /** * @package mod-resource - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} + * @copyright 2009 Petr Skoda (http://skodak.org) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ -/** Require {@link portfoliolib.php} */ -require_once($CFG->libdir.'/portfoliolib.php'); +/** + * List of features supported in Resource module + * @param string $feature FEATURE_xx constant for requested feature + * @return mixed True if module supports feature, false if not, null if doesn't know + */ +function resource_supports($feature) { + switch($feature) { + case FEATURE_MOD_ARCHETYPE: return MOD_ARCHETYPE_RESOURCE; + case FEATURE_GROUPS: return false; + case FEATURE_GROUPINGS: return false; + case FEATURE_GROUPMEMBERSONLY: return true; + case FEATURE_MOD_INTRO: return true; + case FEATURE_COMPLETION_TRACKS_VIEWS: return true; + case FEATURE_GRADE_HAS_GRADE: return false; + case FEATURE_GRADE_OUTCOMES: return false; -/** RESOURCE_LOCALPATH = LOCALPATH */ -define('RESOURCE_LOCALPATH', 'LOCALPATH'); + default: return null; + } +} /** - * @global array $RESOURCE_WINDOW_OPTIONS - * @name $RESOURCE_WINDOW_OPTIONS + * Returns all other caps used in module + * @return array */ -global $RESOURCE_WINDOW_OPTIONS; // must be global because it might be included from a function! -$RESOURCE_WINDOW_OPTIONS = array('resizable', 'scrollbars', 'directories', 'location', - 'menubar', 'toolbar', 'status', 'width', 'height'); +function resource_get_extra_capabilities() { + return array('moodle/site:accessallgroups'); +} /** - * resource_base is the base class for resource types - * - * This class provides all the functionality for a resource - * @package mod-resource - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * This function is used by the reset_course_userdata function in moodlelib. + * @param $data the data submitted from the reset course. + * @return array status array */ -class resource_base { - - var $cm; - var $course; - var $resource; - var $navlinks; - - /** - * Constructor for the base resource class - * - * Constructor for the base resource class. - * If cmid is set create the cm, course, resource objects. - * and do some checks to make sure people can be here, and so on. - * - * @global stdClass - * @global object - * @global object - * @uses CONTEXT_MODULE - * @param int $cmid the current course module id - not set for new resources - */ - function resource_base($cmid=0) { - global $CFG, $COURSE, $DB; - - $this->navlinks = array(); - - if ($cmid) { - if (! $this->cm = get_coursemodule_from_id('resource', $cmid)) { - print_error('invalidcoursemodule'); - } - - if (! $this->course = $DB->get_record("course", array("id"=>$this->cm->course))) { - print_error('coursemisconf'); - } +function resource_reset_userdata($data) { + return array(); +} - if (! $this->resource = $DB->get_record("resource", array("id"=>$this->cm->instance))) { - print_error('invalidid', 'resource'); - } +/** + * List of view style log actions + * @return array + */ +function resource_get_view_actions() { + return array('view','view all'); +} - $this->strresource = get_string("modulename", "resource"); - $this->strresources = get_string("modulenameplural", "resource"); +/** + * List of update style log actions + * @return array + */ +function resource_get_post_actions() { + return array('update', 'add'); +} - if (!$this->cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $this->cm->id))) { - $pagetitle = strip_tags($this->course->shortname.': '.$this->strresource); - $navigation = build_navigation($this->navlinks, $this->cm); +/** + * Add resource instance. + * @param object $data + * @param object $mform + * @return int new resoruce instance id + */ +function resource_add_instance($data, $mform) { + global $CFG, $DB; + require_once("$CFG->libdir/resourcelib.php"); - print_header($pagetitle, $this->course->fullname, $navigation, "", "", true, '', navmenu($this->course, $this->cm)); - notice(get_string("activityiscurrentlyhidden"), "$CFG->wwwroot/course/view.php?id={$this->course->id}"); - } + $cmid = $data->coursemodule; + $draftitemid = $data->files; - } else { - $this->course = $COURSE; - } + $data->timemodified = time(); + $displayoptions = array(); + if ($data->display == RESOURCELIB_DISPLAY_POPUP) { + $displayoptions['popupwidth'] = $data->popupwidth; + $displayoptions['popupheight'] = $data->popupheight; } - - - /** - * Display function does nothing in the base class - */ - function display() { - + if (in_array($data->display, array(RESOURCELIB_DISPLAY_AUTO, RESOURCELIB_DISPLAY_EMBED, RESOURCELIB_DISPLAY_FRAME))) { + $displayoptions['printheading'] = (int)!empty($data->printheading); + $displayoptions['printintro'] = (int)!empty($data->printintro); } + $data->displayoptions = serialize($displayoptions); + $data->id = $DB->insert_record('resource', $data); - /** - * Display the resource with the course blocks. - */ - function display_course_blocks_start() { - global $CFG, $USER, $PAGE; - - /// 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 => ''); + // we need to use context now, so we need to make sure all needed info is already in db + $DB->set_field('course_modules', 'instance', $data->id, array('id'=>$cmid)); + $context = get_context_instance(CONTEXT_MODULE, $cmid); - $PAGE->print_header($this->course->shortname.': %fullname%', $morenavlinks, "", "", - update_module_button($this->cm->id, $this->course->id, $this->strresource)); + if ($draftitemid) { + file_save_draft_area_files($draftitemid, $context->id, 'resource_content', 0, array('subdirs'=>true)); } - - /** - * Finish displaying the resource with the course blocks - */ - function display_course_blocks_end() { - global $CFG, $THEME; - - $PAGE = $this->PAGE; - $pageblocks = blocks_setup($PAGE); - $blocks_preferred_width = bounded_number(180, blocks_preferred_width($pageblocks[BLOCK_POS_RIGHT]), 210); - - $lt = (empty($THEME->layouttable)) ? array('left', 'middle', 'right') : $THEME->layouttable; - foreach ($lt as $column) { - if ($column != 'middle') { - array_shift($lt); - } else if ($column == 'middle') { - break; - } + $fs = get_file_storage(); + $files = $fs->get_area_files($context->id, 'resource_content', 0, '', false); + if (count($files) == 1) { + $file = reset($files); + $path = $file->get_filepath().$file->get_filename(); + if ($path !== $data->mainfile) { + $data->mainfile = $path; + $DB->set_field('resource', 'mainfile', $path, array('id'=>$data->id)); } - foreach ($lt as $column) { - switch ($column) { - case 'left': - if((blocks_have_content($pageblocks, BLOCK_POS_LEFT) || $PAGE->user_is_editing())) { - echo ''; - print_container_start(); - blocks_print_group($PAGE, $pageblocks, BLOCK_POS_LEFT); - print_container_end(); - echo ''; - } - break; - - case 'middle': - echo ''; - print_container_end(); - echo ''; - break; - - case 'right': - if((blocks_have_content($pageblocks, BLOCK_POS_RIGHT) || $PAGE->user_is_editing())) { - echo ''; - print_container_start(); - blocks_print_group($PAGE, $pageblocks, BLOCK_POS_RIGHT); - print_container_end(); - echo ''; - } - break; - } - } - - echo ''; - - print_footer($this->course); - - } - - /** - * Given an object containing all the necessary data, - * (defined by the form in mod_form.php) this function - * will create a new instance and return the id number - * of the new instance. - * - * @global object - * @param object $resource - * @return int|bool - */ - function add_instance($resource) { - global $DB; - - $resource->timemodified = time(); - - return $DB->insert_record("resource", $resource); } - /** - * Given an object containing all the necessary data, - * (defined by the form in mod_form.php) this function - * will update an existing instance with new data. - * - * @global object - * @param object $resource - * @return bool - */ - function update_instance($resource) { - global $DB; - - $resource->id = $resource->instance; - $resource->timemodified = time(); - - return $DB->update_record("resource", $resource); - } + return $data->id; +} - /** - * Given an object containing the resource data - * this function will permanently delete the instance - * and any data that depends on it. - * - * @global object - * @param object $resource - * @return bool - */ - function delete_instance($resource) { - global $DB; - - $result = true; - - if (! $DB->delete_records("resource", array("id"=>$resource->id))) { - $result = false; - } +/** + * Update resource instance. + * @param object $data + * @param object $mform + * @return bool true + */ +function resource_update_instance($data, $mform) { + global $CFG, $DB; + require_once("$CFG->libdir/resourcelib.php"); - return $result; - } + $cmid = $data->coursemodule; + $draftitemid = $data->files; - /** - * - */ - function setup_elements(&$mform) { - //override to add your own options - } + $data->timemodified = time(); + $data->id = $data->instance; + $data->revision++; - /** - * - */ - function setup_preprocessing(&$default_values){ - //override to add your own options + $displayoptions = array(); + if ($data->display == RESOURCELIB_DISPLAY_POPUP) { + $displayoptions['popupwidth'] = $data->popupwidth; + $displayoptions['popupheight'] = $data->popupheight; } - - /** - * @todo penny implement later - see MDL-15758 - */ - function portfolio_prepare_package_uploaded($exporter) { - // @todo penny implement later - see MDL-15758 - + if (in_array($data->display, array(RESOURCELIB_DISPLAY_AUTO, RESOURCELIB_DISPLAY_EMBED, RESOURCELIB_DISPLAY_FRAME))) { + $displayoptions['printheading'] = (int)!empty($data->printheading); + $displayoptions['printintro'] = (int)!empty($data->printintro); } + $data->displayoptions = serialize($displayoptions); - /** - * @uses FORMAT_MOODLE - * @uses FORMAT_HTML - * @param object $exporter - * @param bool $text - * @return int|bool - */ - function portfolio_prepare_package_online($exporter, $text=false) { - $filename = clean_filename($this->cm->name . '.' . 'html'); - $formatoptions = (object)array('noclean' => true); - $format = (($text) ? FORMAT_MOODLE : FORMAT_HTML); - $content = format_text($this->resource->alltext, $format, $formatoptions, $this->course->id); - return $exporter->write_new_file($content, $filename, false); - } + $DB->update_record('resource', $data); - /** - * @param bool $text - * @uses FORMAT_MOODLE - * @uses FORMAT_HTML - * @return string - */ - function portfolio_get_sha1_online($text=false) { - $formatoptions = (object)array('noclean' => true); - $format = (($text) ? FORMAT_MOODLE : FORMAT_HTML); - $content = format_text($this->resource->alltext, $format, $formatoptions, $this->course->id); - return sha1($content); + $context = get_context_instance(CONTEXT_MODULE, $cmid); + if ($draftitemid) { + file_save_draft_area_files($draftitemid, $context->id, 'resource_content', 0, array('subdirs'=>true)); } - /** - * @todo penny implement later. - */ - function portfolio_get_sha1_uploaded() { - // @todo penny implement later. + $fs = get_file_storage(); + $files = $fs->get_area_files($context->id, 'resource_content', 0, '', false); + if (count($files) == 1) { + $file = reset($files); + $path = $file->get_filepath().$file->get_filename(); + if ($path !== $data->mainfile) { + $data->mainfile = $path; + $DB->set_field('resource', 'mainfile', $path, array('id'=>$data->id)); + } } -} /// end of class definition - - -/** - * @global stdClass - * @uses PARAM_SAFEDIR - * @param object $resource - * @return int|bool - */ -function resource_add_instance($resource) { - global $CFG; - - $resource->type = clean_param($resource->type, PARAM_SAFEDIR); // Just to be safe - - require_once("$CFG->dirroot/mod/resource/type/$resource->type/resource.class.php"); - $resourceclass = "resource_$resource->type"; - $res = new $resourceclass(); - - return $res->add_instance($resource); -} - -/** - * @global stdClass - * @uses PARAM_SAFEDIR - * @param object $resource - * @return bool - */ -function resource_update_instance($resource) { - global $CFG; - - $resource->type = clean_param($resource->type, PARAM_SAFEDIR); // Just to be safe - - require_once("$CFG->dirroot/mod/resource/type/$resource->type/resource.class.php"); - $resourceclass = "resource_$resource->type"; - $res = new $resourceclass(); - - return $res->update_instance($resource); + return true; } /** - * @global stdClass - * @global object - * @uses PARAM_SAFEDIR + * Delete resource instance. * @param int $id - * @return bool + * @return bool true */ function resource_delete_instance($id) { - global $CFG, $DB; + global $DB; - if (! $resource = $DB->get_record("resource", array("id"=>$id))) { + if (!$resource = $DB->get_record('resource', array('id'=>$id))) { return false; } - $resource->type = clean_param($resource->type, PARAM_SAFEDIR); // Just to be safe + // note: all context files are deleted automatically - require_once("$CFG->dirroot/mod/resource/type/$resource->type/resource.class.php"); - $resourceclass = "resource_$resource->type"; - $res = new $resourceclass(); + $DB->delete_records('resource', array('id'=>$resource->id)); - return $res->delete_instance($resource); + return true; } /** - * - * @global object + * Return use outline * @param object $course * @param object $user * @param object $mod @@ -369,14 +202,14 @@ function resource_delete_instance($id) { function resource_user_outline($course, $user, $mod, $resource) { global $DB; - if ($logs = $DB->get_records("log", array('userid'=>$user->id, 'module'=>'resource', - 'action'=>'view', 'info'=>$resource->id), "time ASC")) { + if ($logs = $DB->get_records('log', array('userid'=>$user->id, 'module'=>'resource', + 'action'=>'view', 'info'=>$resource->id), 'time ASC')) { $numviews = count($logs); $lastlog = array_pop($logs); $result = new object(); - $result->info = get_string("numviews", "", $numviews); + $result->info = get_string('numviews', '', $numviews); $result->time = $lastlog->time; return $result; @@ -385,8 +218,7 @@ function resource_user_outline($course, $user, $mod, $resource) { } /** - * @global stdClass - * @global object + * Return use complete * @param object $course * @param object $user * @param object $mod @@ -395,24 +227,23 @@ function resource_user_outline($course, $user, $mod, $resource) { function resource_user_complete($course, $user, $mod, $resource) { global $CFG, $DB; - if ($logs = $DB->get_records("log", array('userid'=>$user->id, 'module'=>'resource', - 'action'=>'view', 'info'=>$resource->id), "time ASC")) { + if ($logs = $DB->get_records('log', array('userid'=>$user->id, 'module'=>'resource', + 'action'=>'view', 'info'=>$resource->id), 'time ASC')) { $numviews = count($logs); $lastlog = array_pop($logs); - $strmostrecently = get_string("mostrecently"); - $strnumviews = get_string("numviews", "", $numviews); + $strmostrecently = get_string('mostrecently'); + $strnumviews = get_string('numviews', '', $numviews); echo "$strnumviews - $strmostrecently ".userdate($lastlog->time); } else { - print_string("neverseen", "resource"); + print_string('neverseen', 'resource'); } } /** * Returns the users with data in one resource - * (NONE, byt must exists on EVERY mod !!) * * @param int $resourceid * @return bool false @@ -428,519 +259,171 @@ function resource_get_participants($resourceid) { * * See {@link get_array_of_activities()} in course/lib.php * - * @global stdClass - * @global object * @param object $coursemodule * @return object info */ function resource_get_coursemodule_info($coursemodule) { - global $CFG, $DB; - - $info = NULL; - - if ($resource = $DB->get_record("resource", array("id"=>$coursemodule->instance), 'id, popup, reference, type, name')) { - $info = new object(); - $info->name = $resource->name; - if (!empty($resource->popup)) { - $info->extra = urlencode("onclick=\"this.target='resource$resource->id'; return ". - "openpopup('/mod/resource/view.php?inpopup=true&id=". - $coursemodule->id. - "','resource$resource->id','$resource->popup');\""); - } - - require_once($CFG->libdir.'/filelib.php'); - - $customicon = $CFG->dirroot.'/mod/resource/type/'.$resource->type.'/icon.gif'; - if ($resource->type == 'file') { - $icon = mimeinfo("icon", $resource->reference); - if ($icon != 'unknown.gif') { - $info->icon ="f/$icon"; - } else { - $info->icon ="f/web.gif"; - } - } else if ($resource->type == 'directory') { - $info->icon ="f/folder.gif"; - } else if (file_exists($customicon)) { - $info->icon ='mod/resource/type/'.$resource->type.'/icon.gif'; - } - } - - return $info; -} + global $CFG, $DB; + require_once("$CFG->libdir/filelib.php"); + require_once("$CFG->dirroot/mod/resource/locallib.php"); -/** - * @param string $text - * @param string $url - * @param string $tagtoparse - * @param string $keytoparse - * @param string $prefix - * @return string - */ -function resource_redirect_tags($text, $url, $tagtoparse, $keytoparse,$prefix = "" ) { - $valid = 1; - if ( strpos($url,"?") == FALSE ) { - $valid = 1; + if (!$resource = $DB->get_record('resource', array('id'=>$coursemodule->instance), 'id, name, display, displayoptions, tobemigrated, mainfile, revision')) { + return NULL; } - if ( $valid ) { - $lastpoint = strrpos($url,"."); - $lastslash = strrpos($url,"/"); - if ( $lastpoint > $lastslash ) { - $root = substr($url,0,$lastslash+1); - } else { - $root = $url; - } - if ( $root == "http://" or - $root == "https://") { - $root = $url; - } - if ( substr($root,strlen($root)-1) == '/' ) { - $root = substr($root,0,-1); - } - $mainroot = $root; - $lastslash = strrpos($mainroot,"/"); - while ( $lastslash > 9) { - $mainroot = substr($mainroot,0,$lastslash); - - $lastslash = strrpos($mainroot,"/"); - } + $info = new object(); + $info->name = $resource->name; - $regex = "/<$tagtoparse (.+?)>/is"; - $count = preg_match_all($regex, $text, $hrefs); - for ( $i = 0; $i < $count; $i++) { - $tag = $hrefs[1][$i]; - - $poshref = strpos(strtolower($tag),strtolower($keytoparse)); - $start = $poshref + strlen($keytoparse); - $left = substr($tag,0,$start); - if ( $tag[$start] == '"' ) { - $left .= '"'; - $start++; - } - $posspace = strpos($tag," ", $start+1); - $right = ""; - if ( $posspace != FALSE) { - $right = substr($tag, $posspace); - } - $end = strlen($tag)-1; - if ( $tag[$end] == '"' ) { - $right = '"' . $right; - } - $finalurl = substr($tag,$start,$end-$start+$diff); - // Here, we could have these possible values for $finalurl: - // file.ext Add current root dir - // http://(domain) don't care - // http://(domain)/ don't care - // http://(domain)/folder don't care - // http://(domain)/folder/ don't care - // http://(domain)/folder/file.ext don't care - // folder/ Add current root dir - // folder/file.ext Add current root dir - // /folder/ Add main root dir - // /folder/file.ext Add main root dir - - // Special case: If finalurl contains a ?, it won't be parsed - $valid = 1; - - if ( strpos($finalurl,"?") == FALSE ) { - $valid = 1; - } - if ( $valid ) { - if ( $finalurl[0] == "/" ) { - $finalurl = $mainroot . $finalurl; - } elseif ( strtolower(substr($finalurl,0,7)) != "http://" and - strtolower(substr($finalurl,0,8)) != "https://") { - if ( $finalurl[0] == "/") { - $finalurl = $mainroot . $finalurl; - } else { - $finalurl = "$root/$finalurl"; - } - } - - $text = str_replace($tag,"$left$prefix$finalurl$right",$text); - } - } + if ($resource->tobemigrated) { + $info->icon ='i/cross_red_big'; + return $info; } - return $text; -} -/** - * @param string $path - * @return bool - */ -function resource_is_url($path) { - if (strpos($path, '://')) { // eg http:// https:// ftp:// etc - return true; - } - if (strpos($path, '/') === 0) { // Starts with slash - return true; - } - return false; -} + $info->icon = str_replace(array('.gif', '.png'), '', file_extension_icon($resource->mainfile)); -/** - * @global stdClass - * @uses MOD_CLASS_RESOURCE - * @return array - */ -function resource_get_types() { - global $CFG; + $display = resource_get_final_display_type($resource); - $types = array(); + if ($display == RESOURCELIB_DISPLAY_POPUP) { + $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&redirect=1"; + $options = empty($resource->displayoptions) ? array() : unserialize($resource->displayoptions); + $width = empty($options['popupwidth']) ? 620 : $options['popupwidth']; + $height = empty($options['popupheight']) ? 450 : $options['popupheight']; + $wh = "width=$width,height=$height,toolbar=no,location=no,menubar=no,copyhistory=no,status=no,directories=no,scrollbars=yes,resizable=yes"; + $info->extra = urlencode("onclick=\"window.open('$fullurl', '', '$wh'); return false;\""); - $standardresources = array('text','html','file','directory'); - foreach ($standardresources as $resourcetype) { - $type = new object(); - $type->modclass = MOD_CLASS_RESOURCE; - $type->name = $resourcetype; - $type->type = "resource&type=$resourcetype"; - $type->typestr = resource_get_name($resourcetype); - $types[] = $type; - } + } else if ($display == RESOURCELIB_DISPLAY_NEW) { + $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&redirect=1"; + $info->extra = urlencode("onclick=\"window.open('$fullurl'); return false;\""); - /// Drop-in extra resource types - $resourcetypes = get_plugin_list('resource'); - foreach ($resourcetypes as $resourcetype => $dir) { - if (!empty($CFG->{'resource_hide_'.$resourcetype})) { // Not wanted - continue; - } - if (!in_array($resourcetype, $standardresources)) { - $type = new object(); - $type->modclass = MOD_CLASS_RESOURCE; - $type->name = $resourcetype; - $type->type = "resource&type=$resourcetype"; - $type->typestr = resource_get_name($resourcetype); - $types[] = $type; - } + } else if ($display == RESOURCELIB_DISPLAY_OPEN) { + $fullurl = "$CFG->wwwroot/mod/resource/view.php?id=$coursemodule->id&redirect=1"; + $info->extra = urlencode("onclick=\"window.location.href ='$fullurl';return false;\""); + + } else if ($display == RESOURCELIB_DISPLAY_DOWNLOAD) { + // do not open any window because it would be left there after download + $context = get_context_instance(CONTEXT_MODULE, $coursemodule->id); + $path = '/'.$context->id.'/resource_content/'.$resource->revision.$resource->mainfile; + $fullurl = addslashes_js(file_encode_url($CFG->wwwroot.'/pluginfile.php', $path, true)); + $info->extra = urlencode("onclick=\"window.open('$fullurl'); return false;\""); } - return $types; + return $info; } -/** - * @return array - */ -function resource_get_view_actions() { - return array('view','view all'); -} /** + * Lists all browsable file areas + * @param object $course + * @param object $cm + * @param object $context * @return array */ -function resource_get_post_actions() { - return array(); +function resource_get_file_areas($course, $cm, $context) { + $areas = array(); + if (has_capability('moodle/course:managefiles', $context)) { + $areas['resource_content'] = get_string('resourcecontent', 'resource'); + } + return $areas; } /** - * @global stdClass - * @global object + * File browsing support for resource module ontent area. + * @param object $browser + * @param object $areas * @param object $course - * @param string $wdir - * @param string $oldname - * @param string $name + * @param object $cm + * @param object $context + * @param string $filearea + * @param int $itemid + * @param string $filepath + * @param string $filename + * @return object file_info instance or null if not found */ -function resource_renamefiles($course, $wdir, $oldname, $name) { - global $CFG, $DB; - - $status = '

'.get_string('affectedresources', 'resource').':

    '; - $updates = false; - - $old = trim($wdir.'/'.$oldname, '/'); - $new = trim($wdir.'/'.$name, '/'); - - $sql = "SELECT r.id, r.reference, r.name, cm.id AS cmid - FROM {resource} r, {course_modules} cm, {modules} m - WHERE r.course = :courseid - AND m.name = 'resource' - AND cm.module = m.id - AND cm.instance = r.id - AND (r.type = 'file' OR r.type = 'directory') - AND (r.reference LIKE :old1 OR r.reference = :old2)"; - $params = array('courseid'=>$course->id, 'old1'=>"{$old}/%", 'old2'=>$old); - if ($resources = $DB->get_records_sql($sql, $params)) { - foreach ($resources as $resource) { - $r = new object(); - $r->id = $resource->id; - $r->reference = ''; - if ($resource->reference == $old) { - $r->reference = $new; - } else { - $r->reference = preg_replace('|^'.preg_quote($old, '|').'/|', $new.'/', $resource->reference); - } - if ($r->reference !== '') { - $updates = true; - $status .= "
  • wwwroot/mod/resource/view.php?id=$resource->cmid\" target=\"_blank\">$resource->name: $resource->reference ==> $r->reference
  • "; - if (!empty($CFG->resource_autofilerename)) { - $DB->update_record('resource', $r); - } - } - } - } - $status .= '

'; +function resource_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) { + global $CFG; - if ($updates) { - echo $status; - if (empty($CFG->resource_autofilerename)) { - notify(get_string('warningdisabledrename', 'resource')); - } - } -} + $canwrite = has_capability('moodle/course:managefiles', $context); -/** - * @global stdClass - * @global object - * @param object $course - * @param array $files - * @return bool - */ -function resource_delete_warning($course, $files) { - global $CFG, $DB; + $fs = get_file_storage(); - $found = array(); + if ($filearea === 'resource_content') { + $filepath = is_null($filepath) ? '/' : $filepath; + $filename = is_null($filename) ? '.' : $filename; - foreach($files as $key=>$file) { - $files[$key] = trim($file, '/'); - } - $sql = "SELECT r.id, r.reference, r.name, cm.id AS cmid - FROM {resource} r, - {course_modules} cm, - {modules} m - WHERE r.course = ? - AND m.name = 'resource' - AND cm.module = m.id - AND cm.instance = r.id - AND (r.type = 'file' OR r.type = 'directory')"; - if ($resources = $DB->get_records_sql($sql, array($course->id))) { - foreach ($resources as $resource) { - if ($resource->reference == '') { - continue; // top shared directory does not prevent anything - } - if (in_array($resource->reference, $files)) { - $found[$resource->id] = $resource; + $urlbase = $CFG->wwwroot.'/pluginfile.php'; + if (!$storedfile = $fs->get_file($context->id, $filearea, 0, $filepath, $filename)) { + if ($filepath === '/' and $filename === '.') { + $storedfile = new virtual_root_file($context->id, $filearea, 0); } else { - foreach($files as $file) { - if (preg_match('|^'.preg_quote($file, '|').'/|', $resource->reference)) { - $found[$resource->id] = $resource; - } - } + // not found + return null; } } + require_once("$CFG->dirroot/mod/resource/locallib.php"); + return new resource_content_file_info($browser, $context, $storedfile, $urlbase, $areas[$filearea], true, true, $canwrite, false); } - if (!empty($found)) { - - print_simple_box_start("center"); - echo '

'.get_string('affectedresources', 'resource').':

'; - print_simple_box_end(); + // note: resource_intro handled in file_browser automatically - return true; - } else { - return false; - } + return null; } /** - * This function is used by the reset_course_userdata function in moodlelib. - * - * @param $data the data submitted from the reset course. - * @return array status array - */ -function resource_reset_userdata($data) { - return array(); -} - -/** - * Returns all other caps used in module - * - * @return array - */ -function resource_get_extra_capabilities() { - return array('moodle/site:accessallgroups'); -} - -/** - * @package mod-resource - * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} - * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + * Serves the resource files. + * @param object $course + * @param object $cminfo + * @param object $context + * @param string $filearea + * @param array $args + * @param bool $forcedownload + * @return bool false if file not found, does not return if found - justsend the file */ -class resource_portfolio_caller extends portfolio_module_caller_base { - - private $resource; - private $resourcefile; - - /** - * @return array - */ - public static function expected_callbackargs() { - return array( - 'id' => true, - ); - } - - /** - * @global stdClass - * @global object - */ - public function load_data() { - global $CFG, $DB; - if (!$this->cm = get_coursemodule_from_instance('resource', $this->id)) { - throw new portfolio_caller_exception('invalidid'); - } - $this->cm->type = $DB->get_field('resource', 'type', array('id' => $this->cm->instance)); - $resourceclass = 'resource_'. $this->cm->type; - $this->resourcefile = $CFG->dirroot.'/mod/resource/type/'.$this->cm->type.'/resource.class.php'; - require_once($this->resourcefile); - $this->resource= new $resourceclass($this->cm->id); - if (!is_callable(array($this->resource, 'portfolio_prepare_package')) || !is_callable(array($this->resource, 'portfolio_get_sha1'))) { - throw new portfolio_exception('portfolionotimplemented', 'resource', null, $this->cm->type); - } - $this->supportedformats = array(self::type_to_format($this->cm->type)); - } +function resource_pluginfile($course, $cminfo, $context, $filearea, $args, $forcedownload) { + global $CFG, $DB; + require_once("$CFG->libdir/resourcelib.php"); - /** - * @uses PORTFOLIO_FORMAT_FILE - * @uses PORTFOLIO_FORMAT_PLAINHTML - * @uses PORTFOLIO_FORMAT_TEXT - * @param string $type - * @return string - */ - public static function type_to_format($type) { - // this is kind of yuk... but there's just not good enough OO here - $format = PORTFOLIO_FORMAT_FILE; - switch ($type) { - case 'html': - $format = PORTFOLIO_FORMAT_PLAINHTML; - case 'text': - $format = PORTFOLIO_FORMAT_TEXT; - case 'file': - // $format = portfolio_format_from_file($file); // change after we switch upload type resources over to new files api. - } - return $format; + if (!$cminfo->uservisible) { + return false; } - /** - * @global stdClass - * @return void - */ - public function __wakeup() { - global $CFG; - if (empty($CFG)) { - return; // too early yet - } - require_once($this->resourcefile); - $this->resource = unserialize(serialize($this->resource)); + if ($filearea !== 'resource_content') { + // intro is handled automatically in pluginfile.php + return false; } - /** - * @todo penny check filesize if the type is uploadey (not implemented yet) - * like this: return portfolio_expected_time_file($this->file); or whatever - * - * @return string - */ - public function expected_time() { - return PORTFOLIO_TIME_LOW; + if (!$cm = get_coursemodule_from_instance('resource', $cminfo->instance, $course->id)) { + return false; } - /** - * - */ - public function prepare_package() { - return $this->resource->portfolio_prepare_package($this->exporter); - } + require_course_login($course, true, $cm); - /** - * @uses CONTEXT_MODULE - * @return bool - */ - public function check_permissions() { - return has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $this->cm->id)); - } + array_shift($args); // ignore revision - designed to prevent caching problems only - /** - * @uses CONTEXT_MODULE - * @param object $resource - * @param mixed $format - * @param bool $return - * @return mixed - */ - public static function add_button($resource, $format=null, $return=false) { - if (!has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $resource->cm->id))) { - return; - } - if (!is_callable(array($resource, 'portfolio_prepare_package')) || !is_callable(array($resource, 'portfolio_get_sha1'))) { - debugging(get_string('portfolionotimplemented', 'resource')); + $fs = get_file_storage(); + $relativepath = '/'.implode('/', $args); + $fullpath = $context->id.$filearea.'0'.$relativepath; + if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) { + $resource = $DB->get_record('resource', array('id'=>$cminfo->instance), 'id, legacyfiles', MUST_EXIST); + if ($resource->legacyfiles != RESOURCELIB_LEGACYFILES_ACTIVE) { return false; } - $callersupports = array(self::type_to_format($resource->resource->type)); - if ($resource->resource->type == 'file') { - // $callersupports = array(portfolio_format_from_file($file); - } - $button = new portfolio_add_button(); - $button->set_callback_options('resource_portfolio_caller', array('id' => $resource->cm->instance), '/mod/resource/lib.php'); - $button->set_formats($callersupports); - if ($return) { - return $button->to_html($format); + require_once("$CFG->dirroot/mod/resource/db/upgradelib.php"); + if (!$file = resource_try_file_migration($relativepath, $cminfo->id, $cminfo->course, 'resource_content', 0)) { + return false; } - $button->render($format); - } - - /** - * @return string - */ - public function get_sha1() { - return $this->resource->portfolio_get_sha1(); + // file migrate - update flag + $resource->legacyfileslast = time(); + $DB->update_record('resource', $resource); } - /** - * @return string - */ - public static function display_name() { - return get_string('modulename', 'resource'); - } -} - -/** - * @uses FEATURE_GROUPS - * @uses FEATURE_GROUPINGS - * @uses FEATURE_GROUPMEMBERSONLY - * @uses FEATURE_MOD_INTRO - * @uses FEATURE_COMPLETION_TRACKS_VIEWS - * @uses FEATURE_GRADE_HAS_GRADE - * @uses FEATURE_GRADE_OUTCOMES - * @param string $feature FEATURE_xx constant for requested feature - * @return mixed True if module supports feature, false if not, null if doesn't know - */ -function resource_supports($feature) { - switch($feature) { - case FEATURE_GROUPS: return false; - case FEATURE_GROUPINGS: return false; - case FEATURE_GROUPMEMBERSONLY: return true; - case FEATURE_MOD_INTRO: return true; - case FEATURE_COMPLETION_TRACKS_VIEWS: return true; - case FEATURE_GRADE_HAS_GRADE: return false; - case FEATURE_GRADE_OUTCOMES: return false; - case FEATURE_MOD_SUBPLUGINS: return array('resource'=>'mod/resource/type'); // to be removed in 2.0 - - default: return null; + // should we apply filters? + $mimetype = $file->get_mimetype(); + if ($mimetype = 'text/html' or $mimetype = 'text/plain') { + $filter = $DB->get_field('resource', 'filterfiles', array('id'=>$cminfo->instance)); + } else { + $filter = 0; } -} -/** - * Returns the full name of the given resource type. The name can - * either be set at the resource type level or at the resource module - * level. - * - * @param string $type shortname (or directory name) of the resource type - * @return string - */ -function resource_get_name($type) { - $name = get_string("resourcetype$type", "resource_$type"); - if (substr($name, 0, 2) === '[[') { - $name = get_string("resourcetype$type", 'resource'); - } - return $name; + // finally send the file + send_stored_file($file, 86400, $filter, $forcedownload); } diff --git a/mod/resource/locallib.php b/mod/resource/locallib.php new file mode 100644 index 0000000000000..aed8ceb318485 --- /dev/null +++ b/mod/resource/locallib.php @@ -0,0 +1,395 @@ +. + +/** + * Private resource module utility functions + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once("$CFG->libdir/filelib.php"); +require_once("$CFG->libdir/resourcelib.php"); +require_once("$CFG->dirroot/mod/resource/lib.php"); + +/** + * Redirected to migrated resource if needed, + * return if incorrect parameters specified + * @param int $oldid + * @param int $cmid + * @return void + */ +function resource_redirect_if_migrated($oldid, $cmid) { + global $DB, $CFG; + + if ($oldid) { + $old = $DB->get_record('resource_old', array('oldid'=>$oldid)); + } else { + $old = $DB->get_record('resource_old', array('cmid'=>$cmid)); + } + + if (!$old) { + return; + } + + redirect("$CFG->wwwroot/mod/$old->newmodule/view.php?id=".$old->cmid); +} + +/** + * Display embedded resource file. + * @param object $resource + * @param object $cm + * @param object $course + * @param stored_file $file main file + * @return does not return + */ +function resource_display_embed($resource, $cm, $course, $file) { + global $CFG, $PAGE, $OUTPUT; + + $clicktoopen = resource_get_clicktoopen($file, $resource->revision); + + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $path = '/'.$context->id.'/resource_content/'.$resource->revision.$file->get_filepath().$file->get_filename(); + $fullurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', $path, false); + + $mimetype = $file->get_mimetype(); + $title = $resource->name; + + if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image + $code = resourcelib_embed_image($fullurl, $title); + + } else if ($mimetype == 'audio/mp3') { + // MP3 audio file + $code = resourcelib_embed_mp3($fullurl, $title, $clicktoopen); + + } else if ($mimetype == 'video/x-flv') { + // Flash video file + $code = resourcelib_embed_flashvideo($fullurl, $title, $clicktoopen); + + } else if ($mimetype == 'application/x-shockwave-flash') { + // Flash file + $code = resourcelib_embed_flash($fullurl, $title, $clicktoopen); + + } else if (substr($mimetype, 0, 10) == 'video/x-ms') { + // Windows Media Player file + $code = resourcelib_embed_mediaplayer($fullurl, $title, $clicktoopen); + + } else if ($mimetype == 'video/quicktime') { + // Quicktime file + $code = resourcelib_embed_quicktime($fullurl, $title, $clicktoopen); + + } else if ($mimetype == 'video/mpeg') { + // Mpeg file + $code = resourcelib_embed_mpeg($fullurl, $title, $clicktoopen); + + } else if ($mimetype == 'audio/x-pn-realaudio') { + // RealMedia file + $code = resourcelib_embed_real($fullurl, $title, $clicktoopen); + + } else { + // anything else - just try object tag enlarged as much as possible + $code = resourcelib_embed_general($fullurl, $title, $clicktoopen, $mimetype); + $PAGE->requires->yui_lib('dom')->in_head(); + $PAGE->requires->js('mod/url/functions.js')->in_head(); + $PAGE->requires->js_function_call('url_init_object'); + } + + resource_print_header($resource, $cm, $course); + resource_print_heading($resource, $cm, $course); + + echo $code; + + resource_print_intro($resource, $cm, $course); + + echo $OUTPUT->footer(); + die; +} + +/** + * Display resource frames. + * @param object $resource + * @param object $cm + * @param object $course + * @param stored_file $file main file + * @return does not return + */ +function resource_display_frame($resource, $cm, $course, $file) { + global $PAGE, $OUTPUT, $CFG; + + $frame = optional_param('frameset', 'main', PARAM_ALPHA); + + if ($frame === 'top') { + $PAGE->set_generaltype('topframe'); + resource_print_header($resource, $cm, $course); + resource_print_heading($resource, $cm, $course); + resource_print_intro($resource, $cm, $course); + echo $OUTPUT->footer(); + die; + + } else { + $config = get_config('resource'); + $context = get_context_instance(CONTEXT_MODULE, $cm->id); + $path = '/'.$context->id.'/resource_content/'.$resource->revision.$file->get_filepath().$file->get_filename(); + $fileurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', $path, false); + $navurl = "$CFG->wwwroot/mod/resource/view.php?id=$cm->id&frameset=top"; + $title = strip_tags(format_string($course->shortname.': '.$resource->name)); + $framesize = $config->framesize; + $modulename = s(get_string('modulename','resource')); + $dir = get_string('thisdirection'); + + $file = << + + + + $title + + + + + + +EOF; + + @header('Content-Type: text/html; charset=utf-8'); + echo $file; + die; + } +} + +/** + * Internal function - create click to open text with link. + */ +function resource_get_clicktoopen($file, $revision, $extra='') { + global $CFG; + + $filename = $file->get_filename(); + $path = '/'.$file->get_contextid().'/resource_content/'.$revision.$file->get_filepath().$file->get_filename(); + $fullurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', $path, false); + + $string = get_string('clicktoopen2', 'resource', "$filename"); + + return $string; +} + +/** + * Internal function - create click to open text with link. + */ +function resource_get_clicktodownload($file, $revision) { + global $CFG; + + $filename = $file->get_filename(); + $path = '/'.$file->get_contextid().'/resource_content/'.$revision.$file->get_filepath().$file->get_filename(); + $fullurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', $path, true); + + $string = get_string('clicktodownload', 'resource', "$filename"); + + return $string; +} + +/** + * Print resource info and workaround link when JS not available. + * @param object $resource + * @param object $cm + * @param object $course + * @param stored_file $file main file + * @return does not return + */ +function resource_print_workaround($resource, $cm, $course, $file) { + global $CFG, $OUTPUT; + + resource_print_header($resource, $cm, $course); + resource_print_heading($resource, $cm, $course, true); + resource_print_intro($resource, $cm, $course, true); + + echo '
'; + switch (resource_get_final_display_type($resource)) { + case RESOURCELIB_DISPLAY_POPUP: + $path = '/'.$file->get_contextid().'/resource_content/'.$resource->revision.$file->get_filepath().$file->get_filename(); + $fullurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', $path, false); + $options = empty($resource->displayoptions) ? array() : unserialize($resource->displayoptions); + $width = empty($options['popupwidth']) ? 620 : $options['popupwidth']; + $height = empty($options['popupheight']) ? 450 : $options['popupheight']; + $wh = "width=$width,height=$height,toolbar=no,location=no,menubar=no,copyhistory=no,status=no,directories=no,scrollbars=yes,resizable=yes"; + $extra = "onclick=\"window.open('$fullurl', '', '$wh'); return false;\""; + echo resource_get_clicktoopen($file, $resource->revision, $extra); + break; + + case RESOURCELIB_DISPLAY_NEW: + $extra = 'onclick="this.target=\'_blank\'"'; + echo resource_get_clicktoopen($file, $resource->revision, $extra); + break; + + case RESOURCELIB_DISPLAY_DOWNLOAD: + echo resource_get_clicktodownload($file, $resource->revision); + break; + + case RESOURCELIB_DISPLAY_OPEN: + default: + echo resource_get_clicktoopen($file, $resource->revision); + break; + } + echo '
'; + + echo $OUTPUT->footer(); + die; +} + +/** + * Print resource header. + * @param object $resource + * @param object $cm + * @param object $course + * @return void + */ +function resource_print_header($resource, $cm, $course) { + global $PAGE, $OUTPUT; + + $PAGE->set_title($course->shortname.': '.$resource->name); + $PAGE->set_heading($course->fullname); + $PAGE->set_activity_record($resource); + $PAGE->set_button(update_module_button($cm->id, '', get_string('modulename', 'resource'))); + echo $OUTPUT->header(build_navigation('', $cm), navmenu($course, $cm)); +} + +/** + * Print resource heading. + * @param object $resource + * @param object $cm + * @param object $course + * @param bool $ignoresettings print even if not specified in modedit + * @return void + */ +function resource_print_heading($resource, $cm, $course, $ignoresettings=false) { + global $OUTPUT; + + $options = empty($resource->displayoptions) ? array() : unserialize($resource->displayoptions); + if ($ignoresettings or !empty($options['printheading'])) { + echo $OUTPUT->heading(format_string($resource->name), 2, 'main', 'resourceheading'); + } +} + +/** + * Print resource introduction. + * @param object $resource + * @param object $cm + * @param object $course + * @param bool $ignoresettings print even if not specified in modedit + * @return void + */ +function resource_print_intro($resource, $cm, $course, $ignoresettings=false) { + global $OUTPUT; + + $options = empty($resource->displayoptions) ? array() : unserialize($resource->displayoptions); + if ($ignoresettings or !empty($options['printintro'])) { + if (trim(strip_tags($resource->intro))) { + echo $OUTPUT->box_start('mod_introbox', 'resourceintro'); + echo format_module_intro('resource', $resource, $cm->id); + echo $OUTPUT->box_end(); + } + } +} + +/** + * Print warning that instance not migrated yet. + * @param object $resource + * @param object $cm + * @param object $course + * @return void, does not return + */ +function resource_print_tobemigrated($resource, $cm, $course) { + global $DB, $OUTPUT; + + $resoruce_old = $DB->get_record('resource_old', array('oldid'=>$resource->id)); + resource_print_header($resource, $cm, $course); + resource_print_heading($resource, $cm, $course); + resource_print_intro($resource, $cm, $course); + notify(get_string('notmigrated', 'resource', $resoruce_old->type)); + echo $OUTPUT->footer(); + die; +} + +/** + * Print warning that file can not be found. + * @param object $resource + * @param object $cm + * @param object $course + * @return void, does not return + */ +function resource_print_filenotfound($resource, $cm, $course) { + global $DB, $OUTPUT; + + $resoruce_old = $DB->get_record('resource_old', array('oldid'=>$resource->id)); + resource_print_header($resource, $cm, $course); + resource_print_heading($resource, $cm, $course); + resource_print_intro($resource, $cm, $course); + notify(get_string('notmigrated', 'resource', $resoruce_old->type)); + echo $OUTPUT->footer(); + die; +} + +/** + * Decide the best diaply format. + * @param object $resource + * @return int display type constant + */ +function resource_get_final_display_type($resource) { + global $CFG; + + if ($resource->display != RESOURCELIB_DISPLAY_AUTO) { + return $resource->display; + } + + static $download = array('application/zip', 'application/x-tar', 'application/g-zip'); // binary formats + static $embed = array('image/gif', 'image/jpeg', 'image/png', 'image/svg+xml', // images + 'application/x-shockwave-flash', 'video/x-flv', 'video/x-ms-wm', // video formats + 'video/quicktime', 'video/mpeg', + 'audio/mp3', 'audio/x-realaudio-plugin', 'x-realaudio-plugin', // audio formats + 'application/pdf', 'text/html', + ); + + $mimetype = mimeinfo('type', $resource->mainfile); + + if (in_array($mimetype, $download)) { + return RESOURCELIB_DISPLAY_DOWNLOAD; + } + if (in_array($mimetype, $embed)) { + return RESOURCELIB_DISPLAY_EMBED; + } + + // let the browser deal with it somehow + return RESOURCELIB_DISPLAY_OPEN; +} + +/** + * File browsing support class + */ +class resource_content_file_info extends file_info_stored { + public function get_parent() { + if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') { + return $this->browser->get_file_info($this->context); + } + return parent::get_parent(); + } + public function get_visible_name() { + if ($this->lf->get_filepath() === '/' and $this->lf->get_filename() === '.') { + return $this->topvisiblename; + } + return parent::get_visible_name(); + } +} diff --git a/mod/resource/mod_form.php b/mod/resource/mod_form.php index f1860c8b25dfd..2dc370b376d8e 100644 --- a/mod/resource/mod_form.php +++ b/mod/resource/mod_form.php @@ -1,33 +1,50 @@ dirroot.'/course/moodleform_mod.php'); -class mod_resource_mod_form extends moodleform_mod { - var $_resinstance; +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see . + +/** + * Resource configuration form + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require_once($CFG->dirroot.'/course/moodleform_mod.php'); +require_once($CFG->dirroot.'/mod/resource/locallib.php'); +require_once($CFG->libdir.'/filelib.php'); +class mod_resource_mod_form extends moodleform_mod { function definition() { global $CFG, $DB; $mform =& $this->_form; - // this hack is needed for different settings of each subtype - if (!empty($this->_instance)) { - if($res = $DB->get_record('resource', array('id'=>$this->_instance))) { - $type = $res->type; - } else { - print_error('invalidassignment', 'resource'); - } - } else { - $type = required_param('type', PARAM_ALPHA); - } - $mform->addElement('hidden', 'type', $type); - $mform->setDefault('type', $type); + $config = get_config('resource'); - require($CFG->dirroot.'/mod/resource/type/'.$type.'/resource.class.php'); - $resclass = 'resource_'.$type; - $this->_resinstance = new $resclass(); + if ($this->current->instance and $this->current->tobemigrated) { + // resource not migrated yet + $resoruce_old = $DB->get_record('resource_old', array('oldid'=>$this->current->instance)); + $mform->addElement('static', 'warning', '', get_string('notmigrated', 'resource', $resoruce_old->type)); + $mform->addElement('cancel'); + $this->standard_hidden_coursemodule_elements(); + return; + } -//------------------------------------------------------------------------------- + //------------------------------------------------------- $mform->addElement('header', 'general', get_string('general', 'form')); - $mform->addElement('text', 'name', get_string('name'), array('size'=>'48')); if (!empty($CFG->formatstringstriptags)) { $mform->setType('name', PARAM_TEXT); @@ -35,20 +52,152 @@ function definition() { $mform->setType('name', PARAM_CLEAN); } $mform->addRule('name', null, 'required', null, 'client'); + $this->add_intro_editor($config->requiremodintro); - $this->add_intro_editor(false); + //------------------------------------------------------- + $mform->addElement('header', 'contentsection', get_string('contentheader', 'resource')); + $mform->addElement('static', 'note', '', '(TODO: This filemanager + textfield is temporary until we create new file manager with main file support.)'); + $mform->addElement('filemanager', 'files', get_string('file')); + $mform->addElement('static', 'notex', '', '(TODO: Ignore main file when uploading only one file, if multiple files present use "/myfile.ext" to specify the main file.)'); + $mform->addElement('text', 'mainfile', 'Main file'); - $mform->addElement('header', 'typedesc', resource_get_name($type)); - $this->_resinstance->setup_elements($mform); + //------------------------------------------------------- + $mform->addElement('header', 'optionssection', get_string('optionsheader', 'resource')); + + if ($this->current->instance) { + $options = resourcelib_get_displayoptions(explode(',', $config->displayoptions), $this->current->display); + } else { + $options = resourcelib_get_displayoptions(explode(',', $config->displayoptions)); + } + + if (count($options) == 1) { + $mform->addElement('hidden', 'display'); + reset($options); + $mform->setDefault('display', key($options)); + } else { + $mform->addElement('select', 'display', get_string('displayselect', 'resource'), $options); + $mform->setDefault('display', $config->display); + $mform->setAdvanced('display', $config->display_adv); + } + + if (array_key_exists(RESOURCELIB_DISPLAY_POPUP, $options)) { + $mform->addElement('text', 'popupwidth', get_string('popupwidth', 'resource'), array('size'=>3)); + if (count($options) > 1) { + $mform->disabledIf('popupwidth', 'display', 'noteq', RESOURCELIB_DISPLAY_POPUP); + } + $mform->setType('popupwidth', PARAM_INT); + $mform->setDefault('popupwidth', $config->popupwidth); + $mform->setAdvanced('popupwidth', $config->popupwidth_adv); + + $mform->addElement('text', 'popupheight', get_string('popupheight', 'resource'), array('size'=>3)); + if (count($options) > 1) { + $mform->disabledIf('popupheight', 'display', 'noteq', RESOURCELIB_DISPLAY_POPUP); + } + $mform->setType('popupheight', PARAM_INT); + $mform->setDefault('popupheight', $config->popupheight); + $mform->setAdvanced('popupheight', $config->popupheight_adv); + } + + if (array_key_exists(RESOURCELIB_DISPLAY_AUTO, $options) or + array_key_exists(RESOURCELIB_DISPLAY_EMBED, $options) or + array_key_exists(RESOURCELIB_DISPLAY_FRAME, $options)) { + $mform->addElement('checkbox', 'printheading', get_string('printheading', 'resource')); + $mform->disabledIf('printheading', 'display', 'eq', RESOURCELIB_DISPLAY_POPUP); + $mform->disabledIf('printheading', 'display', 'eq', RESOURCELIB_DISPLAY_DOWNLOAD); + $mform->disabledIf('printheading', 'display', 'eq', RESOURCELIB_DISPLAY_OPEN); + $mform->disabledIf('printheading', 'display', 'eq', RESOURCELIB_DISPLAY_NEW); + $mform->setDefault('printheading', $config->printheading); + $mform->setAdvanced('printheading', $config->printheading_adv); + + $mform->addElement('checkbox', 'printintro', get_string('printintro', 'resource')); + $mform->disabledIf('printintro', 'display', 'eq', RESOURCELIB_DISPLAY_POPUP); + $mform->disabledIf('printintro', 'display', 'eq', RESOURCELIB_DISPLAY_DOWNLOAD); + $mform->disabledIf('printintro', 'display', 'eq', RESOURCELIB_DISPLAY_OPEN); + $mform->disabledIf('printintro', 'display', 'eq', RESOURCELIB_DISPLAY_NEW); + $mform->setDefault('printintro', $config->printintro); + $mform->setAdvanced('printintro', $config->printintro_adv); + } + $options = array('0' => get_string('none'), '1' => get_string('allfiles'), '2' => get_string('htmlfilesonly')); + $mform->addElement('select', 'filterfiles', get_string('filterfiles', 'resource'), $options); + $mform->setDefault('filterfiles', $config->filterfiles); + $mform->setAdvanced('filterfiles', $config->filterfiles_adv); + + // add legacy files flag only if used + if (isset($this->current->legacyfiles) and $this->current->legacyfiles != RESOURCELIB_LEGACYFILES_NO) { + $options = array(RESOURCE_LEGACYYFILES_DONE => get_string('legacyfilesdone', 'resource'), + RESOURCELIB_LEGACYFILES_ACTIVE => get_string('legacyfilesactive', 'resource')); + $mform->addElement('select', 'legacyfiles', get_string('legacyfiles', 'resource'), $options); + $mform->setAdvanced('legacyfiles', 1); + } + + //------------------------------------------------------- $this->standard_coursemodule_elements(); + //------------------------------------------------------- $this->add_action_buttons(); + + //------------------------------------------------------- + $mform->addElement('hidden', 'revision'); + $mform->setType('revision', PARAM_INT); + $mform->setDefault('revision', 1); + } + + function data_preprocessing(&$default_values) { + if ($this->current->instance and !$this->current->tobemigrated) { + $draftitemid = file_get_submitted_draft_itemid('files'); + file_prepare_draft_area($draftitemid, $this->context->id, 'resource_content', 0, array('subdirs'=>true)); + $default_values['files'] = $draftitemid; + } + if (!empty($default_values['displayoptions'])) { + $displayoptions = unserialize($default_values['displayoptions']); + if (isset($displayoptions['printintro'])) { + $default_values['printintro'] = $displayoptions['printintro']; + } + if (isset($displayoptions['printheading'])) { + $default_values['printheading'] = $displayoptions['printheading']; + } + if (!empty($displayoptions['popupwidth'])) { + $default_values['popupwidth'] = $displayoptions['popupwidth']; + } + if (!empty($displayoptions['popupheight'])) { + $default_values['popupheight'] = $displayoptions['popupheight']; + } + } } - function data_preprocessing(&$default_values){ - $this->_resinstance->setup_preprocessing($default_values); + function definition_after_data() { + if ($this->current->instance and $this->current->tobemigrated) { + // resource not migrated yet + return; + } + + parent::definition_after_data(); } + function validation($data, $files) { + global $USER; + + $errors = parent::validation($data, $files); + + $usercontext = get_context_instance(CONTEXT_USER, $USER->id); + $fs = get_file_storage(); + if (!$files = $fs->get_area_files($usercontext->id, 'user_draft', $data['files'], 'id', false)) { + $errors['files'] = get_string('required'); + return $errors; + } + if (count($files) == 1) { + // no need to select main file if only one picked + return $errors; + } + $filepaths = array(); + foreach ($files as $file) { + $filepaths[] = $file->get_filepath().$file->get_filename(); + } + if (!in_array($data['mainfile'], $filepaths)) { + $errors['mainfile'] = 'Please type correct main file path'; //TODO: will not be needed, do NOT localize! + } + return $errors; + } } -?> + diff --git a/mod/resource/readme.txt b/mod/resource/readme.txt new file mode 100644 index 0000000000000..bad422c5961fc --- /dev/null +++ b/mod/resource/readme.txt @@ -0,0 +1,32 @@ +This file is part of Moodle - http://moodle.org/ + +Moodle 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. + +Moodle 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 Moodle. If not, see . + +copyright 2009 Petr Skoda (http://skodak.org) +license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + + +Resource module +============= + +Resource module one of the successors to original 'file' type plugin of Resource module. + + +TODO: + * create better icon (?) + * reimplement portfolio support (?) + * new backup/restore (Eloy) + * old restore support (Eloy) + * file manager element with main file selection (Dongsheng) + * reimplement resource name filter as part of more general activitynames filter (skodak) diff --git a/mod/resource/restorelib.php b/mod/resource/restorelib.php deleted file mode 100644 index 6d78e4316b624..0000000000000 --- a/mod/resource/restorelib.php +++ /dev/null @@ -1,385 +0,0 @@ -id,files) - // - // Meaning: pk->primary key field of the table - // fk->foreign key to link with parent - // nt->nested field (recursive data) - // CL->course level info - // UL->user level info - // files->table may have files) - // - //----------------------------------------------------------- - - //This function executes all the restore procedure about this mod - function resource_restore_mods($mod,$restore) { - global $CFG, $DB; - - $status = true; - - //Get record from backup_ids - $data = backup_getid($restore->backup_unique_code,$mod->modtype,$mod->id); - - if ($data) { - //Now get completed xmlized object - $info = $data->info; - //traverse_xmlize($info); //Debug - //print_object ($GLOBALS['traverse_array']); //Debug - //$GLOBALS['traverse_array']=""; //Debug - - //Now, build the RESOURCE record structure - $resource->course = $restore->course_id; - $resource->name = backup_todb($info['MOD']['#']['NAME']['0']['#']); - $resource->type = $info['MOD']['#']['TYPE']['0']['#']; - $resource->reference = backup_todb($info['MOD']['#']['REFERENCE']['0']['#']); - $resource->intro = backup_todb($info['MOD']['#']['SUMMARY']['0']['#']); - $resource->alltext = backup_todb($info['MOD']['#']['ALLTEXT']['0']['#']); - $resource->popup = backup_todb($info['MOD']['#']['POPUP']['0']['#']); - $resource->options = backup_todb($info['MOD']['#']['OPTIONS']['0']['#']); - $resource->timemodified = $info['MOD']['#']['TIMEMODIFIED']['0']['#']; - - //To mantain compatibility, in 1.4 the type and alltext meaning has changed and - //two new fields have arrived (popup and options). We have to modify somethigs - //if the popup field isn't present in the backup file to be upwards compatible. - if (! isset($info['MOD']['#']['POPUP']['0']['#'])) { //It's a pre-14 backup file - //Move alltext to popup in 3 and 5 resource types - if ($resource->type == 3 || $resource->type == 5) { - $resource->popup = $resource->alltext; - $resource->alltext = ''; - } - //Move reference to alltext for references - if ($resource->type == 1) { - $resource->popup = ''; - $resource->alltext = $resource->reference; - $resource->reference = ''; - } - //Reencode the type field to its new values and fill the options field as needed - //Array 1-9 of new types - $types = array ('','html','file','file','text','file', - 'html','file','text','directory'); - //Array 1-9 of corresponding options - $options = array ('','','frame','','0','', - '','','3',''); - //Make the conversion - $oldtype = $resource->type; - $resource->type = $types[$oldtype]; - $resource->options = $options[$oldtype]; - } - - if ($resource->type == 'reference') { // Obsolete type of resource - $resource->type == 'html'; - $resource->alltext = $resource->reference; - $resource->reference = ''; - } - - //The structure is equal to the db, so insert the resource - $newid = $DB->insert_record ("resource",$resource); - - //Do some output - if (!defined('RESTORE_SILENTLY')) { - echo "
  • ".get_string("modulename","resource")." \"".format_string($resource->name,true)."\"
  • "; - } - backup_flush(300); - - if ($newid) { - //We have the newid, update backup_ids - backup_putid($restore->backup_unique_code,$mod->modtype, - $mod->id, $newid); - - // restore any associated files... - if ($resource->type == 'file' || $resource->type == 'directory' || $resource->type == 'ims') { - resource_restore_files($mod->id,$newid,$resource,$restore); - } - - } else { - $status = false; - } - } else { - $status = false; - } - - return $status; - } - - //Return a content decoded to support interactivities linking. Every module - //should have its own. They are called automatically from - //resource_decode_content_links_caller() function in each module - //in the restore process - function resource_decode_content_links ($content,$restore) { - - global $CFG; - - $result = $content; - - //Link to the list of resources - - $searchstring='/\$@(RESOURCEINDEX)\*([0-9]+)@\$/'; - //We look for it - preg_match_all($searchstring,$content,$foundset); - //If found, then we are going to look for its new id (in backup tables) - if ($foundset[0]) { - //print_object($foundset); //Debug - //Iterate over foundset[2]. They are the old_ids - foreach($foundset[2] as $old_id) { - //We get the needed variables here (course id) - $rec = backup_getid($restore->backup_unique_code,"course",$old_id); - //Personalize the searchstring - $searchstring='/\$@(RESOURCEINDEX)\*('.$old_id.')@\$/'; - //If it is a link to this course, update the link to its new location - if (!empty($rec->new_id)) { - //Now replace it - $result= preg_replace($searchstring,$CFG->wwwroot.'/mod/resource/index.php?id='.$rec->new_id,$result); - } else { - //It's a foreign link so leave it as original - $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/resource/index.php?id='.$old_id,$result); - } - } - } - - //Link to resource view by moduleid - - $searchstring='/\$@(RESOURCEVIEWBYID)\*([0-9]+)@\$/'; - //We look for it - preg_match_all($searchstring,$result,$foundset); - //If found, then we are going to look for its new id (in backup tables) - if ($foundset[0]) { - //print_object($foundset); //Debug - //Iterate over foundset[2]. They are the old_ids - foreach($foundset[2] as $old_id) { - //We get the needed variables here (course_modules id) - $rec = backup_getid($restore->backup_unique_code,"course_modules",$old_id); - //Personalize the searchstring - $searchstring='/\$@(RESOURCEVIEWBYID)\*('.$old_id.')@\$/'; - //If it is a link to this course, update the link to its new location - if (!empty($rec->new_id)) { - //Now replace it - $result= preg_replace($searchstring,$CFG->wwwroot.'/mod/resource/view.php?id='.$rec->new_id,$result); - } else { - //It's a foreign link so leave it as original - $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/resource/view.php?id='.$old_id,$result); - } - } - } - - //Link to resource view by resourceid - - $searchstring='/\$@(RESOURCEVIEWBYR)\*([0-9]+)@\$/'; - //We look for it - preg_match_all($searchstring,$result,$foundset); - //If found, then we are going to look for its new id (in backup tables) - if ($foundset[0]) { - //print_object($foundset); //Debug - //Iterate over foundset[2]. They are the old_ids - foreach($foundset[2] as $old_id) { - //We get the needed variables here (forum id) - $rec = backup_getid($restore->backup_unique_code,"resource",$old_id); - //Personalize the searchstring - $searchstring='/\$@(RESOURCEVIEWBYR)\*('.$old_id.')@\$/'; - //If it is a link to this course, update the link to its new location - if($rec->new_id) { - //Now replace it - $result= preg_replace($searchstring,$CFG->wwwroot.'/mod/resource/view.php?r='.$rec->new_id,$result); - } else { - //It's a foreign link so leave it as original - $result= preg_replace($searchstring,$restore->original_wwwroot.'/mod/resource/view.php?r='.$old_id,$result); - } - } - } - - return $result; - } - - //This function makes all the necessary calls to xxxx_decode_content_links() - //function in each module, passing them the desired contents to be decoded - //from backup format to destination site/course in order to mantain inter-activities - //working in the backup/restore process. It's called from restore_decode_content_links() - //function in restore process - function resource_decode_content_links_caller($restore) { - global $CFG, $DB; - $status = true; - - if ($resources = $DB->get_records('resource', array('course'=>$restore->course_id), '', "id, alltext, intro, reference")) { - - $i = 0; //Counter to send some output to the browser to avoid timeouts - foreach ($resources as $resource) { - //Increment counter - $i++; - $content1 = $resource->alltext; - $content2 = $resource->intro; - $content3 = $resource->reference; - $result1 = restore_decode_content_links_worker($content1,$restore); - $result2 = restore_decode_content_links_worker($content2,$restore); - $result3 = restore_decode_content_links_worker($content3,$restore); - - if ($result1 != $content1 || $result2 != $content2 || $result3 != $content3) { - //Update record - $resource->alltext = $result1; - $resource->intro = $result2; - $resource->reference = $result3; - $status = $DB->update_record("resource",$resource); - if (debugging()) { - if (!defined('RESTORE_SILENTLY')) { - echo '

    '.s($content1).'
    changed to
    '.s($result1).'

    '; - echo '

    '.s($content2).'
    changed to
    '.s($result2).'

    '; - echo '

    '.s($content3).'
    changed to
    '.s($result3).'

    '; - } - } - } - //Do some output - if (($i+1) % 5 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if (($i+1) % 100 == 0) { - echo "
    "; - } - } - backup_flush(300); - } - } - } - return $status; - } - - //This function converts texts in FORMAT_WIKI to FORMAT_MARKDOWN for - //some texts in the module - function resource_restore_wiki2markdown ($restore) { - global $CFG, $DB; - - $status = true; - - //Convert resource->alltext - if ($records = $DB->get_records_sql("SELECT r.id, r.alltext, r.options - FROM {resource} r, - {backup_ids} b - WHERE r.course = ? AND - options = ".FORMAT_WIKI. " AND - b.backup_code = ? AND - b.table_name = 'resource' AND - b.new_id = r.id", array($restore->course_id, $restore->backup_unique_code))) { - foreach ($records as $record) { - //Rebuild wiki links - $record->alltext = restore_decode_wiki_content($record->alltext, $restore); - //Convert to Markdown - $wtm = new WikiToMarkdown(); - $record->alltext = $wtm->convert($record->alltext, $restore->course_id); - $record->options = FORMAT_MARKDOWN; - $status = $DB->update_record('resource', $record); - //Do some output - $i++; - if (($i+1) % 1 == 0) { - if (!defined('RESTORE_SILENTLY')) { - echo "."; - if (($i+1) % 20 == 0) { - echo "
    "; - } - } - backup_flush(300); - } - } - - } - return $status; - } - - - //This function returns a log record with all the necessay transformations - //done. It's used by restore_log_module() to restore modules log. - function resource_restore_logs($restore,$log) { - - $status = false; - - //Depending of the action, we recode different things - switch ($log->action) { - case "add": - if ($log->cmid) { - //Get the new_id of the module (to recode the info field) - $mod = backup_getid($restore->backup_unique_code,$log->module,$log->info); - if ($mod) { - $log->url = "view.php?id=".$log->cmid; - $log->info = $mod->new_id; - $status = true; - } - } - break; - case "update": - if ($log->cmid) { - //Get the new_id of the module (to recode the info field) - $mod = backup_getid($restore->backup_unique_code,$log->module,$log->info); - if ($mod) { - $log->url = "view.php?id=".$log->cmid; - $log->info = $mod->new_id; - $status = true; - } - } - break; - case "view": - if ($log->cmid) { - //Get the new_id of the module (to recode the info field) - $mod = backup_getid($restore->backup_unique_code,$log->module,$log->info); - if ($mod) { - $log->url = "view.php?id=".$log->cmid; - $log->info = $mod->new_id; - $status = true; - } - } - break; - case "view all": - $log->url = "index.php?id=".$log->course; - $status = true; - break; - default: - if (!defined('RESTORE_SILENTLY')) { - echo "action (".$log->module."-".$log->action.") unknown. Not restored
    "; //Debug - } - break; - } - - if ($status) { - $status = $log; - } - return $status; - } - - function resource_restore_files($oldid,$newid,$resource,$restore) { - global $CFG; - - $status = true; - $status = check_dir_exists($CFG->dataroot."/".$restore->course_id,true); - - // we need to do anything referenced by $resource->reference and anything in moddata/resource/instance - - // do referenced files/dirs first. - $temp_path = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code.'/course_files/'.$resource->reference; - if (file_exists($temp_path)) { // ok, it was backed up, restore it. - $new_path = $CFG->dataroot.'/'.$restore->course_id.'/'.$resource->reference; - - // if this is somewhere deeply nested we need to do all the structure stuff first..... - $bits = explode('/',$resource->reference); - $newbit = ''; - for ($i = 0; $i< count($bits)-1; $i++) { - $newbit .= $bits[$i].'/'; - $status = $status && check_dir_exists($CFG->dataroot.'/'.$restore->course_id.'/'.$newbit,true); - } - $status = $status && backup_copy_file($temp_path,$new_path); - } - - // and now for moddata. - $temp_path = $CFG->dataroot."/temp/backup/".$restore->backup_unique_code. - "/moddata/resource/".$oldid; - if (file_exists($temp_path)) { // there's something to back up, restore it. - $new_path = $CFG->dataroot."/".$restore->course_id."/".$CFG->moddata; - $status = $status && check_dir_exists($new_path,true); - $new_path .= '/resource'; - $status = $status && check_dir_exists($new_path,true); - $new_path .= '/'.$newid; - $status = $status && backup_copy_file($temp_path,$new_path); - } - return $status; - } - -?> diff --git a/mod/resource/settings.php b/mod/resource/settings.php index 242f49389f777..7f3189404f738 100644 --- a/mod/resource/settings.php +++ b/mod/resource/settings.php @@ -1,48 +1,75 @@ -dirroot.'/mod/resource/lib.php'); +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see . -global $RESOURCE_WINDOW_OPTIONS; // make sure we have the pesky global +/** + * Resource module admin settings and defaults + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ -$checkedyesno = array(''=>get_string('no'), 'checked'=>get_string('yes')); // not nice at all +if ($ADMIN->fulltree) { + require_once("$CFG->libdir/resourcelib.php"); -$settings->add(new admin_setting_configtext('resource_framesize', get_string('framesize', 'resource'), - get_string('configframesize', 'resource'), 130, PARAM_INT)); + $displayoptions = resourcelib_get_displayoptions(array(RESOURCELIB_DISPLAY_AUTO, + RESOURCELIB_DISPLAY_EMBED, + RESOURCELIB_DISPLAY_FRAME, + RESOURCELIB_DISPLAY_DOWNLOAD, + RESOURCELIB_DISPLAY_OPEN, + RESOURCELIB_DISPLAY_NEW, + RESOURCELIB_DISPLAY_POPUP, + )); + $defaultdisplayoptions = array(RESOURCELIB_DISPLAY_AUTO, + RESOURCELIB_DISPLAY_EMBED, + RESOURCELIB_DISPLAY_DOWNLOAD, + RESOURCELIB_DISPLAY_OPEN, + RESOURCELIB_DISPLAY_POPUP, + ); -$settings->add(new admin_setting_configtext('resource_websearch', get_string('websearchdefault', 'resource'), - get_string('configwebsearch', 'resource'), 'http://google.com/')); + //--- general settings ----------------------------------------------------------------------------------- + $settings->add(new admin_setting_configtext('resource/framesize', + get_string('framesize', 'resource'), get_string('configframesize', 'resource'), 130, PARAM_INT)); + $settings->add(new admin_setting_configcheckbox('resource/requiremodintro', + get_string('requiremodintro', 'admin'), get_string('configrequiremodintro', 'admin'), 1)); + $settings->add(new admin_setting_configmultiselect('resource/displayoptions', + get_string('displayoptions', 'resource'), get_string('configdisplayoptions', 'resource'), + $defaultdisplayoptions, $displayoptions)); -$settings->add(new admin_setting_configtext('resource_defaulturl', get_string('resourcedefaulturl', 'resource'), - get_string('configdefaulturl', 'resource'), 'http://')); + //--- modedit defaults ----------------------------------------------------------------------------------- + $settings->add(new admin_setting_heading('resourcemodeditdefaults', get_string('modeditdefaults', 'admin'), get_string('condifmodeditdefaults', 'admin'))); -$settings->add(new admin_setting_configpasswordunmask('resource_secretphrase', get_string('password'), - get_string('configsecretphrase', 'resource'), random_string(20))); - -$settings->add(new admin_setting_configcheckbox('resource_allowlocalfiles', get_string('allowlocalfiles', 'resource'), - get_string('configallowlocalfiles', 'resource'), 0)); - -$woptions = array('' => get_string('pagewindow', 'resource'), 'checked' => get_string('newwindow', 'resource')); -$settings->add(new admin_setting_configselect('resource_popup', get_string('display', 'resource'), - get_string('configpopup', 'resource'), '', $woptions)); - -foreach ($RESOURCE_WINDOW_OPTIONS as $optionname) { - $popupoption = "resource_popup$optionname"; - if ($popupoption == 'resource_popupheight') { - $settings->add(new admin_setting_configtext('resource_popupheight', get_string('newheight', 'resource'), - get_string('configpopupheight', 'resource'), 450, PARAM_INT)); - } else if ($popupoption == 'resource_popupwidth') { - $settings->add(new admin_setting_configtext('resource_popupwidth', get_string('newwidth', 'resource'), - get_string('configpopupwidth', 'resource'), 620, PARAM_INT)); - } else { - $settings->add(new admin_setting_configselect($popupoption, get_string('new'.$optionname, 'resource'), - get_string('configpopup'.$optionname, 'resource'), 'checked', $checkedyesno)); - } + $settings->add(new admin_setting_configcheckbox_with_advanced('resource/printheading', + get_string('printheading', 'resource'), get_string('printheadingexplain', 'resource'), + array('value'=>0, 'adv'=>false))); + $settings->add(new admin_setting_configcheckbox_with_advanced('resource/printintro', + get_string('printintro', 'resource'), get_string('printintroexplain', 'resource'), + array('value'=>1, 'adv'=>false))); + $settings->add(new admin_setting_configselect_with_advanced('resource/display', + get_string('displayselect', 'resource'), get_string('displayselectexplain', 'resource'), + array('value'=>RESOURCELIB_DISPLAY_AUTO, 'adv'=>false), $displayoptions)); + $settings->add(new admin_setting_configtext_with_advanced('resource/popupwidth', + get_string('popupwidth', 'resource'), get_string('popupwidthexplain', 'resource'), + array('value'=>620, 'adv'=>true), PARAM_INT, 7)); + $settings->add(new admin_setting_configtext_with_advanced('resource/popupheight', + get_string('popupheight', 'resource'), get_string('popupheightexplain', 'resource'), + array('value'=>450, 'adv'=>true), PARAM_INT, 7)); + $options = array('0' => get_string('none'), '1' => get_string('allfiles'), '2' => get_string('htmlfilesonly')); + $settings->add(new admin_setting_configselect_with_advanced('resource/filterfiles', + get_string('filterfiles', 'resource'), get_string('filterfilesexplain', 'resource'), + array('value'=>0, 'adv'=>true), $options)); } - -$settings->add(new admin_setting_configcheckbox('resource_autofilerename', get_string('autofilerename', 'resource'), - get_string('configautofilerenamesettings', 'resource'), 1)); - -$settings->add(new admin_setting_configcheckbox('resource_blockdeletingfile', get_string('blockdeletingfile', 'resource'), - get_string('configblockdeletingfilesettings', 'resource'), 1)); - -?> diff --git a/mod/resource/simpletest/test_resource_portfolio_callers.php b/mod/resource/simpletest/test_resource_portfolio_callers.php deleted file mode 100644 index 506e1ca003124..0000000000000 --- a/mod/resource/simpletest/test_resource_portfolio_callers.php +++ /dev/null @@ -1,51 +0,0 @@ -libdir/simpletest/portfolio_testclass.php"); -require_once("$CFG->dirroot/mod/resource/lib.php"); -require_once("$CFG->dirroot/$CFG->admin/generator.php"); - -Mock::generate('resource_portfolio_caller', 'mock_caller'); -Mock::generate('portfolio_exporter', 'mock_exporter'); - -class testResourcePortfolioCallers extends portfoliolib_test { - public static $includecoverage = array('lib/portfoliolib.php', 'mod/resource/lib.php'); - public $module_type = 'resource'; - public $modules = array(); - public $entries = array(); - public $caller; - - public function setUp() { - global $DB, $USER; - - parent::setUp(); - - $resource_type = new stdClass(); - $resource_type->type = GENERATOR_SEQUENCE; - $resource_type->options = array('text', 'html'); - - $settings = array('quiet' => 1, 'pre_cleanup' => 1, - 'modules_list' => array($this->module_type), - 'resource_type' => $resource_type, - 'number_of_students' => 15, 'students_per_course' => 15, 'number_of_sections' => 1, - 'number_of_modules' => 3); - - generator_generate_data($settings); - - $this->modules = $DB->get_records($this->module_type); - $first_module = reset($this->modules); - $cm = get_coursemodule_from_instance($this->module_type, $first_module->id); - - $this->caller = parent::setup_caller('resource_portfolio_caller', array('id' => $cm->instance)); - } - - public function tearDown() { - parent::tearDown(); - } - - public function test_caller_sha1() { - $sha1 = $this->caller->get_sha1(); - $this->caller->prepare_package(); - $this->assertEqual($sha1, $this->caller->get_sha1()); - } - -} -?> diff --git a/mod/resource/type/directory/resource.class.php b/mod/resource/type/directory/resource.class.php deleted file mode 100644 index 9f15053cdddf9..0000000000000 --- a/mod/resource/type/directory/resource.class.php +++ /dev/null @@ -1,195 +0,0 @@ -_postprocess($resource); - return parent::add_instance($resource); -} - -function update_instance($resource) { - $this->_postprocess($resource); - return parent::update_instance($resource); -} - -function _postprocess(&$resource) { - if($resource->reference=='0') - $resource->reference = ''; - - $resource->popup = ''; - $resource->alltext = ''; -} - -function display() { - global $CFG, $OUTPUT; - -/// Set up generic stuff first, including checking for access - parent::display(); - -/// Set up some shorthand variables - $cm = $this->cm; - $course = $this->course; - $resource = $this->resource; - - require_once($CFG->libdir.'/filelib.php'); - - $subdir = optional_param('subdir','', PARAM_PATH); - $resource->reference = clean_param($resource->reference, PARAM_PATH); - - add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id); - - if ($resource->reference) { - $relativepath = "{$course->id}/{$resource->reference}"; - } else { - $relativepath = "{$course->id}"; - } - - if ($subdir) { - $relativepath = "$relativepath$subdir"; - if (stripos($relativepath, 'backupdata') !== FALSE or stripos($relativepath, $CFG->moddata) !== FALSE) { - print_error('invalidaccess'); - } - - $subs = explode('/', $subdir); - array_shift($subs); - $countsubs = count($subs); - $count = 0; - $backsub = ''; - - foreach ($subs as $sub) { - $count++; - if ($count < $countsubs) { - $backsub .= "/$sub"; - - $this->navlinks[] = array('name' => $sub, 'link' => "view.php?id={$cm->id}", 'type' => 'title'); - } else { - $this->navlinks[] = array('name' => $sub, 'link' => '', 'type' => 'title'); - } - } - } - - $pagetitle = strip_tags($course->shortname.': '.format_string($resource->name)); - - $update = update_module_button($cm->id, $course->id, $this->strresource); - if (has_capability('moodle/course:managefiles', get_context_instance(CONTEXT_COURSE, $course->id))) { - $options = array('id'=>$course->id, 'wdir'=>'/'.$resource->reference.$subdir); - $editfiles = print_single_button("$CFG->wwwroot/files/index.php", $options, get_string("editfiles"), 'get', '', true); - $update = $editfiles.$update; - } - $navigation = build_navigation($this->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, $update, - navmenu($course, $cm)); - - - if (trim(strip_tags($resource->intro))) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - $spacer = new html_image(); - $spacer->height = 10; - $spacer->width = 10; - echo $OUTPUT->spacer($spacer) . '
    '; - } - - $files = get_directory_list("$CFG->dataroot/$relativepath", array($CFG->moddata, 'backupdata'), false, true, true); - - - if (!$files) { - print_heading(get_string("nofilesyet")); - print_footer($course); - exit; - } - - print_simple_box_start("center", "", "", '0' ); - - $strftime = get_string('strftimedatetime'); - $strname = get_string("name"); - $strsize = get_string("size"); - $strmodified = get_string("modified"); - $strfolder = get_string("folder"); - $strfile = get_string("file"); - - echo ''; - echo "". - "". - "". - ""; - foreach ($files as $file) { - if (is_dir("$CFG->dataroot/$relativepath/$file")) { // Must be a directory - $icon = 'folder'; - $relativeurl = "/view.php?blah"; - $filesize = display_size(get_directory_size("$CFG->dataroot/$relativepath/$file")); - - } else { - $icon = file_extension_icon($file); - $relativeurl = get_file_url("$relativepath/$file"); - $filesize = display_size(filesize("$CFG->dataroot/$relativepath/$file")); - } - - if ($icon == 'folder') { - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - } - echo '
    $strname$strsize$strmodified
    '; - echo "id}&subdir=$subdir/$file\">"; - echo "old_icon_url('f/' . $icon) . "\" class=\"icon\" alt=\"$strfolder\" /> $file"; - } else { - echo '
    '; - link_to_popup_window($relativeurl, "resourcedirectory{$resource->id}", "old_icon_url($icon) . "\" class=\"icon\" alt=\"$strfile\" /> $file", 450, 600, ''); - } - echo ' '; - echo $filesize; - echo ''; - echo userdate(filemtime("$CFG->dataroot/$relativepath/$file"), $strftime); - echo '
    '; - - print_simple_box_end(); - - print_footer($course); - -} - - -function setup($form) { - global $CFG; - - parent::setup($form); - - $rawdirs = get_directory_list("$CFG->dataroot/{$this->course->id}", array($CFG->moddata, 'backupdata'), true, true, false); - $dirs = array(); - foreach ($rawdirs as $rawdir) { - $dirs[$rawdir] = $rawdir; - } - - include("$CFG->dirroot/mod/resource/type/directory/directory.html"); - - parent::setup_end(); -} - -function setup_elements(&$mform) { - global $CFG; - - $rawdirs = get_directory_list($CFG->dataroot.'/'.$this->course->id, array($CFG->moddata, 'backupdata'), true, true, false); - $dirs = array(); - $dirs[0]=get_string('maindirectory', 'resource'); - foreach ($rawdirs as $rawdir) { - $dirs[$rawdir] = $rawdir; - } - - $mform->addElement('select', 'reference', get_string('resourcetypedirectory', 'resource'), $dirs); - $mform->setDefault('windowpopup', 0); - -} - - -} - -?> diff --git a/mod/resource/type/file/file.js b/mod/resource/type/file/file.js deleted file mode 100644 index e0efccf168346..0000000000000 --- a/mod/resource/type/file/file.js +++ /dev/null @@ -1,40 +0,0 @@ -function local_file_set_value(choose, localpath) { - var txt = document.getElementById('myform').myfile.value; - if (txt.indexOf('/') > -1) { - var mpath = txt.substring(txt.indexOf('/'),txt.length); - } else if (txt.indexOf('\\') > -1) { - var mpath = txt.substring(txt.indexOf('\\'),txt.length); - } else { - window.close(); - return; - } - opener.document.getElementById('').value = localpath+mpath; - window.close(); -} - -function local_path_set_value(txt) { - if (txt.indexOf('/') > -1) { - txt = txt.substring(0,txt.lastIndexOf('/')); - } else if (txt.indexOf('\\') > -1) { - txt = txt.substring(0,txt.lastIndexOf('\\')); - } - document.getElementById('myform').pathname.value = txt; - document.getElementById('myform').submit(); -} - -function resizeEmbeddedHtml(viewportheight) { - //calculate new embedded html height size - objectheight = YAHOO.util.Dom.getViewportHeight() - viewportheight; - - if (objectheight < 200) { - objectheight = 200; - } - //resize the embedded html object - YAHOO.util.Dom.setStyle("embeddedhtml", "height", objectheight+"px"); - YAHOO.util.Dom.setStyle("embeddedhtml", "width", "100%"); -} - -function file_resource_init(viewportheight) { - resizeEmbeddedHtml(); - YAHOO.widget.Overlay.windowResizeEvent.subscribe(resizeEmbeddedHtml); -} \ No newline at end of file diff --git a/mod/resource/type/file/localfile.php b/mod/resource/type/file/localfile.php deleted file mode 100644 index 29741beb3a948..0000000000000 --- a/mod/resource/type/file/localfile.php +++ /dev/null @@ -1,35 +0,0 @@ -resource_allowlocalfiles) { - print_error('cannotcallscript'); - } - - print_header(get_string('localfilechoose', 'resource')); - - print_simple_box(get_string('localfileinfo', 'resource'), 'center'); - - $PAGE->requires->js('mod/resource/type/file/file.js'); - ?> -
    -
    -
    -
    -
    - - -
    -
    -
    - - diff --git a/mod/resource/type/file/localpath.php b/mod/resource/type/file/localpath.php deleted file mode 100644 index 37d3705b15f6a..0000000000000 --- a/mod/resource/type/file/localpath.php +++ /dev/null @@ -1,38 +0,0 @@ -requires->js_function_call('window.close')->asap(); - exit; - } - - print_header(get_string('localfilechoose', 'resource')); - - print_simple_box(get_string('localfilepath', 'resource', $CFG->wwwroot.'/user/edit.php?course='.SITEID), 'center'); - $PAGE->requires->js('mod/resource/type/file/file.js'); - - ?> -
    -
    -
    -
    - - -
    - - -
    -
    -
    - diff --git a/mod/resource/type/file/resource.class.php b/mod/resource/type/file/resource.class.php deleted file mode 100644 index 2dfc3523b6806..0000000000000 --- a/mod/resource/type/file/resource.class.php +++ /dev/null @@ -1,865 +0,0 @@ -wwwroot = $CFG->wwwroot; - - - $courseparameters = array( - 'label3' => array('langstr' => get_string('course'), - 'value' => 'optgroup'), - - 'courseid' => array('langstr' => 'id', - 'value' => $this->course->id), - 'coursefullname' => array('langstr' => get_string('fullnamecourse'), - 'value' => $this->course->fullname), - 'courseshortname' => array('langstr' => get_string('shortnamecourse'), - 'value' => $this->course->shortname), - 'courseidnumber' => array('langstr' => get_string('idnumbercourse'), - 'value' => $this->course->idnumber), - 'coursesummary' => array('langstr' => get_string('summary'), - 'value' => $this->course->summary), - 'courseformat' => array('langstr' => get_string('format'), - 'value' => $this->course->format), - ); - - $roles = get_all_roles(); - $coursecontext = get_context_instance(CONTEXT_COURSE, $this->course->id); - $roles = role_fix_names($roles, $coursecontext, ROLENAME_ALIAS); - foreach ($roles as $role) { - $courseparameters['course' . $role->shortname] = array( - 'langstr' => get_string('yourwordforx', '', $role->name), - 'value' => $role->localname); - } - $courseparameters['label4'] = array('langstr' => '', 'value' =>'/optgroup'); - - $miscparameters = array( - 'label5' => array('langstr' => get_string('miscellaneous'), - 'value' => 'optgroup'), - - 'lang' => array('langstr' => get_string('preferredlanguage'), - 'value' => current_language()), - 'sitename' => array('langstr' => get_string('fullsitename'), - 'value' => format_string($site->fullname)), - 'serverurl' => array('langstr' => get_string('serverurl', 'resource', $littlecfg), - 'value' => $littlecfg->wwwroot), - 'currenttime' => array('langstr' => get_string('time'), - 'value' => time()), - 'encryptedcode' => array('langstr' => get_string('encryptedcode'), - 'value' => $this->set_encrypted_parameter()), - - 'label6' => array('langstr' => "", - 'value' =>'/optgroup'), - ); - - $userparameters = array(); - if (!empty($USER->id)) { - $userparameters = array( - 'label1' => array('langstr' => get_string('user'), - 'value' => 'optgroup'), - - 'userid' => array('langstr' => 'id', - 'value' => $USER->id), - 'userusername' => array('langstr' => get_string('username'), - 'value' => $USER->username), - 'useridnumber' => array('langstr' => get_string('idnumber'), - 'value' => $USER->idnumber), - 'userfirstname' => array('langstr' => get_string('firstname'), - 'value' => $USER->firstname), - 'userlastname' => array('langstr' => get_string('lastname'), - 'value' => $USER->lastname), - 'userfullname' => array('langstr' => get_string('fullnameuser'), - 'value' => fullname($USER)), - 'useremail' => array('langstr' => get_string('email'), - 'value' => $USER->email), - 'usericq' => array('langstr' => get_string('icqnumber'), - 'value' => $USER->icq), - 'userphone1' => array('langstr' => get_string('phone').' 1', - 'value' => $USER->phone1), - 'userphone2' => array('langstr' => get_string('phone2').' 2', - 'value' => $USER->phone2), - 'userinstitution' => array('langstr' => get_string('institution'), - 'value' => $USER->institution), - 'userdepartment' => array('langstr' => get_string('department'), - 'value' => $USER->department), - 'useraddress' => array('langstr' => get_string('address'), - 'value' => $USER->address), - 'usercity' => array('langstr' => get_string('city'), - 'value' => $USER->city), - 'usertimezone' => array('langstr' => get_string('timezone'), - 'value' => get_user_timezone_offset()), - 'userurl' => array('langstr' => get_string('webpage'), - 'value' => $USER->url), - - 'label2' => array('langstr' => "", - 'value' =>'/optgroup'), - ); - } - $this->parameters = array_merge($userparameters, $courseparameters, $miscparameters); - } - - function add_instance($resource) { - $this->_postprocess($resource); - return parent::add_instance($resource); - } - - function update_instance($resource) { - $this->_postprocess($resource); - return parent::update_instance($resource); - } - - function _postprocess(&$resource) { - global $RESOURCE_WINDOW_OPTIONS; - $alloptions = $RESOURCE_WINDOW_OPTIONS; - - if (!empty($resource->forcedownload)) { - $resource->popup = ''; - $resource->options = 'forcedownload'; - - } else if ($resource->windowpopup) { - $optionlist = array(); - foreach ($alloptions as $option) { - $optionlist[] = $option."=".$resource->$option; - unset($resource->$option); - } - $resource->popup = implode(',', $optionlist); - unset($resource->windowpopup); - $resource->options = ''; - - } else { - if (empty($resource->framepage)) { - $resource->options = ''; - } else { - switch ($resource->framepage) { - case 1: - $resource->options = 'frame'; - break; - case 2: - $resource->options = 'objectframe'; - break; - default: - $resource->options = ''; - break; - } - } - unset($resource->framepage); - $resource->popup = ''; - } - - $optionlist = array(); - for ($i = 0; $i < $this->maxparameters; $i++) { - $parametername = "parameter$i"; - $parsename = "parse$i"; - if (!empty($resource->$parsename) and $resource->$parametername != "-") { - $optionlist[] = $resource->$parametername."=".$resource->$parsename; - } - unset($resource->$parsename); - unset($resource->$parametername); - } - - $resource->alltext = implode(',', $optionlist); - } - - /** - * Display the file resource - * - * Displays a file resource embedded, in a frame, or in a popup. - * Output depends on type of file resource. - * - * @param CFG global object - */ - function display() { - global $CFG, $THEME, $USER, $PAGE, $OUTPUT; - ///Yahoo javascript libaries for updating embedded object size - $PAGE->requires->yui_lib('container'); - - /// Set up generic stuff first, including checking for access - parent::display(); - - /// Set up some shorthand variables - $cm = $this->cm; - $course = $this->course; - $resource = $this->resource; - - - $this->set_parameters(); // set the parameters array - - /////////////////////////////////////////////// - - /// Possible display modes are: - /// File displayed embedded in a normal page - /// File displayed in a popup window - /// File displayed embedded in a popup window - /// File not displayed at all, but downloaded - - - /// First, find out what sort of file we are dealing with. - require_once($CFG->libdir.'/filelib.php'); - - $querystring = ''; - $resourcetype = ''; - $embedded = false; - $mimetype = mimeinfo("type", $resource->reference); - $pagetitle = strip_tags($course->shortname.': '.format_string($resource->name)); - - if ($resource->options != "forcedownload") { // TODO nicolasconnault 14-03-07: This option should be renamed "embed" - if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image - $resourcetype = "image"; - $embedded = true; - - } else if ($mimetype == "audio/mp3") { // It's an MP3 audio file - $resourcetype = "mp3"; - $embedded = true; - - } else if ($mimetype == "video/x-flv") { // It's a Flash video file - $resourcetype = "flv"; - $embedded = true; - - } else if (substr($mimetype, 0, 10) == "video/x-ms") { // It's a Media Player file - $resourcetype = "mediaplayer"; - $embedded = true; - - } else if ($mimetype == "video/quicktime") { // It's a Quicktime file - $resourcetype = "quicktime"; - $embedded = true; - - } else if ($mimetype == "application/x-shockwave-flash") { // It's a Flash file - $resourcetype = "flash"; - $embedded = true; - - } else if ($mimetype == "video/mpeg") { // It's a Mpeg file - $resourcetype = "mpeg"; - $embedded = true; - - } else if ($mimetype == "text/html") { // It's a web page - $resourcetype = "html"; - - } else if ($mimetype == "application/zip") { // It's a zip archive - $resourcetype = "zip"; - $embedded = true; - - } else if ($mimetype == 'application/pdf' || $mimetype == 'application/x-pdf') { - $resourcetype = "pdf"; - $embedded = true; - } else if ($mimetype == "audio/x-pn-realaudio") { // It's a realmedia file - $resourcetype = "rm"; - $embedded = true; - } - } - - $isteamspeak = (stripos($resource->reference, 'teamspeak://') === 0); - - /// Form the parse string - $querys = array(); - if (!empty($resource->alltext)) { - $parray = explode(',', $resource->alltext); - foreach ($parray as $fieldstring) { - $field = explode('=', $fieldstring); - // Backwards compatibility. This is not ideal, but we no longer - // store plural role names, so the best we can do is send the - // singular instead. - if ($field[0] == 'courseteachers') { - $field[0] = 'courseeditingteacher'; - } else if ($field[0] == 'coursestudents') { - $field[0] = 'coursestudent'; - } - $querys[] = urlencode($field[1]).'='.urlencode($this->parameters[$field[0]]['value']); - } - if ($isteamspeak) { - $querystring = implode('?', $querys); - } else { - $querystring = implode('&', $querys); - } - } - - - /// Set up some variables - - $inpopup = optional_param('inpopup', 0, PARAM_BOOL); - - if (resource_is_url($resource->reference)) { - $fullurl = $resource->reference; - if (!empty($querystring)) { - $urlpieces = parse_url($resource->reference); - if (empty($urlpieces['query']) or $isteamspeak) { - $fullurl .= '?'.$querystring; - } else { - $fullurl .= '&'.$querystring; - } - } - - } else if ($CFG->resource_allowlocalfiles and (strpos($resource->reference, RESOURCE_LOCALPATH) === 0)) { // Localpath - $localpath = get_user_preferences('resource_localpath', 'D:'); - $relativeurl = str_replace(RESOURCE_LOCALPATH, $localpath, $resource->reference); - - if ($querystring) { - $relativeurl .= '?'.$querystring; - } - - $relativeurl = str_replace('\\', '/', $relativeurl); - $relativeurl = str_replace(' ', '%20', $relativeurl); - $fullurl = 'file:///'.htmlentities($relativeurl); - $localpath = true; - - } else { // Normal uploaded file - $forcedownloadsep = '?'; - if ($resource->options == 'forcedownload') { - $querys[] = 'forcedownload=1'; - } - $fullurl = get_file_url($course->id.'/'.$resource->reference, $querys); - } - - /// Print a notice and redirect if we are trying to access a file on a local file system - /// and the config setting has been disabled - if (!$CFG->resource_allowlocalfiles and (strpos($resource->reference, RESOURCE_LOCALPATH) === 0)) { - if ($inpopup) { - print_header($pagetitle, $course->fullname); - } else { - $navigation = build_navigation($this->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm)); - } - notify(get_string('notallowedlocalfileaccess', 'resource', '')); - if ($inpopup) { - echo $OUTPUT->close_window_button(); - } - print_footer('none'); - die; - } - - - /// Check whether this is supposed to be a popup, but was called directly - if ($resource->popup and !$inpopup) { /// Make a page and a pop-up window - $navigation = build_navigation($this->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm)); - - $PAGE->requires->js_function_call('openpopup', Array("/mod/resource/view.php?inpopup=true&id={$cm->id}","resource{$resource->id}",$resource->popup)); - - if (trim(strip_tags($resource->intro))) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - - $link = "wwwroot/mod/resource/view.php?inpopup=true&id={$cm->id}\" " - . "onclick=\"this.target='resource{$resource->id}'; return openpopup('/mod/resource/view.php?inpopup=true&id={$cm->id}', " - . "'resource{$resource->id}','{$resource->popup}');\">".format_string($resource->name,true).""; - - echo '
    '; - print_string('popupresource', 'resource'); - echo '
    '; - print_string('popupresourcelink', 'resource', $link); - echo '
    '; - - print_footer($course); - exit; - } - - - /// Now check whether we need to display a frameset - - $frameset = optional_param('frameset', '', PARAM_ALPHA); - if (empty($frameset) and !$embedded and !$inpopup and ($resource->options == "frame" || $resource->options == "objectframe") and empty($USER->screenreader)) { - /// display the resource into a object tag - if ($resource->options == "objectframe") { - - ///Moodle Header and navigation bar - $navigation = build_navigation($this->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "parent")); - $options = new object(); - $options->para = false; - if (!empty($localpath)) { // Show some help - echo ''; - } - echo ''; - - /// embedded file into iframe if the resource is on another domain - /// - /// This case is not XHTML strict but there is no alternative - /// The object tag alternative is XHTML strict, however IE6-7 displays a blank object on accross domain by default, - /// so we decided to use iframe for accross domain MDL-10021 - if (!stristr($fullurl,$CFG->wwwroot)) { - echo '

    '; - } - else { - ///embedded HTML file into an object tag - echo '

    - alt : ' . $fullurl . ' -

    '; - } - - if (!empty($resource->intro)) { - $viewportheight = 230; - } else { - $viewportheight = 120; - } - ///add some javascript in order to fit this object tag into the browser window - $PAGE->requires->js('mod/resource/type/file/file.js'); - $PAGE->requires->js_function_call('file_resource_init', Array($viewportheight)); - - ///print the intro - if (!empty($resource->intro)) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - print_footer(); - exit; - } else { - /// display the resource into a frame tag - @header('Content-Type: text/html; charset=utf-8'); - echo "\n"; - echo "\n"; - echo ''; - echo ''; - echo "" . format_string($course->shortname) . ": ".strip_tags(format_string($resource->name,true))."\n"; - echo "resource_framesize,*\">"; - echo "id}&type={$resource->type}&frameset=top\" title=\"".get_string('modulename','resource')."\"/>"; - if (!empty($localpath)) { // Show it like this so we interpose some HTML - echo "id}&type={$resource->type}&inpopup=true\" title=\"".get_string('modulename','resource')."\"/>"; - } else { - echo ""; - } - echo ""; - echo ""; - exit; - } - } - - - /// We can only get here once per resource, so add an entry to the log - - add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id); - - - /// If we are in a frameset, just print the top of it - - if (!empty( $frameset ) and ($frameset == "top") ) { - $navigation = build_navigation($this->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "parent")); - - echo '
    '.format_module_intro('resource', $resource, $cm->id).'
    '; - if (!empty($localpath)) { // Show some help - echo ''; - } - print_footer('empty'); - exit; - } - - - /// Display the actual resource - if ($embedded) { // Display resource embedded in page - $strdirectlink = get_string("directlink", "resource"); - - if ($inpopup) { - print_header($pagetitle); - } else { - $navigation = build_navigation($this->navlinks, $cm); - print_header_simple($pagetitle, '', $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "self")); - - } - - if ($resourcetype == "image") { - echo '
    '; - echo "name,true))."\" class=\"resourceimage\" src=\"$fullurl\" alt=\"\" />"; - echo '
    '; - - } else if ($resourcetype == "mp3") { - if (!empty($THEME->resource_mp3player_colors)) { - $c = $THEME->resource_mp3player_colors; // You can set this up in your theme/xxx/config.php - } else { - $c = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&'. - 'iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&'. - 'font=Arial&fontColour=FF33FF&buffer=10&waitForPlay=no&autoPlay=yes'; - } - $c .= '&volText='.get_string('vol', 'resource').'&panText='.get_string('pan','resource'); - $id = 'filter_mp3_'.time(); //we need something unique because it might be stored in text cache - $cleanurl = addslashes_js($fullurl); - - - // If we have Javascript, use UFO to embed the MP3 player, otherwise depend on plugins - - echo '
    '; - - echo ''; - $args = Array(); - $args['movie'] = $CFG->wwwroot.'/lib/mp3player/mp3player.swf?src='.$cleanurl; - $args['width'] = 600; - $args['height'] = 70; - $args['majorversion'] = 6; - $args['build'] = 40; - $args['flashvars'] = $c; - $args['quality'] = 'high'; - echo $PAGE->requires->js('lib/ufo.js')->asap(); - echo $PAGE->requires->data_for_js('FO', $args)->asap(); - echo $PAGE->requires->js_function_call('create_UFO_object', Array($id))->asap(); - - echo ''; - echo '
    '; - - } else if ($resourcetype == "flv") { - $id = 'filter_flv_'.time(); //we need something unique because it might be stored in text cache - $cleanurl = addslashes_js($fullurl); - - - // If we have Javascript, use UFO to embed the FLV player, otherwise depend on plugins - - echo '
    '; - - echo ''; - $args = Array(); - $args['movie'] = $CFG->wwwroot.'/filter/mediaplugin/flvplayer.swf?file='.$cleanurl; - $args['width'] = 600; - $args['height'] = 400; - $args['majorversion'] = 6; - $args['build'] = 40; - $args['allowscriptaccess'] = 'never'; - $args['allowfullscreen'] = 'true'; - $args['quality'] = 'high'; - echo $PAGE->requires->js('lib/ufo.js')->asap(); - echo $PAGE->requires->data_for_js('FO', $args)->asap(); - echo $PAGE->requires->js_function_call('create_UFO_object', Array($id))->asap(); - - echo ''; - echo '
    '; - - } else if ($resourcetype == "mediaplayer") { - echo '
    '; - echo ''; - echo ''; - echo ''; - echo ""; - echo ''; - echo "$fullurl"; - echo ''; - echo '
    '; - - } else if ($resourcetype == "mpeg") { - echo '
    '; - echo ''; - echo ""; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ""; - echo "$fullurl"; - echo ''; - echo '' . $fullurl . ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '
    '; - } else if ($resourcetype == "rm") { - - echo '
    '; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '' . $fullurl .''; - echo ''; - echo ''; - echo ''; - echo '
    '; - - } else if ($resourcetype == "quicktime") { - echo '
    '; - - echo ''; - echo ""; - echo ''; - echo ''; - echo ''; - echo ''; - - echo ''; - echo ""; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '' . $fullurl . ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '
    '; - } else if ($resourcetype == "flash") { - echo '
    '; - echo ''; - echo ""; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ""; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '' . $fullurl . ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '
    '; - - } elseif ($resourcetype == 'zip') { - echo '
    '; - echo get_string('clicktoopen', 'resource') . '' . format_string($resource->name) . ''; - echo '
    '; - - } elseif ($resourcetype == 'pdf') { - echo '
    '; - echo ''; - echo ''; - echo get_string('clicktoopen', 'resource') . '' . format_string($resource->name) . ''; - echo ''; - echo '
    '; - } - - if (trim($resource->intro)) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - - if ($inpopup) { - echo ""; - print_footer($course); // MDL-12098 - } else { - $spacer = new html_image(); - $spacer->height = 20; - $spacer->width = 20; - echo $OUTPUT->spacer($spacer) . '
    '; - print_footer($course); - } - - } else { // Display the resource on it's own - if (!empty($localpath)) { // Show a link to help work around browser security - echo ''; - echo ""; - } - redirect($fullurl); - } - - } - - - //backwards compatible with existing resources - function set_encrypted_parameter() { - global $CFG; - - if (!empty($this->resource->reference) && file_exists($CFG->dirroot ."/mod/resource/type/file/externserverfile.php")) { - include $CFG->dirroot ."/mod/resource/type/file/externserverfile.php"; - if (function_exists('extern_server_file')) { - return extern_server_file($this->resource->reference); - } - } - return md5(getremoteaddr().$CFG->resource_secretphrase); - } - - function setup_preprocessing(&$defaults){ - - if (isset($defaults['options']) and $defaults['options'] === 'forcedownload') { - $defaults['forcedownload'] = 1; - - } else if (!isset($defaults['popup'])) { - // use form defaults - - } else if (!empty($defaults['popup'])) { - $defaults['windowpopup'] = 1; - if (array_key_exists('popup', $defaults)) { - $rawoptions = explode(',', $defaults['popup']); - foreach ($rawoptions as $rawoption) { - $option = explode('=', trim($rawoption)); - $defaults[$option[0]] = $option[1]; - } - } - } else { - $defaults['windowpopup'] = 0; - /// set default value of 'keep navigation visible' - if (array_key_exists('options', $defaults)) { - if ($defaults['options']=='frame') { - $defaults['framepage'] = 1; - } else if ($defaults['options']=='objectframe') { - $defaults['framepage'] = 2; - } else { - $defaults['framepage'] = 0; - } - } - } - /// load up any stored parameters - if (!empty($defaults['alltext'])) { - $parray = explode(',', $defaults['alltext']); - $i=0; - foreach ($parray as $rawpar) { - list($param, $varname) = explode('=', $rawpar); - $defaults["parse$i"] = $varname; - $defaults["parameter$i"] = $param; - $i++; - } - } - } - - /** - * TODO document - */ - function setup_elements(&$mform) { - global $CFG, $RESOURCE_WINDOW_OPTIONS; - - $this->set_parameters(); // set the parameter array for the form - - $mform->addElement('choosecoursefile', 'reference', get_string('location'), null, array('maxlength' => 255, 'size' => 48)); - $mform->setDefault('reference', $CFG->resource_defaulturl); - $mform->addGroupRule('reference', array('value' => array(array(get_string('maximumchars', '', 255), 'maxlength', 255, 'client')))); - $mform->addRule('name', null, 'required', null, 'client'); - - if (!empty($CFG->resource_websearch)) { - $searchbutton = $mform->addElement('button', 'searchbutton', get_string('searchweb', 'resource').'...'); - $buttonattributes = array('title'=>get_string('searchweb', 'resource'), 'onclick'=>"return window.open('" - . "$CFG->resource_websearch', 'websearch', 'menubar=1,location=1,directories=1,toolbar=1," - . "scrollbars,resizable,width=800,height=600');"); - $searchbutton->updateAttributes($buttonattributes); - } - - if (!empty($CFG->resource_allowlocalfiles)) { - $lfbutton = $mform->addElement('button', 'localfilesbutton', get_string('localfilechoose', 'resource').'...'); - $options = 'menubar=0,location=0,scrollbars,resizable,width=600,height=400'; - $url = '/mod/resource/type/file/localfile.php?choose=id_reference_value'; - $buttonattributes = array('title'=>get_string('localfilechoose', 'resource'), 'onclick'=>"return openpopup('$url', '" - . $lfbutton->getName()."', '$options', 0);"); - $lfbutton->updateAttributes($buttonattributes); - } - - $mform->addElement('header', 'displaysettings', get_string('display', 'resource')); - - $mform->addElement('checkbox', 'forcedownload', get_string('forcedownload', 'resource')); - $mform->setHelpButton('forcedownload', array('forcedownload', get_string('forcedownload', 'resource'), 'resource')); - $mform->disabledIf('forcedownload', 'windowpopup', 'eq', 1); - - $woptions = array(0 => get_string('pagewindow', 'resource'), 1 => get_string('newwindow', 'resource')); - $mform->addElement('select', 'windowpopup', get_string('display', 'resource'), $woptions); - $mform->setDefault('windowpopup', !empty($CFG->resource_popup)); - $mform->disabledIf('windowpopup', 'forcedownload', 'checked'); - - $navoptions = array(0 => get_string('keepnavigationvisibleno','resource'), 1 => get_string('keepnavigationvisibleyesframe','resource'), 2 => get_string('keepnavigationvisibleyesobject','resource')); - $mform->addElement('select', 'framepage', get_string('keepnavigationvisible', 'resource'), $navoptions); - - $mform->setHelpButton('framepage', array('frameifpossible', get_string('keepnavigationvisible', 'resource'), 'resource')); - $mform->setDefault('framepage', 0); - $mform->disabledIf('framepage', 'windowpopup', 'eq', 1); - $mform->disabledIf('framepage', 'forcedownload', 'checked'); - $mform->setAdvanced('framepage'); - - foreach ($RESOURCE_WINDOW_OPTIONS as $option) { - if ($option == 'height' or $option == 'width') { - $mform->addElement('text', $option, get_string('new'.$option, 'resource'), array('size'=>'4')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } else { - $mform->addElement('checkbox', $option, get_string('new'.$option, 'resource')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } - $mform->setAdvanced($option); - } - - $mform->addElement('header', 'parameters', get_string('parameters', 'resource')); - - $optiongroups = array(); - $optiongroups[''] = array('-' => get_string('chooseaparameter', 'resource')); - $addto = &$optiongroups['']; - foreach ($this->parameters as $pname=>$param) { - if ($param['value']=='/optgroup') { - continue; - } - if ($param['value']=='optgroup') { - $optiongroups[$param['langstr']] = array(); - $addto = &$optiongroups[$param['langstr']]; - continue; - } - $addto[$pname] = $param['langstr']; - } - - for ($i = 0; $i < $this->maxparameters; $i++) { - $parametername = "parameter$i"; - $parsename = "parse$i"; - $group = array(); - $group[] =& $mform->createElement('text', $parsename, '', array('size'=>'12')); - $group[] =& $mform->createElement('selectgroups', $parametername, '', $optiongroups); - $mform->addGroup($group, 'pargroup'.$i, get_string('variablename', 'resource').'='.get_string('parameter', 'resource'), ' ', false); - $mform->setAdvanced('pargroup'.$i); - - $mform->setDefault($parametername, '-'); - } - } - -} - -?> diff --git a/mod/resource/type/html/resource.class.php b/mod/resource/type/html/resource.class.php deleted file mode 100644 index 76c6705c48100..0000000000000 --- a/mod/resource/type/html/resource.class.php +++ /dev/null @@ -1,203 +0,0 @@ -_postprocess($resource); - return parent::add_instance($resource); -} - - -function update_instance($resource) { - $this->_postprocess($resource); - return parent::update_instance($resource); -} - -function _postprocess(&$resource) { - global $RESOURCE_WINDOW_OPTIONS; - $alloptions = $RESOURCE_WINDOW_OPTIONS; - - if ($resource->windowpopup) { - $optionlist = array(); - foreach ($alloptions as $option) { - $optionlist[] = $option."=".$resource->$option; - unset($resource->$option); - } - $resource->popup = implode(',', $optionlist); - unset($resource->windowpopup); - $resource->options = ''; - - } else { - if (empty($resource->blockdisplay)) { - $resource->options = ''; - } else { - $resource->options = 'showblocks'; - } - unset($resource->blockdisplay); - $resource->popup = ''; - } -} - - -function display() { - global $CFG, $PAGE; - - $formatoptions = new object(); - $formatoptions->noclean = true; - - /// Set up some shorthand variables - $cm = $this->cm; - $course = $this->course; - $resource = $this->resource; - - // fix for MDL-9021, thanks Etienne Roz - // fix for MDL-15387, thanks to John Beedell - add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id); - - /// Are we displaying the course blocks? - if ($this->resource->options == 'showblocks') { - - parent::display_course_blocks_start(); - - echo format_text($this->resource->alltext, FORMAT_HTML, $formatoptions, $this->course->id); - if (has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $this->cm->id))) { - resource_portfolio_caller::add_button($this); - } - - parent::display_course_blocks_end(); - - } else { - - /// Set up generic stuff first, including checking for access - parent::display(); - - $pagetitle = strip_tags($course->shortname.': '.format_string($resource->name)); - $inpopup = optional_param('inpopup', '', PARAM_BOOL); - - if ($resource->popup) { - if ($inpopup) { /// Popup only - - print_header(); - print_simple_box(format_text($resource->alltext, FORMAT_HTML, $formatoptions, $course->id), - "center clearfix", "", "", "20"); - if (has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $this->cm->id))) { - resource_portfolio_caller::add_button($this); - } - print_footer($course); - } else { /// Make a page and a pop-up window - $navigation = build_navigation($this->navlinks, $cm); - - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, update_module_button($cm->id, $course->id, $this->strresource), - navmenu($course, $cm)); - - $PAGE->requires->js_function_call('openpopup', Array("/mod/resource/view.php?inpopup=true&id={$cm->id}","resource{$resource->id}",$resource->popup)); - - if (trim(strip_tags($resource->intro))) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - - $link = "wwwroot/mod/resource/view.php?inpopup=true&id={$cm->id}\" onclick=\"this.target='resource{$resource->id}'; return openpopup('/mod/resource/view.php?inpopup=true&id={$cm->id}', 'resource{$resource->id}','{$resource->popup}');\">".format_string($resource->name,true).""; - - echo '
    '; - print_string('popupresource', 'resource'); - echo '
    '; - print_string('popupresourcelink', 'resource', $link); - echo '
    '; - - print_footer($course); - } - } else { /// not a popup at all - $navigation = build_navigation($this->navlinks, $cm); - - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, update_module_button($cm->id, $course->id, $this->strresource), - navmenu($course, $cm)); - - print_simple_box(format_text($resource->alltext, FORMAT_HTML, $formatoptions, $course->id), "center clearfix", "", "", "20"); - if (has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $this->cm->id))) { - resource_portfolio_caller::add_button($this); - } - - $strlastmodified = get_string("lastmodified"); - echo "
    $strlastmodified: ".userdate($resource->timemodified)."
    "; - - print_footer($course); - } - - } - -} - -function setup_preprocessing(&$defaults){ - - if (!isset($defaults['popup'])) { - // use form defaults - - } else if (!empty($defaults['popup'])) { - $defaults['windowpopup'] = 1; - if (array_key_exists('popup', $defaults)) { - $rawoptions = explode(',', $defaults['popup']); - foreach ($rawoptions as $rawoption) { - $option = explode('=', trim($rawoption)); - $defaults[$option[0]] = $option[1]; - } - } - } else { - $defaults['windowpopup'] = 0; - if (array_key_exists('options', $defaults)) { - $defaults['blockdisplay'] = ($defaults['options']=='showblocks'); - } - } -} - -function setup_elements(&$mform) { - global $CFG, $RESOURCE_WINDOW_OPTIONS; - - $mform->addElement('htmleditor', 'alltext', get_string('fulltext', 'resource'), array('cols'=>85, 'rows'=>30)); - $mform->setType('alltext', PARAM_RAW); - $mform->setHelpButton('alltext', array('reading', 'writing', 'richtext2'), false, 'editorhelpbutton'); - $mform->addRule('alltext', get_string('required'), 'required', null, 'client'); - - $mform->addElement('header', 'displaysettings', get_string('display', 'resource')); - - $woptions = array(0 => get_string('pagewindow', 'resource'), 1 => get_string('newwindow', 'resource')); - $mform->addElement('select', 'windowpopup', get_string('display', 'resource'), $woptions); - $mform->setDefault('windowpopup', !empty($CFG->resource_popup)); - - $mform->addElement('checkbox', 'blockdisplay', get_string('showcourseblocks', 'resource')); - $mform->setDefault('blockdisplay', 0); - $mform->disabledIf('blockdisplay', 'windowpopup', 'eq', '1'); - $mform->setAdvanced('blockdisplay'); - - foreach ($RESOURCE_WINDOW_OPTIONS as $option) { - if ($option == 'height' or $option == 'width') { - $mform->addElement('text', $option, get_string('new'.$option, 'resource'), array('size'=>'4')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', '0'); - } else { - $mform->addElement('checkbox', $option, get_string('new'.$option, 'resource')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', '0'); - } - $mform->setAdvanced($option); - } -} - -function portfolio_prepare_package($exporter) { - return parent::portfolio_prepare_package_online($exporter); -} - -function portfolio_get_sha1() { - return parent::portfolio_get_sha1_online(); -} - - -} - -?> diff --git a/mod/resource/type/ims/deploy.php b/mod/resource/type/ims/deploy.php deleted file mode 100644 index af7eda5b82f89..0000000000000 --- a/mod/resource/type/ims/deploy.php +++ /dev/null @@ -1,422 +0,0 @@ -get_record ('course', array('id'=>$courseid)); - $cm = get_coursemodule_from_id('resource', $cmid); - $resource = $DB->get_record ('resource', array('id'=>$cm->instance)); - -/// Get some needed strings - $strdeploy = get_string('deploy','resource'); - -/// Instantiate a resource_ims object and modify its navigation - $resource_obj = new resource_ims ($cmid); - -/// Print the header of the page - $pagetitle = strip_tags($course->shortname.': '. - format_string($resource->name)).': '. - $strdeploy; - - if ($inpopup) { - print_header($pagetitle, $course->fullname); - } else { - - $resource_obj->navlinks[] = array('name' => $strdeploy, 'link' => '', 'type' => 'action'); - $navigation = build_navigation($resource_obj->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, - '', '', true, - update_module_button($cm->id, $course->id, $resource_obj->strresource)); - } - -/// Security Constraints (sesskey and isteacheredit) - if (!confirm_sesskey()) { - print_error('confirmsesskeybad', 'error'); - } else if (!has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid))) { - print_error('onlyeditingteachers', 'error'); - } - -/// -/// Main process, where everything is deployed -/// - -/// Set some variables - -/// Create directories - if (!$resourcedir = make_upload_directory($courseid.'/'.$CFG->moddata.'/resource/'.$resource->id)) { - print_error('errorcreatingdirectory', 'error', '', $CFG->moddata.'/resource/'.$resource->id); - } - -/// Ensure it's empty - if (!delete_dir_contents($resourcedir)) { - print_error('errorcleaningdirectory', 'error', '', $resourcedir); - } - -/// Copy files - $origin = $CFG->dataroot.'/'.$courseid.'/'.$file; - - if (!is_file($origin)) { - print_error('filenotfound' , 'error', '', $file); - } - $mimetype = mimeinfo("type", $file); - if ($mimetype != "application/zip") { - print_error('invalidfiletype', 'error', '', $file); - } - $resourcefile = $resourcedir.'/'.basename($origin); - if (!backup_copy_file($origin, $resourcefile)) { - print_error('errorcopyingfiles', 'error'); - } - -/// Unzip files - if (!unzip_file($resourcefile, '', false)) { - print_error('errorunzippingfiles', 'error'); - } - -/// Check for imsmanifest - if (!file_exists($resourcedir.'/imsmanifest.xml')) { - print_error('filenotfound', 'error', '', 'imsmanifest.xml'); - } - -/// Load imsmanifest to memory (instead of using a full parser, -/// we are going to use xmlize intensively (because files aren't too big) - if (!$imsmanifest = ims_file2var ($resourcedir.'/imsmanifest.xml')) { - print_error('errorreadingfile', 'error', '', 'imsmanifest.xml'); - } - -/// Check if the first line is a proper one, because I've seen some -/// packages with some control characters at the beginning. - $inixml = strpos($imsmanifest, '$item) { - if (!empty($resources[$item->identifierref])) { - $items[$key]->href = $resources[$item->identifierref]; - } else { - $items[$key]->href = ''; - } - } - -/// Create the INDEX (moodle_inx.ser - where the order of the pages are stored serialized) file - if (!ims_save_serialized_file($resourcedir.'/moodle_inx.ser', $items)) { - print_error('errorcreatingfile', 'error', '', 'moodle_inx.ser'); - } - -/// Create the HASH file (moodle_hash.ser - where the hash of the ims is stored serialized) file - $hash = $resource_obj->calculatefilehash($resourcefile); - if (!ims_save_serialized_file($resourcedir.'/moodle_hash.ser', $hash)) { - print_error('errorcreatingfile', 'error', '', 'moodle_hash.ser'); - } - -/// End button (go to view mode) - echo '
    '; - print_simple_box(get_string('imspackageloaded', 'resource'), 'center'); - $link = $CFG->wwwroot.'/mod/resource/view.php'; - $options['r'] = $resource->id; - $label = get_string('viewims', 'resource'); - $method = 'post'; - print_single_button($link, $options, $label, $method); - echo '
    '; - -/// -/// End of main process, where everything is deployed -/// - -/// Print the footer of the page - print_footer(); - -/// -/// Common and useful functions used by the body of the script -/// - - /*** This function will return a tree of manifests (xmlized) as they are - * found and extracted from one manifest file. The first manifest in the - * will be the main one, while the rest will be submanifests. In the - * future (when IMS CP suppors it, external submanifest will be detected - * and retrieved here too). See IMS specs for more info. - */ - function ims_extract_manifests($data) { - - $manifest = new stdClass; //To store found manifests in a tree structure - - /// If there are some manifests - if (!empty($data['manifest'])) { - /// Add manifest to results array - $manifest->data = $data['manifest']; - /// Look for submanifests - $submanifests = ims_extract_submanifests($data['manifest']['#']); - /// Add them as child - if (!empty($submanifests)) { - $manifest->childs = $submanifests; - } - } - /// Return tree of manifests found - return $manifest; - } - - /* This function will search recursively for submanifests returning an array - * containing them (xmlized) following a tree structure. - */ - function ims_extract_submanifests($data) { - - $submanifests = array(); //To store found submanifests - - /// If there are some manifests - if (!empty($data['manifest'])) { - /// Get them - foreach ($data['manifest'] as $submanifest) { - /// Create a new submanifest object - $submanifest_object = new stdClass; - $submanifest_object->data = $submanifest; - /// Look for more submanifests recursively - $moresubmanifests = ims_extract_submanifests($submanifest['#']); - /// Add them to results array - if (!empty($moresubmanifests)) { - $submanifest_object->childs = $moresubmanifests; - } - /// Add submanifest object to results array - $submanifests[] = $submanifest_object; - } - } - /// Return array of manifests found - return $submanifests; - } - - /*** This function will return an ordered and nested array of items - * that is a perfect representation of the prefered organization - */ - function ims_process_organizations($data) { - - global $CFG; - - /// Get the default organization - $default_organization = $data['@']['default']; - debugging('default_organization: '.$default_organization); - - /// Iterate (reverse) over organizations until we find the default one - if (empty($data['#']['organization'])) { /// Verify exists - return false; - } - $count_organizations = count($data['#']['organization']); - debugging('count_organizations: '.$count_organizations); - - $current_organization = $count_organizations - 1; - while ($current_organization >= 0) { - /// Load organization and check it - $organization = $data['#']['organization'][$current_organization]; - if ($organization['@']['identifier'] == $default_organization) { - $current_organization = -1; //Match, so exit. - } - $current_organization--; - } - - /// At this point we MUST have the final organization - debugging('final organization: '.$organization['#']['title'][0]['#']); - if (empty($organization)) { - return false; //Error, no organization found - } - - /// Extract items map from organization - $items = $organization['#']['item']; - if (empty($organization['#']['item'])) { /// Verify exists - return false; - } - if (!$itemmap = ims_process_items($items)) { - return false; //Error, no items found - } - return $itemmap; - } - - /*** This function gets the xmlized representation of the items - * and returns an array of items, ordered, with level and info - */ - function ims_process_items($items, $level = 1, $id = 1, $parent = 0) { - global $CFG; - - $itemmap = array(); - - /// Iterate over items from start to end - $count_items = count($items); - debugging('level '.$level.'-count_items: '.$count_items); - - $current_item = 0; - while ($current_item < $count_items) { - /// Load item - $item = $items[$current_item]; - $obj_item = new stdClass; - $obj_item->title = $item['#']['title'][0]['#']; - $obj_item->identifier = $item['@']['identifier']; - $obj_item->identifierref = $item['@']['identifierref']; - $obj_item->id = $id; - $obj_item->level = $level; - $obj_item->parent = $parent; - /// Only if the item has everything - if (!empty($obj_item->title) && - !empty($obj_item->identifier)) { - /// Add to itemmap - $itemmap[$id] = $obj_item; - debugging('level '.$level.'-id '.$id.'-parent '.$parent.'-'.$obj_item->title); - /// Counters go up - $id++; - /// Check for subitems recursively - $subitems = $item['#']['item']; - if (count($subitems)) { - /// Recursive call - $subitemmap = ims_process_items($subitems, $level+1, $id, $obj_item->id); - /// Add at the end and counters if necessary - if ($count_subitems = count($subitemmap)) { - foreach ($subitemmap as $subitem) { - /// Add the subitem to the main items array - $itemmap[$subitem->id] = $subitem; - /// Counters go up - $id++; - } - } - } - } - $current_item++; - } - return $itemmap; - } - - /*** This function will load an array of resources to be used later. - * Keys are identifiers - */ - function ims_load_resources($data, $manifest_base, $resources_base) { - global $CFG; - - $resources = array(); - - if (empty($data)) { /// Verify exists - return false; - } - $count_resources = count($data); - debugging('count_resources: '.$count_resources); - - $current_resource = 0; - while ($current_resource < $count_resources) { - /// Load resource - $resource = $data[$current_resource]; - - /// Create a new object resource - $obj_resource = new stdClass; - $obj_resource->identifier = $resource['@']['identifier']; - $obj_resource->resource_base = $resource['@']['xml:base']; - $obj_resource->href = $resource['@']['href']; - if (empty($obj_resource->href)) { - $obj_resource->href = $resource['#']['file']['0']['@']['href']; - } - - /// Some packages are poorly done and use \ in roots. This makes them - /// not display since the URLs are not valid. - if (!empty($obj_resource->href)) { - $obj_resource->href = strtr($obj_resource->href, "\\", '/'); - } - - /// Only if the resource has everything - if (!empty($obj_resource->identifier) && - !empty($obj_resource->href)) { - /// Add to resources (identifier as key) - /// Depending of $manifest_base, $resources_base and the particular - /// $resource_base variable, concatenate them to build the correct href - $href_base = ''; - if (!empty($manifest_base)) { - $href_base = $manifest_base; - } - if (!empty($resources_base)) { - $href_base .= $resources_base; - } - if (!empty($obj_resource->resource_base)) { - $href_base .= $obj_resource->resource_base; - } - $resources[$obj_resource->identifier] = $href_base.$obj_resource->href; - } - /// Counters go up - $current_resource++; - } - return $resources; - } - -?> diff --git a/mod/resource/type/ims/dummyapi.js b/mod/resource/type/ims/dummyapi.js deleted file mode 100644 index 2a956948eb0ff..0000000000000 --- a/mod/resource/type/ims/dummyapi.js +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Dummy SCORM API -*/ - -function GenericAPIAdaptor(){ - this.LMSInitialize = LMSInitializeMethod; - this.LMSGetValue = LMSGetValueMethod; - this.LMSSetValue = LMSSetValueMethod; - this.LMSCommit = LMSCommitMethod; - this.LMSFinish = LMSFinishMethod; - this.LMSGetLastError = LMSGetLastErrorMethod; - this.LMSGetErrorString = LMSGetErrorStringMethod; - this.LMSGetDiagnostic = LMSGetDiagnosticMethod; -} -/* -* LMSInitialize. -*/ -function LMSInitializeMethod(parameter){return "true";} -/* -* LMSFinish. -*/ -function LMSFinishMethod(parameter){return "true";} -/* -* LMSCommit. -*/ -function LMSCommitMethod(parameter){return "true";} -/* -* LMSGetValue. -*/ -function LMSGetValueMethod(element){return "";} -/* -* LMSSetValue. -*/ -function LMSSetValueMethod(element, value){return "true";} -/* -* LMSGetLastErrorString -*/ -function LMSGetErrorStringMethod(errorCode){return "No error";} -/* -* LMSGetLastError -*/ -function LMSGetLastErrorMethod(){return "0";} -/* -* LMSGetDiagnostic -*/ -function LMSGetDiagnosticMethod(errorCode){return "No error. No errors were encountered. Successful API call.";} - -var API = new GenericAPIAdaptor; \ No newline at end of file diff --git a/mod/resource/type/ims/finder.php b/mod/resource/type/ims/finder.php deleted file mode 100644 index 91ff27fa1654e..0000000000000 --- a/mod/resource/type/ims/finder.php +++ /dev/null @@ -1,139 +0,0 @@ -repository/$directory"))) die("Can't open directory \"$CFG->repository/$directory\""); - -/// Loops though dir building a list of all relevent entries. Ignores files. -/// Asks for deploy if admin user AND no serialized file found. - while (false !== ($filename = readdir($repository_dir))) { - if ($filename != '.' && $filename != '..' && is_dir("$CFG->repository/$directory/$filename")) { - unset($item); - $item->type = ''; - $item->name = 0; - $item->path = "$directory/$filename"; - - /// No manifest => normal, browsable directory. - if (!file_exists("$CFG->repository/$item->path/imsmanifest.xml")) { - $item->type = 'directory'; - $item->name = $filename; - } - /// Manifest, so IMS CP. - else { - if (file_exists("$CFG->repository/$item->path/moodle_inx.ser")) { - $item->type = 'deployed'; - $index = ims_load_serialized_file("$CFG->repository/$item->path/moodle_inx.ser"); - $item->name = $index['title']; - } - else { - $item->type = 'not deployed'; - $item->name = $filename; - } - } - $items[] = $item; - } - } - closedir($repository_dir); - -/// Prints the toolbar. - echo '
    '; - ims_print_crumbtrail($directory, $choose); - -/// If admin, add extra buttons - redeploy & help. - if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { - echo " | ($strdeployall) "; - helpbutton("deploy", get_string("deployall", "resource"), "resource", true); - } - echo '
    '; - -/// Prints the file list from list generated above. - echo '
    '; - ?> - - '; - if ($items != array()) { - - foreach ($items as $item) { - if ($item->type == 'deployed') { - echo "
  • \"IMS $item->name" . - "(path', true); set_opener_value('$name', '$item->name', false); window.close()\" href=\"#\">$strchoose) " . - "(path&choose=$choose\">$strpreview)
  • \n"; - } - else if ($item->type == 'not deployed') { - /// Only displays non-deployed IMS CP's if admin user. - if (has_capability('moodle/site:config', get_context_instance(CONTEXT_SYSTEM))) { - echo "
  • \"IMS $item->path - $strnotdeployed (path\">$strdeploy)
  • \n"; - } - } - else if ($item->type == 'directory') { - echo "
  • \"IMS path&choose=$choose\">$item->name
  • \n"; - } - } - } - else { - echo "
  • $stremptyfolder
  • "; - } - echo ""; - -/// Print footer and exit. - echo "
    "; - exit; - -/// Generates the crumbtrial from $directory. Just splits up on '/'. - function ims_print_crumbtrail($directory, $choose='') { - $strrepository = get_string('repository','resource'); - - $arr = explode('/', $directory); - $last = array_pop($arr); - if (trim($directory, '/') == '') { - echo $strrepository; - return; - } - else { - $output = "$strrepository » "; - } - $itemdir = ''; - foreach ($arr as $item) { - if ($item == '') continue; - $itemdir .= '/'.$item; - $output .= "$item » "; - } - $output .= $last; - echo $output; - } -?> diff --git a/mod/resource/type/ims/images/dir.gif b/mod/resource/type/ims/images/dir.gif deleted file mode 100644 index fd6af277d71e8..0000000000000 Binary files a/mod/resource/type/ims/images/dir.gif and /dev/null differ diff --git a/mod/resource/type/ims/images/ims.gif b/mod/resource/type/ims/images/ims.gif deleted file mode 100644 index fc60d4ece071f..0000000000000 Binary files a/mod/resource/type/ims/images/ims.gif and /dev/null differ diff --git a/mod/resource/type/ims/ims.js b/mod/resource/type/ims/ims.js deleted file mode 100644 index f6673615dc53e..0000000000000 --- a/mod/resource/type/ims/ims.js +++ /dev/null @@ -1,20 +0,0 @@ -window.onresize = function() { - resizeiframe(imsdata.jsarg, imsdata.customcorners); -}; -window.name='ims-cp-page'; - -// Set Interval until ims-containerdiv and (ims-contentframe or ims-contentframe-no-nav) is available -function waiting() { - var cd = document.getElementById('ims-containerdiv'); - var cf = document.getElementById('ims-contentframe'); - var cfnv = document.getElementById('ims-contentframe-no-nav'); - - if (cd && (cf || cfnv)) { - resizeiframe(imsdata.jsarg, imsdata.customcorners); - clearInterval(ourInterval); - return true; - } - return false; -} - -var ourInterval = setInterval('waiting()', 100); \ No newline at end of file diff --git a/mod/resource/type/ims/preview.php b/mod/resource/type/ims/preview.php deleted file mode 100644 index 2294df6271c9a..0000000000000 --- a/mod/resource/type/ims/preview.php +++ /dev/null @@ -1,170 +0,0 @@ -repository . '/' . $directory; - -/// Confirm that the IMS package has been deployed. Hash not generated -/// for repository ones. - if (!file_exists($deploydir.'/moodle_inx.ser')) { - $errortext = "Not Deployed"; - print_header(); - print_simple_box_start('center', '60%'); - echo '

    '.$errortext.'

    '; - print_footer(); - exit; - } - -/// Load serialized IMS CP index to memory only once. - if (empty($items)) { - if (!$items = ims_load_serialized_file($deploydir.'/moodle_inx.ser')) { - print_error('errorreadingfile', 'error', '', 'moodle_inx.ser'); - } - } - -/// fast forward to first non-index page - while (empty($items[$page]->href)) $page++; - -/// Select direction - if (get_string('thisdirection') == 'rtl') { - $direction = ' dir="rtl"'; - } else { - $direction = ' dir="ltr"'; - } - - $jsarg = 'true'; - if (!empty($THEME->customcorners)) { - $customcorners = 'true'; - } else { - $customcorners = 'false'; - } - $PAGE->requires->data_for_js('imsdata', Array('customcorners'=>$customcorners, 'jsarg'=>$jsarg)); - $PAGE->requires->js('mod/resource/type/ims/dummyapi.js')->in_head(); - $PAGE->requires->js('mod/resource/type/ims/resize.js')->in_head(); - $PAGE->requires->js('mod/resource/type/ims/ims.js')->in_head(); - -/// The output here - -/// moodle header - print_header(); -/// content - this produces everything else - -/// adds side navigation bar if needed. must also adjust width of iframe to accomodate - echo "
    "; - preview_buttons($directory, $items['title'], $choose); - echo preview_ims_generate_toc($items, $directory, 0, $page); echo "
    "; - - $fullurl = "$CFG->repositorywebroot/$directory/".$items[$page]->href; -/// prints iframe filled with $fullurl ;width:".$iframewidth." missing also height=\"420px\" - echo ""; //Content frame -/// moodle footer - echo ""; - - /*** This function will generate the TOC file for the package - * from an specified parent to be used in the view of the IMS - */ - function preview_ims_generate_toc($items, $directory, $page=0, $selected_page) { - global $CFG; - - $contents = ''; - - /// Configure links behaviour - $fullurl = '?directory='.$directory.'&page='; - - /// Iterate over items to build the menu - $currlevel = 0; - $currorder = 0; - $endlevel = 0; - $openlielement = false; - foreach ($items as $item) { - if (!is_object($item)) { - continue; - } - /// Skip pages until we arrive to $page - if ($item->id < $page) { - continue; - } - /// Arrive to page, we store its level - if ($item->id == $page) { - $endlevel = $item->level; - continue; - } - /// We are after page and inside it (level > endlevel) - if ($item->id > $page && $item->level > $endlevel) { - /// Start Level - if ($item->level > $currlevel) { - $contents .= '
      '; - $openlielement = false; - } - /// End Level - if ($item->level < $currlevel) { - $contents .= ''; - $contents .= '
    '; - } - /// If we have some openlielement, just close it - if ($openlielement) { - $contents .= ''; - } - /// Add item - $contents .= '
  • '; - if (!empty($item->href)) { - if ($item->id == $selected_page) $contents .= '
    '; - $contents .= ''.$item->title.''; - if ($item->id == $selected_page) $contents .= '
    '; - } else { - $contents .= $item->title; - } - $currlevel = $item->level; - $openlielement = true; - continue; - } - /// We have reached endlevel, exit - if ($item->id > $page && $item->level <= $endlevel) { - break; - } - } - /// Close up to $endlevel - for ($i=$currlevel;$i>$endlevel;$i--) { - $contents .= '
  • '; - $contents .= ''; - } - - return $contents; - } - - function preview_buttons($directory, $name, $choose='') { - $strchoose = get_string('choose','resource'); - $strback = get_string('back','resource'); - - $path = $directory; - $arr = explode('/', $directory); - array_pop($arr); - $directory = implode('/', $arr); - ?> - - ". - "($strback) ". - "($strchoose)"; - } - -?> diff --git a/mod/resource/type/ims/repository_config.php b/mod/resource/type/ims/repository_config.php deleted file mode 100644 index 76e1ed6c06aa4..0000000000000 --- a/mod/resource/type/ims/repository_config.php +++ /dev/null @@ -1,5 +0,0 @@ -repositoryactivate = false; - $CFG->repository = "C:/public/www/html/ims_repository"; - $CFG->repositorywebroot = "/ims_repository"; -?> \ No newline at end of file diff --git a/mod/resource/type/ims/repository_deploy.php b/mod/resource/type/ims/repository_deploy.php deleted file mode 100644 index 981d5a4ed40ed..0000000000000 --- a/mod/resource/type/ims/repository_deploy.php +++ /dev/null @@ -1,437 +0,0 @@ -repository/$file"; - $dir = opendir($dirpath); - while (false !== ($filename = readdir($dir))) { - if ($filename != '.' && $filename != '..') { - $path = $dirpath.'/'.$filename; - if (is_dir($path) && file_exists("$path/imsmanifest.xml")) { - if ($all == 'force' || !file_exists("$path/moodle_inx.ser")) { - echo "DEPLOYING $path
    "; - ims_deploy_file($file.'/'.$filename, $all); - } - } - else if (is_dir($path)) { - echo "DEPLOYING $path
    "; - ims_deploy_folder($file.'/'.$filename, $all); - } - else { - echo "WONT DEPLOY $path
    "; - } - } - } - closedir($dir); - } - - function ims_deploy_file($file, $all='') { - global $CFG; - - /// Load request parameters - $resourcedir = "$CFG->repository/$file"; - - /// Get some needed strings - $strdeploy = get_string('deploy','resource'); - - /// - /// Main process, where everything is deployed - /// - - /// Load imsmanifest to memory (instead of using a full parser, - /// we are going to use xmlize intensively (because files aren't too big) - if (!$imsmanifest = ims_file2var ($resourcedir.'/imsmanifest.xml')) { - print_error('errorreadingfile', 'error', '', 'imsmanifest.xml'); - } - - /// Check if the first line is a proper one, because I've seen some - /// packages with some control characters at the beginning. - $inixml = strpos($imsmanifest, '$item) { - if (!empty($resources[$item->identifierref])) { - $items[$key]->href = $resources[$item->identifierref]; - } else { - $items[$key]->href = ''; - } - } - - /// Create the INDEX (moodle_inx.ser - where the order of the pages are stored serialized) file - $items['title'] = $title; - if (!ims_save_serialized_file($resourcedir.'/moodle_inx.ser', $items)) { - print_error('errorcreatingfile', 'error', '', 'moodle_inx.ser'); - } - - /// No zip so no HASH - - /// End button (go to view mode) - echo '
    '; - print_simple_box(get_string('imspackageloaded', 'resource'), 'center'); - $link = $CFG->wwwroot.'/mod/resource/type/ims/preview.php'; - $options['directory'] = $file; - $label = get_string('viewims', 'resource'); - $method = 'get'; - print_single_button($link, $options, $label, $method); - echo '
    '; - - /// - /// End of main process, where everything is deployed - /// - } -/// -/// Common and useful functions used by the body of the script -/// - - /*** This function will return a tree of manifests (xmlized) as they are - * found and extracted from one manifest file. The first manifest in the - * will be the main one, while the rest will be submanifests. In the - * future (when IMS CP suppors it, external submanifest will be detected - * and retrieved here too). See IMS specs for more info. - */ - function ims_extract_manifests($data) { - - $manifest = new stdClass; //To store found manifests in a tree structure - - /// If there are some manifests - if (!empty($data['manifest'])) { - /// Add manifest to results array - $manifest->data = $data['manifest']; - /// Look for submanifests - $submanifests = ims_extract_submanifests($data['manifest']['#']); - /// Add them as child - if (!empty($submanifests)) { - $manifest->childs = $submanifests; - } - } - /// Return tree of manifests found - return $manifest; - } - - /* This function will search recursively for submanifests returning an array - * containing them (xmlized) following a tree structure. - */ - function ims_extract_submanifests($data) { - - $submanifests = array(); //To store found submanifests - - /// If there are some manifests - if (!empty($data['manifest'])) { - /// Get them - foreach ($data['manifest'] as $submanifest) { - /// Create a new submanifest object - $submanifest_object = new stdClass; - $submanifest_object->data = $submanifest; - /// Look for more submanifests recursively - $moresubmanifests = ims_extract_submanifests($submanifest['#']); - /// Add them to results array - if (!empty($moresubmanifests)) { - $submanifest_object->childs = $moresubmanifests; - } - /// Add submanifest object to results array - $submanifests[] = $submanifest_object; - } - } - /// Return array of manifests found - return $submanifests; - } - - /*** This function will return an ordered and nested array of items - * that is a perfect representation of the prefered organization - */ - function ims_process_organizations($data) { - - global $CFG; - - /// Get the default organization - $default_organization = $data['@']['default']; - debugging('default_organization: '.$default_organization); - - /// Iterate (reverse) over organizations until we find the default one - if (empty($data['#']['organization'])) { /// Verify exists - return false; - } - $count_organizations = count($data['#']['organization']); - debugging('count_organizations: '.$count_organizations); - - $current_organization = $count_organizations - 1; - while ($current_organization >= 0) { - /// Load organization and check it - $organization = $data['#']['organization'][$current_organization]; - if ($organization['@']['identifier'] == $default_organization) { - $current_organization = -1; //Match, so exit. - } - $current_organization--; - } - - /// At this point we MUST have the final organization - debugging('final organization: '.$organization['#']['title'][0]['#']); - if (empty($organization)) { - return false; //Error, no organization found - } - - /// Extract items map from organization - $items = $organization['#']['item']; - if (empty($organization['#']['item'])) { /// Verify exists - return false; - } - if (!$itemmap = ims_process_items($items)) { - return false; //Error, no items found - } - return $itemmap; - } - - /*** This function gets the xmlized representation of the items - * and returns an array of items, ordered, with level and info - */ - function ims_process_items($items, $level = 1, $id = 1, $parent = 0) { - global $CFG; - - $itemmap = array(); - - /// Iterate over items from start to end - $count_items = count($items); - debugging('level '.$level.'-count_items: '.$count_items); - - $current_item = 0; - while ($current_item < $count_items) { - /// Load item - $item = $items[$current_item]; - $obj_item = new stdClass; - $obj_item->title = $item['#']['title'][0]['#']; - $obj_item->identifier = $item['@']['identifier']; - $obj_item->identifierref = $item['@']['identifierref']; - $obj_item->id = $id; - $obj_item->level = $level; - $obj_item->parent = $parent; - /// Only if the item has everything - if (!empty($obj_item->title) && - !empty($obj_item->identifier)) { - /// Add to itemmap - $itemmap[$id] = $obj_item; - debugging('level '.$level.'-id '.$id.'-parent '.$parent.'-'.$obj_item->title); - /// Counters go up - $id++; - /// Check for subitems recursively - $subitems = $item['#']['item']; - if (count($subitems)) { - /// Recursive call - $subitemmap = ims_process_items($subitems, $level+1, $id, $obj_item->id); - /// Add at the end and counters if necessary - if ($count_subitems = count($subitemmap)) { - foreach ($subitemmap as $subitem) { - /// Add the subitem to the main items array - $itemmap[$subitem->id] = $subitem; - /// Counters go up - $id++; - } - } - } - } - $current_item++; - } - return $itemmap; - } - - /*** This function will load an array of resources to be used later. - * Keys are identifiers - */ - function ims_load_resources($data, $manifest_base, $resources_base) { - global $CFG; - - $resources = array(); - - if (empty($data)) { /// Verify exists - return false; - } - $count_resources = count($data); - debugging('count_resources: '.$count_resources); - - $current_resource = 0; - while ($current_resource < $count_resources) { - /// Load resource - $resource = $data[$current_resource]; - - /// Create a new object resource - $obj_resource = new stdClass; - $obj_resource->identifier = $resource['@']['identifier']; - $obj_resource->resource_base = $resource['@']['xml:base']; - $obj_resource->href = $resource['@']['href']; - if (empty($obj_resource->href)) { - $obj_resource->href = $resource['#']['file']['0']['@']['href']; - } - - /// Some packages are poorly done and use \ in roots. This makes them - /// not display since the URLs are not valid. - if (!empty($obj_resource->href)) { - $obj_resource->href = strtr($obj_resource->href, "\\", '/'); - } - - /// Only if the resource has everything - if (!empty($obj_resource->identifier) && - !empty($obj_resource->href)) { - /// Add to resources (identifier as key) - /// Depending of $manifest_base, $resources_base and the particular - /// $resource_base variable, concatenate them to build the correct href - $href_base = ''; - if (!empty($manifest_base)) { - $href_base = $manifest_base; - } - if (!empty($resources_base)) { - $href_base .= $resources_base; - } - if (!empty($obj_resource->resource_base)) { - $href_base .= $obj_resource->resource_base; - } - $resources[$obj_resource->identifier] = $href_base.$obj_resource->href; - } - /// Counters go up - $current_resource++; - } - return $resources; - } - - /*** This function finds out the title of the resource from the XML. - * First 2 conditions cover nearly all cases. The third is a fair guess - * if no metadata is supplied. This is eventually saved in the serialized - * hash as $items['title']. - */ - function ims_get_cp_title($xmlobj) { - $md = $xmlobj['manifest']['#']['metadata']['0']['#']; - if (isset($md['imsmd:lom'])) { - return $md['imsmd:lom']['0']['#']['imsmd:general']['0']['#']['imsmd:title']['0']['#']['imsmd:langstring']['0']['#']; - } - else if (isset($md['imsmd:record'])) { - return $md['imsmd:record']['0']['#']['imsmd:general']['0']['#']['imsmd:title']['0']['#']['imsmd:langstring']['0']['#']; - } - else if ($title = $xmlobj['manifest']['#']['organizations']['0']['#']['organization']['0']['#']['title']['0']['#']) { - return $title; - } - else { - return "NO TITLE FOUND"; - } - } -?> diff --git a/mod/resource/type/ims/resize.js b/mod/resource/type/ims/resize.js deleted file mode 100644 index c5a8d3f5fe6d6..0000000000000 --- a/mod/resource/type/ims/resize.js +++ /dev/null @@ -1,116 +0,0 @@ -/* - * This script resizes everything to fit the iframe - * of the ims-cp resource type. Credits goes to Andrew Walker. - */ - -function getElementStyle(obj, prop, cssProp) { - var ret = ''; - - if (obj.currentStyle) { - ret = obj.currentStyle[prop]; - } else if (document.defaultView && document.defaultView.getComputedStyle) { - var compStyle = document.defaultView.getComputedStyle(obj, null); - ret = compStyle.getPropertyValue(cssProp); - } - - if (ret == 'auto') ret = '0'; - return ret; -} - -function resizeiframe (hasNav, customCorners) { - -/// Calculate window width and height - var winWidth = 0, winHeight = 0; - if( typeof( window.innerWidth ) == 'number' ) { - //Non-IE - winWidth = window.innerWidth; - winHeight = window.innerHeight; - } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { - //IE 6+ in 'standards compliant mode' - winWidth = document.documentElement.clientWidth; - winHeight = document.documentElement.clientHeight; - } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) { - //IE 4 compatible - winWidth = document.body.clientWidth; - winHeight = document.body.clientHeight; - } - -/// Calculate margins - var topMargin = parseInt(getElementStyle(document.getElementsByTagName('body')[0], 'marginTop', 'margin-top')); - var bottomMargin = parseInt(getElementStyle(document.getElementsByTagName('body')[0], 'marginBottom', 'margin-bottom')); - var leftMargin = parseInt(getElementStyle(document.getElementsByTagName('body')[0], 'marginLeft', 'margin-left')); - var rightMargin = parseInt(getElementStyle(document.getElementsByTagName('body')[0], 'marginRight', 'margin-right')); - -/// Calculate heights - var header = document.getElementById('content'); - var headerHeight = 0; - if (header) { - headerHeight = header.offsetTop + parseInt(getElementStyle(header, 'marginTop', 'margin-top')) + parseInt(getElementStyle(header, 'marginBottom', 'margin-bottom')); - } - - var contentbt = document.getElementById('content-bt'); - var contentbtHeight = 0; - if (contentbt) { - contentbtHeight = contentbt.offsetHeight + parseInt(getElementStyle(contentbt, 'marginTop', 'margin-top')) + parseInt(getElementStyle(contentbt, 'marginBottom', 'margin-bottom')); - } - - var contentbb = document.getElementById('content-bb'); - var contentbbHeight = 0; - if (contentbb) { - contentbbHeight = contentbb.offsetHeight + parseInt(getElementStyle(contentbb, 'marginTop', 'margin-top')) + parseInt(getElementStyle(contentbb, 'marginBottom', 'margin-bottom')); - } - - var navbar = document.getElementById('ims-nav-bar'); - var navbarHeight = 0; - if (navbar) { - navbarHeight = navbar.offsetHeight + parseInt(getElementStyle(navbar, 'marginTop', 'margin-top')) + parseInt(getElementStyle(navbar, 'marginBottom', 'margin-bottom'));; - } - - var footer = document.getElementById('footer'); - var footerHeight = 0; - if (footer) { - footerHeight = footer.offsetHeight + parseInt(getElementStyle(footer, 'marginTop', 'margin-top')) + parseInt(getElementStyle(footer, 'marginBottom', 'margin-bottom')); - } - - -/// Calculate the used height - var usedHeight = headerHeight + - contentbtHeight + - navbarHeight + - contentbbHeight + - footerHeight + - bottomMargin + 15; /// Plus 15 points to avoid the wrong vertical scroll bar on some browsers - -/// Calculate widths - var menu = document.getElementById('ims-menudiv'); - var menuWidth = 0; - var menuLeft = 0; - if (menu) { - menuLeft = menu.offsetLeft; - menuWidth = menu.offsetWidth + parseInt(getElementStyle(menu, 'marginLeft', 'margin-left')) + parseInt(getElementStyle(menu, 'marginRight', 'margin-right')) + 2; /// +2 to leave 1px menu borders - } - - var container = document.getElementById('ims-containerdiv'); - var containerWidth = 0; - if (container) { - containerWidth = container.offsetWidth - 2; /// -2 to leave some right margin in the container div - } - -/// Calculate the used width - var usedWidth = winWidth - containerWidth + menuWidth; - -/// Set contentframe dimensions - if (hasNav == true) { - document.getElementById('ims-contentframe').style.height = (winHeight - usedHeight)+'px'; - document.getElementById('ims-contentframe').style.width = (winWidth - usedWidth)+'px'; - document.getElementById('ims-contentframe').style.left = (menuLeft + menuWidth)+'px'; - } else { - document.getElementById('ims-contentframe-no-nav').style.height = (winHeight - usedHeight)+'px'; - document.getElementById('ims-contentframe-no-nav').style.width = (winWidth - usedWidth)+'px'; - } - -/// Set containerdiv dimensions - document.getElementById('ims-containerdiv').style.height = (winHeight - usedHeight)+'px'; -} - - diff --git a/mod/resource/type/ims/resource.class.php b/mod/resource/type/ims/resource.class.php deleted file mode 100644 index 957777e8467e5..0000000000000 --- a/mod/resource/type/ims/resource.class.php +++ /dev/null @@ -1,912 +0,0 @@ - (5) false. Add graying out on setup. - - -require_once($CFG->libdir.'/filelib.php'); -require_once($CFG->dirroot.'/mod/resource/type/ims/repository_config.php'); - - -/** -* Extend the base resource class for ims resources -*/ -class resource_ims extends resource_base { - - var $parameters; //Attribute of this class where we'll store all the IMS deploy preferences - - function resource_ims($cmid=0) { - /// super constructor - parent::resource_base($cmid); - - /// prevent notice - if (empty($this->resource->alltext)) { - $this->resource->alltext=''; - } - /// set own attributes - $this->parameters = $this->alltext2parameters($this->resource->alltext); - - /// navigation menu forces other settings - if ($this->parameters->navigationmenu) { - $this->parameters->tableofcontents = 0; - $this->parameters->navigationuparrow = 0; - $this->parameters->skipsubmenus = 1; - } - - /// Is it in the repository material or not? - if (isset($this->resource->reference)) { - $file = $this->resource->reference; - if ($file[0] == '#') { - $this->isrepository = true; - $file = ltrim($file, '#'); - $this->resource->reference = $file; - } else { - $this->isrepository = false; - } - } else { - $this->isrepository = false; - } - } - - /*** - * This function converts parameters stored in the alltext field to the proper - * this->parameters object storing the special configuration of this resource type - */ - function alltext2parameters($alltext) { - /// set parameter defaults - $alltextfield = new stdClass(); - $alltextfield->tableofcontents=0; - $alltextfield->navigationbuttons=0; - $alltextfield->navigationmenu=1; - $alltextfield->skipsubmenus=1; - $alltextfield->navigationupbutton=1; - - /// load up any stored parameters - if (!empty($alltext)) { - $parray = explode(',', $alltext); - foreach ($parray as $key => $fieldstring) { - $field = explode('=', $fieldstring); - $alltextfield->$field[0] = $field[1]; - } - } - - return $alltextfield; - } - - /*** - * This function converts the this->parameters attribute (object) to the format - * needed to save them in the alltext field to store all the special configuration - * of this resource type - */ - function parameters2alltext($parameters) { - $optionlist = array(); - - $optionlist[] = 'tableofcontents='.$parameters->tableofcontents; - $optionlist[] = 'navigationbuttons='.$parameters->navigationbuttons; - $optionlist[] = 'skipsubmenus='.$parameters->skipsubmenus; - $optionlist[] = 'navigationmenu='.$parameters->navigationmenu; - $optionlist[] = 'navigationupbutton='.$parameters->navigationupbutton; - - return implode(',', $optionlist); - } - - /*** - * This function will convert all the parameters configured in the resource form - * to a this->parameter attribute (object) - */ - function form2parameters($resource) { - $parameters = new stdClass; - $parameters->tableofcontents = isset($resource->param_tableofcontents) ? $resource->param_tableofcontents : 0; - $parameters->navigationbuttons = $resource->param_navigationbuttons; - $parameters->skipsubmenus = isset($resource->param_skipsubmenus) ? $resource->param_skipsubmenus : 0; - $parameters->navigationmenu = $resource->param_navigationmenu; - $parameters->navigationupbutton = isset($resource->param_navigationupbutton) ? $resource->param_navigationupbutton : 0; - - return $parameters; - } - - /*** This function checks for errors in the status or deployment of the IMS - * Content Package returning an error code: - * 1 = Not a .zip file. - * 2 = Zip file doesn't exist - * 3 = Package not deployed. - * 4 = Package has changed since deployed. - * If the IMS CP is one from the central repository, then we instead check - * with the following codes: - * 5 = Not deployed. Since repository is central must be admin to deploy so terminate - */ - function check4errors($file, $course, $resource) { - global $CFG; - - if ($this->isrepository) { - /// Calculate the path were the IMS package must be deployed - $deploydir = $CFG->repository . $file; - - /// Confirm that the IMS package has been deployed. These files must exist if - /// the package is deployed: moodle_index.ser and moodle_hash.ser - if (!file_exists($deploydir.'/moodle_inx.ser')) { - return 5; //Error - } - } - else { - /// Check for zip file type - $mimetype = mimeinfo("type", $file); - if ($mimetype != "application/zip") { - return 1; //Error - } - - /// Check if the uploaded file exists - if (!file_exists($CFG->dataroot.'/'.$course->id.'/'.$file)) { - return 2; //Error - } - - /// Calculate the path were the IMS package must be deployed - $deploydir = $CFG->dataroot.'/'.$course->id.'/'.$CFG->moddata.'/resource/'.$resource->id; - - - /// Confirm that the IMS package has been deployed. These files must exist if - /// the package is deployed: moodle_index.ser and moodle_hash.ser - if (!file_exists($deploydir.'/moodle_inx.ser') || - !file_exists($deploydir.'/moodle_hash.ser')) { - return 3; //Error - } - - /// If teacheredit, make, hash check. It's the md5 of the name of the file - /// plus its size and modification date - /// not sure if this capability is suitable - if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))) { - if (!$this->checkpackagehash($file, $course, $resource)) { - return 4; - } - } - } - - /// We've arrived here. Everything is ok - return 0; - } - - /*** This function will check that the ims package (zip file) uploaded - * isn't changed since it was deployed. - */ - function checkpackagehash($file, $course, $resource) { - global $CFG; - - /// Calculate paths - $zipfile = $CFG->dataroot.'/'.$course->id.'/'.$file; - $hashfile= $CFG->dataroot.'/'.$course->id.'/'.$CFG->moddata.'/resource/'.$resource->id.'/moodle_hash.ser'; - /// Get deloyed hash value - $f = fopen ($hashfile,'r'); - $deployedhash = fread($f, filesize($hashfile)); - fclose ($f); - /// Unserialize the deployed hash - $deployedhash = unserialize($deployedhash); - /// Calculate uploaded file hash value - $uploadedhash = $this->calculatefilehash($zipfile); - - /// Compare them - return ($deployedhash == $uploadedhash); - } - - /*** This function will calculate the hash of any file passes as argument. - * It's based in a md5 of the filename, filesize and 20 first bytes (it includes - * the zip CRC at byte 15). - */ - function calculatefilehash($filefullpath) { - - /// Name and size - $filename = basename($filefullpath); - $filesize = filesize($filefullpath); - /// Read first 20cc - $f = fopen ($filefullpath,'r'); - $data = fread($f, 20); - fclose ($f); - - return md5($filename.'-'.$filesize.'-'.$data); - } - - /** - * Add new instance of file resource - * - * Create alltext field before calling base class function. - * - * @param resource object - */ - function add_instance($resource) { - $this->_postprocess($resource); - return parent::add_instance($resource); - } - - - /** - * Update instance of file resource - * - * Create alltext field before calling base class function. - * - * @param resource object - */ - function update_instance($resource) { - $this->_postprocess($resource); - return parent::update_instance($resource); - } - - function _postprocess(&$resource) { - global $RESOURCE_WINDOW_OPTIONS; - $alloptions = $RESOURCE_WINDOW_OPTIONS; - - if ($resource->windowpopup) { - $optionlist = array(); - foreach ($alloptions as $option) { - $optionlist[] = $option."=".$resource->$option; - unset($resource->$option); - } - $resource->popup = implode(',', $optionlist); - unset($resource->windowpopup); - - } else { - $resource->popup = ''; - } - /// Load parameters to this->parameters - $this->parameters = $this->form2parameters($resource); - /// Save parameters into the alltext field - $resource->alltext = $this->parameters2alltext($this->parameters); - } - - /** Delete instance of IMS-CP resource - * - * Delete all the moddata files for the resource - * @param resource object - */ - function delete_instance($resource) { - - global $CFG; - - /// Delete moddata resource dir completely unless repository. - if (!$this->isrepository) { - $resource_dir = $CFG->dataroot.'/'.$resource->course.'/'.$CFG->moddata.'/resource/'.$resource->id; - if (file_exists($resource_dir)) { - if (!$status = fulldelete($resource_dir)) { - return false; - } - } - } - - return parent::delete_instance($resource); - } - - - /** - * Display the file resource - * - * Displays a file resource embedded, in a frame, or in a popup. - * Output depends on type of file resource. - * - * @param CFG global object - */ - function display() { - global $CFG, $THEME, $USER, $PAGE, $OUTPUT; - - require_once($CFG->libdir.'/filelib.php'); - - /// Set up generic stuff first, including checking for access - parent::display(); - - /// Set up some shorthand variables - $cm = $this->cm; - $course = $this->course; - $resource = $this->resource; - - /// Fetch parameters - $inpopup = optional_param('inpopup', 0, PARAM_BOOL); - $page = optional_param('page', 0, PARAM_INT); - $frameset= optional_param('frameset', '', PARAM_ALPHA); - - /// Init some variables - $errorcode = 0; - $buttontext = 0; - $querystring = ''; - $resourcetype = ''; - $mimetype = mimeinfo("type", $resource->reference); - $pagetitle = strip_tags($course->shortname.': '.format_string($resource->name)); - - /// Cache this per request - static $items; - - /// Check for errors - $errorcode = $this->check4errors($resource->reference, $course, $resource); - - /// If there are any error, show it instead of the resource page - if ($errorcode) { - if (!has_capability('moodle/course:activityvisibility', get_context_instance(CONTEXT_COURSE, $course->id))) { - /// Resource not available page - $errortext = get_string('resourcenotavailable','resource'); - } else { - /// Depending of the error, show different messages and pages - if ($errorcode ==1) { - $errortext = get_string('invalidfiletype','error', $resource->reference); - } else if ($errorcode == 2) { - $errortext = get_string('filenotfound','error', $resource->reference); - } else if ($errorcode == 3) { - $errortext = get_string('packagenotdeplyed','resource'); - } else if ($errorcode == 4) { - $errortext = get_string('packagechanged','resource'); - } else if ($errorcode == 5) { - $errortext = get_string('packagenotdeplyed','resource'); // no button though since from repository. - } - } - /// Display the error and exit - if ($inpopup) { - print_header($pagetitle, $course->fullname.' : '.$resource->name); - } else { - $navigation = build_navigation($this->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm)); - } - print_simple_box_start('center', '60%'); - echo '

    '.$errortext.'

    '; - /// If errors were 3 or 4 and isteacheredit(), show the deploy button - if (has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id)) && ($errorcode == 3 || $errorcode == 4)) { - $link = 'type/ims/deploy.php'; - $options['courseid'] = $course->id; - $options['cmid'] = $cm->id; - $options['file'] = $resource->reference; - $options['sesskey'] = sesskey(); - $options['inpopup'] = $inpopup; - if ($errorcode == 3) { - $label = get_string ('deploy', 'resource'); - } else if ($errorcode == 4) { - $label = get_string ('redeploy', 'resource'); - } - $method='post'; - /// Let's go with the button - echo '
    '; - print_single_button($link, $options, $label, $method); - echo '
    '; - } - print_simple_box_end(); - /// Close button if inpopup - if ($inpopup) { - echo $OUTPUT->close_window_button(); - } - - print_footer(); - exit; - } - - /// Load serialized IMS CP index to memory only once. - if (empty($items)) { - if (!$this->isrepository) { - $resourcedir = $CFG->dataroot.'/'.$course->id.'/'.$CFG->moddata.'/resource/'.$resource->id; - } - else { - $resourcedir = $CFG->repository . $resource->reference; - } - if (!$items = ims_load_serialized_file($resourcedir.'/moodle_inx.ser')) { - print_error('errorreadingfile', 'error', '', 'moodle_inx.ser'); - } - } - - /// Check whether this is supposed to be a popup, but was called directly - - if (empty($frameset) && $resource->popup && !$inpopup) { /// Make a page and a pop-up window - $navigation = build_navigation($this->navlinks, $cm); - - print_header($pagetitle, $course->fullname, $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm)); - - echo "\n'; - - if (trim(strip_tags($resource->intro))) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - - $link = "wwwroot/mod/resource/view.php?inpopup=true&id={$cm->id}\" target=\"resource{$resource->id}\" onclick=\"return openpopup('/mod/resource/view.php?inpopup=true&id={$cm->id}', 'resource{$resource->id}','{$resource->popup}');\">".format_string($resource->name,true).""; - - echo "

     

    "; - echo '

    '; - print_string('popupresource', 'resource'); - echo '
    '; - print_string('popupresourcelink', 'resource', $link); - echo "

    "; - - print_footer($course); - exit; - } - - - /// No frames or framesets anymore, except iframe. in print_ims, iframe filled. - /// needs callback to this file to display table of contents in the iframe so - /// $frameset = 'toc' leads to output of toc and blank or 'ims' produces the - /// iframe. - if (empty($frameset) || $frameset=='ims') { - - /// Conditional argument to pass to IMS JavaScript. Need to be global to retrieve it from our custom javascript! :-( - $jsarg = 'false'; - if (!empty($this->parameters->navigationmenu)) { - $jsarg = 'true'; - } - - if (!empty($THEME->customcorners)) { - $customcorners = 'true'; - } else { - $customcorners = 'false'; - } - $PAGE->requires->data_for_js('imsdata', Array('customcorners'=>$customcorners, 'jsarg'=>$jsarg)); - $PAGE->requires->js('mod/resource/type/ims/dummyapi.js')->in_head(); - $PAGE->requires->js('mod/resource/type/ims/resize.js')->in_head(); - $PAGE->requires->js('mod/resource/type/ims/ims.js')->in_head(); - - /// moodle header - if ($resource->popup) { - //print_header($pagetitle, $course->fullname.' : '.$resource->name); - print_header(); - } else { - $navigation = build_navigation($this->navlinks, $cm); - print_header($pagetitle, $course->fullname, $navigation, "", "", true, update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "parent")); - } - /// content - this produces everything else - $this->print_ims($cm, $course, $items, $resource, $page); - - print_footer('empty'); - - /// log it. - add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id); - exit; - } - - if ($frameset == 'toc') { - print_header(); - $this->print_toc($items, $resource, $page); - echo ''; - exit; - } - } - -/// Function print_ims prints nearly the whole page. Stupid name subject to change :-) - function print_ims($cm, $course, $items, $resource, $page) { - global $CFG; - - /// Set the correct contentframe id based on $this->parameters->navigationmenu - if (!empty($this->parameters->navigationmenu)) { - $contentframe = 'ims-contentframe'; - } else { - $contentframe = 'ims-contentframe-no-nav'; - } - - /// Calculate the file.php correct url - if (!$this->isrepository) { - require_once($CFG->libdir.'/filelib.php'); - $fileurl = get_file_url($course->id.'/'.$CFG->moddata.'/resource/'.$resource->id); - } - else { - $fileurl = $CFG->repositorywebroot . $resource->reference; - } - - - /// Calculate the view.php correct url - $viewurl = "view.php?id={$cm->id}&type={$resource->type}&frameset=toc&page="; - - - /// Decide what to show (full toc, partial toc or package file) - $fullurl = ''; - if (empty($page) && !empty($this->parameters->tableofcontents)) { - /// Full toc contents - $fullurl = $viewurl.$page; - } else { - if (empty($page)) { - /// If no page and no toc, set page 1 unless skipping submenus, in which case fast forward: - $page = 1; - if (!empty($this->parameters->skipsubmenus)) { - while (empty($items[$page]->href) && !empty($items[$page])) { - $page++; - } - } - } - if (empty($items[$page]->href)) { - /// The page hasn't href, then partial toc contents - $fullurl = $viewurl.$page; - } else { - /// The page has href, then its own file contents - /// but considering if it seems to be an external url or a internal one - if (strpos($items[$page]->href, '//') !== false) { - /// External URL - $fullurl = $items[$page]->href; - } else { - /// Internal URL, use file.php - $fullurl = $fileurl.'/'.$items[$page]->href; - } - } - } - - /// print navigation buttons if needed - if (!empty($this->parameters->navigationbuttons)) { - $this->print_nav($items, $resource, $page); - } - - echo '
    '; - /// adds side navigation bar if needed. must also adjust width of iframe to accomodate - if (!empty($this->parameters->navigationmenu)) { - echo "
    "; $this->print_navmenu($items, $resource, $page); echo "
    "; - } - - /// prints iframe filled with $fullurl - echo ""; //Content frame - echo '
    '; - } - -/// Prints TOC - function print_toc($items, $resource, $page) { - $table = new stdClass; - if (empty($page)) { - $table->head[] = ''.$resource->name.''; - } else { - $table->head[] = ''.$items[$page]->title.''; - } - $table->data[] = array(ims_generate_toc ($items, $resource, $page)); - $table->width = '60%'; - print_table($table); - } - -/// Prints side navigation menu. This is just the full TOC with no surround. - function print_navmenu($items, $resource, $page=0) { - echo ims_generate_toc ($items, $resource, 0, $page); - } - -/// Prints navigation bar at the top of the page. - function print_nav($items, $resource, $page) { - echo '
    '; - /// Prev button - echo ims_get_prev_nav_button ($items, $this, $page); - /// Up button - echo ims_get_up_nav_button ($items, $this, $page); - /// Next button - echo ims_get_next_nav_button ($items, $this, $page); - /// Main TOC button - echo ims_get_toc_nav_button ($items, $this, $page); - /// Footer - echo '
    '; - } - - - function setup_preprocessing(&$defaults){ - - if (!isset($defaults['popup'])) { - // use form defaults - - } else if (!empty($defaults['popup'])) { - $defaults['windowpopup'] = 1; - if (array_key_exists('popup', $defaults)) { - $rawoptions = explode(',', $defaults['popup']); - foreach ($rawoptions as $rawoption) { - $option = explode('=', trim($rawoption)); - $defaults[$option[0]] = $option[1]; - } - } - } else { - $defaults['windowpopup'] = 0; - } - //Converts the alltext to form fields - if (!empty($defaults['alltext'])) { - $parameters = $this->alltext2parameters($defaults['alltext']); - $defaults['param_tableofcontents'] = $parameters->tableofcontents; - $defaults['param_navigationbuttons'] = $parameters->navigationbuttons; - $defaults['param_skipsubmenus'] = $parameters->skipsubmenus; - $defaults['param_navigationmenu'] = $parameters->navigationmenu; - $defaults['param_navigationupbutton'] = $parameters->navigationupbutton; - } - } - - function setup_elements(&$mform) { - global $CFG, $RESOURCE_WINDOW_OPTIONS; - - $mform->addElement('choosecoursefileorimsrepo', 'reference', get_string('location')); - $mform->addRule('name', null, 'required', null, 'client'); - - $mform->addElement('header', 'displaysettings', get_string('display', 'resource')); - - $woptions = array(0 => get_string('pagewindow', 'resource'), 1 => get_string('newwindow', 'resource')); - $mform->addElement('select', 'windowpopup', get_string('display', 'resource'), $woptions); - $mform->setDefault('windowpopup', !empty($CFG->resource_popup)); - - foreach ($RESOURCE_WINDOW_OPTIONS as $option) { - if ($option == 'height' or $option == 'width') { - $mform->addElement('text', $option, get_string('new'.$option, 'resource'), array('size'=>'4')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } else { - $mform->addElement('checkbox', $option, get_string('new'.$option, 'resource')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } - $mform->setAdvanced($option); - } - - $mform->addElement('header', 'parameters', get_string('parameters', 'resource')); - - $mform->addElement('selectyesno', 'param_navigationmenu', get_string('navigationmenu', 'resource')); - $mform->setDefault('param_navigationmenu', 1); - - $mform->addElement('selectyesno', 'param_tableofcontents', get_string('tableofcontents', 'resource')); - $mform->disabledIf('param_tableofcontents', 'param_navigationmenu', 'eq', 1); - $mform->setDefault('param_tableofcontents', 0); - - $mform->addElement('selectyesno', 'param_navigationbuttons', get_string('navigationbuttons', 'resource')); - $mform->setDefault('param_navigationbuttons', 0); - - $mform->addElement('selectyesno', 'param_skipsubmenus', get_string('skipsubmenus', 'resource')); - $mform->setDefault('param_skipsubmenus', 1); - $mform->disabledIf('param_skipsubmenus', 'param_navigationmenu', 'eq', 1); - - $mform->addElement('selectyesno', 'param_navigationupbutton', get_string('navigationup', 'resource')); - $mform->setDefault('param_navigationupbutton', 1); - $mform->disabledIf('param_navigationupbutton', 'param_navigationmenu', 'eq', 1); - - } - -} //End class - -/// -/// General purpose functions -/// - /*** This function will serialize the variable passed and send it - * to filesystem - */ - function ims_save_serialized_file($destination, $var) { - $status = false; - if ($ser = serialize($var)) { - $status = ims_var2file($destination, $ser); - } - return $status; - } - - /*** This function will unserialize the variable stored - * in filesystem - */ - function ims_load_serialized_file($file) { - $status = false; - if ($ser = ims_file2var($file)) { - $status = unserialize($ser); - } - return $status; - } - - /*** This function will load all the contents of one file to one variable - * Not suitable for BIG files - */ - function ims_file2var ($file) { - $status = true; - $var = ''; - $fp = fopen($file, 'r') - or $status = false; - if ($status) { - while ($data = fread($fp, 4096)) { - $var = $var.$data; - } - fclose($fp); - } - if (!$status) { - $var = false; - } - return $var; - } - - /*** This file will write the contents of one variable to a file - * Not suitable for BIG files - */ - function ims_var2file ($file, $var) { - $status = false; - if ($out = fopen($file,"w")) { - $status = fwrite($out, $var); - fclose($out); - } - return $status; - } - - /*** This function will generate the TOC file for the package - * from an specified parent to be used in the view of the IMS - * Now hilights 'selected page' also. - */ - function ims_generate_toc($items, $resource, $page=0, $selected_page = -1) { - global $CFG; - - $contents = ''; - - /// Configure links behaviour - $fullurl = $CFG->wwwroot.'/mod/resource/view.php?r='.$resource->id.'&frameset=ims&page='; - - /// Iterate over items to build the menu - $currlevel = 0; - $currorder = 0; - $endlevel = 0; - $openlielement = false; - foreach ($items as $item) { - if (!is_object($item)) { - continue; - } - /// Skip pages until we arrive to $page - if ($item->id < $page) { - continue; - } - /// Arrive to page, we store its level - if ($item->id == $page) { - $endlevel = $item->level; - continue; - } - /// We are after page and inside it (level > endlevel) - if ($item->id > $page && $item->level > $endlevel) { - /// Start Level - if ($item->level > $currlevel) { - $contents .= '
      '; - $openlielement = false; - } - /// End Level - if ($item->level < $currlevel) { - $contents .= ''; - $contents .= '
    '; - } - /// If we have some openlielement, just close it - if ($openlielement) { - $contents .= ''; - } - /// Add item - $contents .= '
  • '; - if (!empty($item->href)) { - if ($item->id == $selected_page) $contents .= '
    '; - $contents .= ''.$item->title.''; - if ($item->id == $selected_page) $contents .= '
    '; - } else { - $contents .= $item->title; - } - $currlevel = $item->level; - $openlielement = true; - continue; - } - /// We have reached endlevel, exit - if ($item->id > $page && $item->level <= $endlevel) { - break; - } - } - /// Close up to $endlevel - for ($i=$currlevel;$i>$endlevel;$i--) { - $contents .= '
  • '; - $contents .= ''; - } - - return $contents; - } - - /*** This function will return the correct html code needed - * to show the previous button in the nav frame - **/ - function ims_get_prev_nav_button ($items, $resource_obj, $page) { - $strprevious = get_string("previous", "resource"); - - $cm = $resource_obj->cm; - $resource = $resource_obj->resource; - - $contents = ''; - - $page--; - /// Skips any menu pages since these are redundant with sidemenu. - if (!empty($resource_obj->parameters->skipsubmenus)) { - while(empty($items[$page]->href) && $page >= 0) { - $page--; - } - } - - if ($page >= 1 ) { //0 and 1 pages haven't previous - $contents .= "id}&type={$resource->type}&page={$page}&frameset=ims\">$strprevious"; - } else { - $contents .= ''.$strprevious.''; - } - - return $contents; - } - - /*** This function will return the correct html code needed - * to show the next button in the nav frame - **/ - function ims_get_next_nav_button ($items, $resource_obj, $page) { - $strnext = get_string("next", "resource"); - - $cm = $resource_obj->cm; - $resource = $resource_obj->resource; - - $contents = ''; - - $page++; - /// Skips any menu pages since these are redundant with sidemenu. - if (!empty($resource_obj->parameters->skipsubmenus)) { - while(empty($items[$page]->href) && !empty($items[$page])) { - $page++; - } - } - - if (!empty($items[$page])) { //If the next page exists - $contents .= "id}&type={$resource->type}&page={$page}&frameset=ims\">$strnext"; - } else { - $contents .= ''.$strnext.''; - } - - - return $contents; - } - - /*** This function will return the correct html code needed - * to show the up button in the nav frame - **/ - function ims_get_up_nav_button ($items, $resource_obj, $page) { - $strup = get_string("upbutton", "resource"); - - $cm = $resource_obj->cm; - $resource = $resource_obj->resource; - - $contents = ''; - - if (!empty($resource_obj->parameters->navigationupbutton)) { - if ($page > 1 && $items[$page]->parent > 0) { //If the page has parent - $page = $items[$page]->parent; - $contents .= "id}&type={$resource->type}&page={$page}&frameset=ims\">$strup"; - } else { - $contents .= "$strup"; - } - } - return $contents; - } - - /*** This function will return the correct html code needed - * to show the toc button in the nav frame - **/ - function ims_get_toc_nav_button ($items, $resource_obj, $page) { - - $cm = $resource_obj->cm; - $resource = $resource_obj->resource; - - $strtoc = get_string('tableofcontentsabbrev', 'resource'); - - $contents = ''; - - if (!empty($resource_obj->parameters->tableofcontents)) { //The toc is enabled - $page = 0; - $contents .= "id}&type={$resource->type}&page={$page}&frameset=ims\">{$strtoc}"; - } - - return $contents; - } - -?> diff --git a/mod/resource/type/repository/hive/hp-footer-hive-powered.gif b/mod/resource/type/repository/hive/hp-footer-hive-powered.gif deleted file mode 100644 index 1a042fa928ece..0000000000000 Binary files a/mod/resource/type/repository/hive/hp-footer-hive-powered.gif and /dev/null differ diff --git a/mod/resource/type/repository/hive/makelink.php b/mod/resource/type/repository/hive/makelink.php deleted file mode 100644 index c8c3b22585bb7..0000000000000 --- a/mod/resource/type/repository/hive/makelink.php +++ /dev/null @@ -1,48 +0,0 @@ -hivehost) or empty($CFG->hiveport) or empty($CFG->hiveprotocol) or empty($CFG->hivepath)) { - print_header(); - notify('A Hive repository is not yet configured in Moodle. Please see Resource settings.'); - print_footer(); - die; - } - - print_header(); - - $aliasid = optional_param('aliasid', '', PARAM_RAW); - $latest = optional_param('lastes', '', PARAM_RAW); - $itemid = optional_param('itemid', '', PARAM_RAW); - $format = optional_param('format', '', PARAM_RAW); - $filename = optional_param('filename', '', PARAM_RAW); - $title = optional_param('title', '', PARAM_RAW); - - /// Generate the HIVE_REF parameter - $hive_ref = 'HIVE_REF=hii%3A'. $aliasid; - if ($latest != 'Y') { - $hive_ref = 'HIVE_REF=hdi%3A'. $itemid; - } - /// Generate the HIVE_RET parameter - $hive_ret = 'HIVE_RET=ORG'; - if ($format != 'orig') { - $hive_ret = 'HIVE_RET=CNV'; - } - - $reference = $hive_ref.'&'. $hive_ret .'&HIVE_REQ=2113'; - - $resource = $CFG->hiveprotocol .'://'. $CFG->hivehost .':'. $CFG->hiveport .''. $CFG->hivepath . '/'.$filename.'?'. $reference; - - -?> - - - - diff --git a/mod/resource/type/repository/hive/openhive.php b/mod/resource/type/repository/hive/openhive.php deleted file mode 100644 index 942d7a0236bd2..0000000000000 --- a/mod/resource/type/repository/hive/openhive.php +++ /dev/null @@ -1,71 +0,0 @@ -hivehost) or empty($CFG->hiveport) or empty($CFG->hiveprotocol) or empty($CFG->hivepath)) { - print_header(); - notify('A Hive repository is not yet configured in Moodle. Please see Resource settings.'); - print_footer(); - die; - } - - if (empty($SESSION->HIVE_SESSION)) { - print_header(); - notify('You do not have access to the Hive repository. Moodle signs you into Hive when you log in. This process may have failed.'); - echo $OUTPUT->close_window_button(); - print_footer(); - die; - } - -$query .= 'HISTORY='; -$query .= '&hiveLanguage=en_AU'; -$query .= '&PUBCATEGORY_LIST='; -$query .= '&CATEGORY_LIST='; -$query .= '&HIDE_LOGOUT=Y'; -$query .= '&mkurl='.$CFG->wwwroot.'/mod/resource/type/repository/hive/makelink.php'; -$query .= '&HIDE_CHANGEUSERDETAILS=Y'; -$query .= '&HIVE_RET=ORG'; -$query .= '&HIVE_PAGE=Lite%20Browse'; -$query .= '&HIVE_REQ=2113'; -$query .= '&HIVE_ERRCODE=0'; -$query .= '&mklms=Doodle'; -$query .= '&HIVE_PROD=0'; -$query .= '&HIVE_CURRENTBUREAUID='.$CFG->decsbureauid; -$query .= '&HIVE_REF=hin:hive@Hive%20Login%20HTML%20Template'; -$query .= '&HIVE_LITEMODE=liteBrowse'; -$query .= '&HIVE_SEREF='.$CFG->wwwroot.'/sso/hive/expired.php'; -$query .= '&HIVE_SESSION='.$SESSION->HIVE_SESSION; - - redirect($CFG->hiveprotocol .'://'. $CFG->hivehost .':'. $CFG->hiveport .''. $CFG->hivepath .'?'.$query); -/***********8 - notify('Opening HarvestRoad Hive. Please wait. Contacting '. $CFG->hivehost ); - - echo '
    '; - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo '
    '; - echo ''; - - print_footer(); -*************/ -?> diff --git a/mod/resource/type/repository/hive/openlitebrowse.php b/mod/resource/type/repository/hive/openlitebrowse.php deleted file mode 100644 index 35fd13b8ff3a1..0000000000000 --- a/mod/resource/type/repository/hive/openlitebrowse.php +++ /dev/null @@ -1,69 +0,0 @@ -hivehost) or empty($CFG->hiveport) or empty($CFG->hiveprotocol) or empty($CFG->hivepath)) { - print_header(); - notify('A Hive repository is not yet configured in Moodle. Please see Resource settings.'); - print_footer(); - die; - } - - if (empty($SESSION->HIVE_SESSION)) { - print_header(); - notify('You do not have access to the Hive repository. Moodle signs you into Hive when you log in. This process may have failed.'); - echo $OUTPUT->close_window_button(); - print_footer(); - die; - } - -// MW Redirect to the Hive page. No need for a self-posting form as there is no sensitive data. -$query =''; -$query .= 'HISTORY='; -$query .= '&hiveLanguage=en_AU'; -$query .= '&PUBCATEGORY_LIST='; -$query .= '&CATEGORY_LIST='; -$query .= '&HIDE_LOGOUT=Y'; -$query .= '&mkurl='.$CFG->wwwroot.'/mod/resource/type/repository/hive/makelink.php'; -$query .= '&HIDE_CHANGEUSERDETAILS=Y'; -$query .= '&HIVE_RET=ORG'; -$query .= '&HIVE_REQ=2113'; -$query .= '&HIVE_ERRCODE=0'; -$query .= '&mklms=Moodle'; -$query .= '&HIVE_PROD=0'; -$query .= '&HIVE_REF=hin:hive@Hive%20Login%20HTML%20Template'; -$query .= '&HIVE_LITEMODE=liteBrowse'; -$query .= '&HIVE_ITEMTYPE='.$CFG->decsitemtypeid; -$query .= '&HIVE_CURRENTBUREAUID='.$CFG->decsbureauid; -$query .= '&HIVE_SEREF='.$CFG->wwwroot.'/sso/hive/expired.php'; -$query .= '&HIVE_SESSION='.$SESSION->HIVE_SESSION; -//$query = ''; - - -//================================================ - $stylesheets = ''; - foreach ($CFG->stylesheets as $stylesheet) { - if(empty($stylesheets)) { - $stylesheets = $stylesheet; - } else { - $stylesheets .= '%26'.$stylesheet; - } - } - -$query = ''; -// $query .= 'HIVE_REF=hin:hive@Demo%20LMS%20Browse'; - $query .= 'HIVE_REF=hin:hive@LMS%20Browse'; - $query .= '&HIVE_RET=ORG'; - $query .= '&HIVE_REQ=2113'; - $query .= '&HIVE_PROD=0'; - $query .= '&HIVE_CURRENTBUREAUID='.$CFG->decsbureauid; - $query .= '&HIVE_BUREAU='.$CFG->decsbureauid; - $query .= '&HIVE_ITEMTYPE='.$CFG->decsitemtypeid; - $query .= '&mkurl='.$CFG->wwwroot.'/mod/resource/type/repository/hive/makelink.php'; - $query .= '&mklms=Moodle'; - $query .= '&HIVE_SEREF='.$CFG->wwwroot.'/sso/hive/expired.php'; - $query .= '&HIVE_SESSION='.$SESSION->HIVE_SESSION; - $query .= '&mklmsstyle='.$stylesheets; - - redirect($CFG->hiveprotocol .'://'. $CFG->hivehost .':'. $CFG->hiveport .''. $CFG->hivepath .'?'.$query); -?> diff --git a/mod/resource/type/repository/hive/openlitepublish.php b/mod/resource/type/repository/hive/openlitepublish.php deleted file mode 100644 index c905341194c51..0000000000000 --- a/mod/resource/type/repository/hive/openlitepublish.php +++ /dev/null @@ -1,45 +0,0 @@ -hivehost) or empty($CFG->hiveport) or empty($CFG->hiveprotocol) or empty($CFG->hivepath)) { - print_header(); - notify('A Hive repository is not yet configured in Moodle. Please see Resource settings.'); - print_footer(); - die; - } - - if (empty($SESSION->HIVE_SESSION)) { - print_header(); - notify('You do not have access to the Hive repository. Moodle signs you into Hive when you log in. This process may have failed.'); - echo $OUTPUT->close_window_button(); - print_footer(); - die; - } - -//================================================ - $stylesheets = ''; - foreach ($CFG->stylesheets as $stylesheet) { - if(empty($stylesheets)) { - $stylesheets = $stylesheet; - } else { - $stylesheets .= '%26'.$stylesheet; - } - } - -$query = ''; -$query .= 'HIVE_REF=hin:hive@LMS%20Publish'; -$query .= '&HIVE_RET=ORG'; -$query .= '&HIVE_REQ=2113'; -$query .= '&HIVE_PROD=0'; -$query .= '&HIVE_CURRENTBUREAUID='.$CFG->decsbureauid; -$query .= '&HIVE_BUREAU='.$CFG->decsbureauid; -$query .= '&HIVE_ITEMTYPE='.$CFG->decsitemtypeid; -$query .= '&mkurl='.$CFG->wwwroot.'/mod/resource/type/repository/hive/makelink.php'; -$query .= '&mklms=Moodle'; -$query .= '&HIVE_SEREF='.$CFG->wwwroot.'/sso/hive/expired.php'; -$query .= '&HIVE_SESSION='.$SESSION->HIVE_SESSION; -$query .= '&mklmsstyle='.$stylesheets; - -redirect($CFG->hiveprotocol .'://'. $CFG->hivehost .':'. $CFG->hiveport .''. $CFG->hivepath .'?'.$query); -?> diff --git a/mod/resource/type/repository/hive/openlitesearch.php b/mod/resource/type/repository/hive/openlitesearch.php deleted file mode 100644 index f35f86330232e..0000000000000 --- a/mod/resource/type/repository/hive/openlitesearch.php +++ /dev/null @@ -1,47 +0,0 @@ -hivehost) or empty($CFG->hiveport) or empty($CFG->hiveprotocol) or empty($CFG->hivepath)) { - print_header(); - notify('A Hive repository is not yet configured in Moodle. Please see Resource settings.'); - print_footer(); - die; - } - - if (empty($SESSION->HIVE_SESSION)) { - print_header(); - notify('You do not have access to the Hive repository. Moodle signs you into Hive when you log in. This process may have failed.'); - echo $OUTPUT->close_window_button(); - print_footer(); - die; - } - -// MW Redirect to the Hive page. No need for a self-posting form as there is no sensitive data. - -///===================================================== - $stylesheets = ''; - foreach ($CFG->stylesheets as $stylesheet) { - if(empty($stylesheets)) { - $stylesheets = $stylesheet; - } else { - $stylesheets .= '%26'.$stylesheet; - } - } - - $query = ''; - /// $query .= 'HIVE_REF=hin:hive@Demo%20LMS%20Browse'; - $query .= 'HIVE_REF=hin:hive@LMS%20Search'; - $query .= '&HIVE_RET=ORG'; - $query .= '&HIVE_REQ=2113'; - $query .= '&HIVE_PROD=0'; - $query .= '&HIVE_CURRENTBUREAUID='.$CFG->decsbureauid; - $query .= '&HIVE_BUREAU='.$CFG->decsbureauid; - $query .= '&HIVE_ITEMTYPE='.$CFG->decsitemtypeid; - $query .= '&mkurl='.$CFG->wwwroot.'/mod/resource/type/repository/hive/makelink.php'; - $query .= '&mklms=Moodle'; - $query .= '&HIVE_SEREF='.$CFG->wwwroot.'/sso/hive/expired.php'; - $query .= '&HIVE_SESSION='.$SESSION->HIVE_SESSION; - $query .= '&mklmsstyle='.$stylesheets; - redirect($CFG->hiveprotocol .'://'. $CFG->hivehost .':'. $CFG->hiveport .''. $CFG->hivepath .'?'.$query); -?> diff --git a/mod/resource/type/repository/resource.class.php b/mod/resource/type/repository/resource.class.php deleted file mode 100644 index a115ec5b5f9fd..0000000000000 --- a/mod/resource/type/repository/resource.class.php +++ /dev/null @@ -1,620 +0,0 @@ -id)) { // No need to set up parameters - $this->parameters = array(); - return; - } - - $site = get_site(); - - $this->parameters = array( - 'label3' => array('langstr' => get_string('course'), - 'value' => 'optgroup'), - - 'courseid' => array('langstr' => 'id', - 'value' => $this->course->id), - 'coursefullname' => array('langstr' => get_string('fullnamecourse'), - 'value' => $this->course->fullname), - 'courseshortname' => array('langstr' => get_string('shortnamecourse'), - 'value' => $this->course->shortname), - 'courseidnumber' => array('langstr' => get_string('idnumbercourse'), - 'value' => $this->course->idnumber), - 'coursesummary' => array('langstr' => get_string('summary'), - 'value' => $this->course->summary), - 'courseformat' => array('langstr' => get_string('format'), - 'value' => $this->course->format), - - 'label4' => array('langstr' => "", - 'value' =>'/optgroup'), - 'label5' => array('langstr' => get_string('miscellaneous'), - 'value' => 'optgroup'), - - 'lang' => array('langstr' => get_string('preferredlanguage'), - 'value' => current_language()), - 'sitename' => array('langstr' => get_string('fullsitename'), - 'value' => format_string($site->fullname)), - 'serverurl' => array('langstr' => get_string('serverurl', 'resource', $CFG), - 'value' => $CFG->wwwroot), - 'currenttime' => array('langstr' => get_string('time'), - 'value' => time()), - 'encryptedcode' => array('langstr' => get_string('encryptedcode'), - 'value' => $this->set_encrypted_parameter()), - - 'label6' => array('langstr' => "", - 'value' =>'/optgroup'), - ); - - if (!empty($USER->id)) { - - $userparameters = array( - - 'label1' => array('langstr' => get_string('user'), - 'value' => 'optgroup'), - - 'userid' => array('langstr' => 'id', - 'value' => $USER->id), - 'userusername' => array('langstr' => get_string('username'), - 'value' => $USER->username), - 'useridnumber' => array('langstr' => get_string('idnumber'), - 'value' => $USER->idnumber), - 'userfirstname' => array('langstr' => get_string('firstname'), - 'value' => $USER->firstname), - 'userlastname' => array('langstr' => get_string('lastname'), - 'value' => $USER->lastname), - 'userfullname' => array('langstr' => get_string('fullnameuser'), - 'value' => fullname($USER)), - 'useremail' => array('langstr' => get_string('email'), - 'value' => $USER->email), - 'usericq' => array('langstr' => get_string('icqnumber'), - 'value' => $USER->icq), - 'userphone1' => array('langstr' => get_string('phone').' 1', - 'value' => $USER->phone1), - 'userphone2' => array('langstr' => get_string('phone2').' 2', - 'value' => $USER->phone2), - 'userinstitution' => array('langstr' => get_string('institution'), - 'value' => $USER->institution), - 'userdepartment' => array('langstr' => get_string('department'), - 'value' => $USER->department), - 'useraddress' => array('langstr' => get_string('address'), - 'value' => $USER->address), - 'usercity' => array('langstr' => get_string('city'), - 'value' => $USER->city), - 'usertimezone' => array('langstr' => get_string('timezone'), - 'value' => get_user_timezone_offset()), - 'userurl' => array('langstr' => get_string('webpage'), - 'value' => $USER->url), - 'label2' => array('langstr' => "", - 'value' =>'/optgroup'), - ); - - $this->parameters = $userparameters + $this->parameters; - } -} - - -function add_instance($resource) { - $this->_postprocess($resource); - return parent::add_instance($resource); -} - - -function update_instance($resource) { - $this->_postprocess($resource); -/* echo ''; - var_dump($_POST); - var_dump($resource);die;*/ - return parent::update_instance($resource); -} - -function _postprocess(&$resource) { - global $RESOURCE_WINDOW_OPTIONS; - $alloptions = $RESOURCE_WINDOW_OPTIONS; - - if ($resource->windowpopup) { - $optionlist = array(); - foreach ($alloptions as $option) { - $optionlist[] = $option."=".$resource->$option; - unset($resource->$option); - } - $resource->popup = implode(',', $optionlist); - unset($resource->windowpopup); - $resource->options = ''; - - } else { - if (empty($resource->framepage)) { - $resource->options = ''; - } else { - $resource->options = 'frame'; - } - unset($resource->framepage); - $resource->popup = ''; - } - - $optionlist = array(); - for ($i = 0; $i < $this->maxparameters; $i++) { - $parametername = "parameter$i"; - $parsename = "parse$i"; - if (!empty($resource->$parsename) and $resource->$parametername != "-") { - $optionlist[] = $resource->$parametername."=".$resource->$parsename; - } - unset($resource->$parsename); - unset($resource->$parametername); - } - - $resource->alltext = implode(',', $optionlist); -} - - -/** -* Display the repository resource -* -* Displays a repository resource embedded, in a frame, or in a popup. -* Output depends on type of file resource. -* -* @param CFG global object -*/ -function display() { - global $CFG, $THEME, $SESSION, $OUTPUT; - -/// Set up generic stuff first, including checking for access - parent::display(); - -/// Set up some shorthand variables - $cm = $this->cm; - $course = $this->course; - $resource = $this->resource; - - - $this->set_parameters(); // set the parameters array - -/////////////////////////////////////////////// - - /// Possible display modes are: - /// File displayed in a frame in a normal window - /// File displayed embedded in a normal page - /// File displayed in a popup window - /// File displayed emebedded in a popup window - - - /// First, find out what sort of file we are dealing with. - require_once($CFG->libdir.'/filelib.php'); - - $querystring = ''; - $resourcetype = ''; - $embedded = false; - $mimetype = mimeinfo("type", $resource->reference); - $pagetitle = strip_tags($course->shortname.': '.format_string($resource->name)); - - if ($resource->options != "frame") { - if (in_array($mimetype, array('image/gif','image/jpeg','image/png'))) { // It's an image - $resourcetype = "image"; - $embedded = true; - - } else if ($mimetype == "audio/mp3") { // It's an MP3 audio file - $resourcetype = "mp3"; - $embedded = true; - - } else if (substr($mimetype, 0, 10) == "video/x-ms") { // It's a Media Player file - $resourcetype = "mediaplayer"; - $embedded = true; - - } else if ($mimetype == "video/quicktime") { // It's a Quicktime file - $resourcetype = "quicktime"; - $embedded = true; - - } else if ($mimetype == "text/html") { // It's a web page - $resourcetype = "html"; - } - } - $navigation = build_navigation($this->navlinks, $cm); - -/// Form the parse string - if (!empty($resource->alltext)) { - $querys = array(); - $parray = explode(',', $resource->alltext); - foreach ($parray as $fieldstring) { - $field = explode('=', $fieldstring); - $querys[] = urlencode($field[1]).'='.urlencode($this->parameters[$field[0]]['value']); - } - $querystring = implode('&amp;', $querys); - } - - - /// Set up some variables - - $inpopup = optional_param('inpopup', 0, PARAM_BOOL); - - $fullurl = $resource->reference. '&amp;HIVE_SESSION='.$SESSION->HIVE_SESSION; - if (!empty($querystring)) { - $urlpieces = parse_url($resource->reference); - if (empty($urlpieces['query'])) { - $fullurl .= '?'.$querystring; - } else { - $fullurl .= '&amp;'.$querystring; - } - } - - /// MW check that the HIVE_SESSION is there - if (empty($SESSION->HIVE_SESSION)) { - if ($inpopup) { - print_header($pagetitle, $course->fullname); - } else { - print_header($pagetitle, $course->fullname, $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm)); - } - notify('You do not have access to HarvestRoad Hive. This resource is unavailable.'); - if ($inpopup) { - echo $OUTPUT->close_window_button(); - } - print_footer('none'); - die; - } - /// MW END - - - /// Print a notice and redirect if we are trying to access a file on a local file system - /// and the config setting has been disabled - if (!$CFG->resource_allowlocalfiles and (strpos($resource->reference, RESOURCE_LOCALPATH) === 0)) { - if ($inpopup) { - print_header($pagetitle, $course->fullname); - } else { - print_header($pagetitle, $course->fullname, $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm)); - } - notify(get_string('notallowedlocalfileaccess', 'resource', '')); - if ($inpopup) { - echo $OUTPUT->close_window_button(); - } - print_footer('none'); - die; - } - - - /// Check whether this is supposed to be a popup, but was called directly - - if ($resource->popup and !$inpopup) { /// Make a page and a pop-up window - print_header($pagetitle, $course->fullname, $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm)); - - - echo "\n<script type=\"text/javascript\">"; - echo "\n<!--\n"; - echo "openpopup('/mod/resource/view.php?inpopup=true&id={$cm->id}','resource{$resource->id}','{$resource->popup}');\n"; - echo "\n-->\n"; - echo '</script>'; - - if (trim(strip_tags($resource->intro))) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - - $link = "<a href=\"$CFG->wwwroot/mod/resource/view.php?inpopup=true&amp;id={$cm->id}\" target=\"resource{$resource->id}\" onclick=\"return openpopup('/mod/resource/view.php?inpopup=true&amp;id={$cm->id}', 'resource{$resource->id}','{$resource->popup}');\">".format_string($resource->name,true)."</a>"; - - echo "<p>&nbsp;</p>"; - echo '<p align="center">'; - print_string('popupresource', 'resource'); - echo '<br />'; - print_string('popupresourcelink', 'resource', $link); - echo "</p>"; - - print_footer($course); - exit; - } - - - /// Now check whether we need to display a frameset - - $frameset = optional_param('frameset', '', PARAM_ALPHA); - if (empty($frameset) and !$embedded and !$inpopup and $resource->options == "frame" and empty($USER->screenreader)) { - echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Frameset//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd\">\n"; - echo "<html dir=\"ltr\">\n"; - echo '<head>'; - echo '<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />'; - echo "<title>" . format_string($course->shortname) . ": ".strip_tags(format_string($resource->name,true))."</title></head>\n"; - echo "<frameset rows=\"$CFG->resource_framesize,*\">"; - echo "<frame src=\"view.php?id={$cm->id}&amp;type={$resource->type}&amp;frameset=top\" title=\"".get_string('modulename','resource')."\"/>"; - if (!empty($localpath)) { // Show it like this so we interpose some HTML - echo "<frame src=\"view.php?id={$cm->id}&amp;type={$resource->type}&amp;inpopup=true\" title=\"".get_string('modulename','resource')."\"/>"; - } else { - echo "<frame src=\"$fullurl\" title=\"".get_string('modulename','resource')."\"/>"; - } - echo "</frameset>"; - echo "</html>"; - exit; - } - - - /// We can only get here once per resource, so add an entry to the log - - add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id); - - - /// If we are in a frameset, just print the top of it - - if (!empty($frameset) and $frameset == "top") { - print_header($pagetitle, $course->fullname, $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "parent")); - - echo '<div class="summary">'.format_module_intro('resource', $resource, $cm->id).'</div>'; - if (!empty($localpath)) { // Show some help - echo '<div class="mdl-right helplink">'; - link_to_popup_window ('/mod/resource/type/file/localpath.php', get_string('localfile', 'resource'), get_string('localfilehelp','resource'), 400, 500, get_string('localfilehelp', 'resource')); - echo '</div>'; - } - echo '</body></html>'; - exit; - } - - - /// Display the actual resource - - if ($embedded) { // Display resource embedded in page - $strdirectlink = get_string("directlink", "resource"); - - if ($inpopup) { - print_header($pagetitle); - } else { - print_header($pagetitle, $course->fullname, $navigation, "", "", true, - update_module_button($cm->id, $course->id, $this->strresource), navmenu($course, $cm, "self")); - - } - - if ($resourcetype == "image") { - echo "<center><p>"; - echo "<img title=\"".strip_tags(format_string($resource->name,true))."\" class=\"resourceimage\" src=\"$fullurl\" alt=\"\" />"; - echo "</p></center>"; - - } else if ($resourcetype == "mp3") { - if (!empty($THEME->resource_mp3player_colors)) { - $c = $THEME->resource_mp3player_colors; // You can set this up in your theme/xxx/config.php - } else { - $c = 'bgColour=000000&btnColour=ffffff&btnBorderColour=cccccc&iconColour=000000&'. - 'iconOverColour=00cc00&trackColour=cccccc&handleColour=ffffff&loaderColour=ffffff&'. - 'font=Arial&fontColour=3333FF&buffer=10&waitForPlay=no&autoPlay=yes'; - } - $c .= '&volText='.get_string('vol', 'resource').'&panText='.get_string('pan','resource'); - $c = htmlentities($c); - echo '<div class="mp3player" align="center">'; - echo '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'; - echo ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" '; - echo ' width="600" height="70" id="mp3player" align="">'; - echo '<param name="movie" value="'.$CFG->wwwroot.'/lib/mp3player/mp3player.swf?src='.$fullurl.'">'; - echo '<param name="quality" value="high">'; - echo '<param name="bgcolor" value="#333333">'; - echo '<param name="flashvars" value="'.$c.'&amp;" />'; - echo '<embed src="'.$CFG->wwwroot.'/lib/mp3player/mp3player.swf?src='.$fullurl.'" '; - echo ' quality="high" bgcolor="#333333" width="600" height="70" name="mp3player" '; - echo ' type="application/x-shockwave-flash" '; - echo ' flashvars="'.$c.'&amp;" '; - echo ' pluginspage="http://www.macromedia.com/go/getflashplayer">'; - echo '</embed>'; - echo '</object>'; - echo '</div>'; - - - } else if ($resourcetype == "mediaplayer") { - echo "<center><p>"; - echo '<object classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95"'; - echo ' codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=5,1,52,701" '; - echo ' standby="Loading Microsoft� Windows� Media Player components..." '; - echo ' id="msplayer" align="" type="application/x-oleobject">'; - echo "<param name=\"Filename\" value=\"$fullurl\">"; - echo '<param name="ShowControls" value="true" />'; - echo '<param name="AutoRewind" value="true" />'; - echo '<param name="AutoStart" value="true" />'; - echo '<param name="Autosize" value="true" />'; - echo '<param name="EnableContextMenu" value="true" />'; - echo '<param name="TransparentAtStart" value="false" />'; - echo '<param name="AnimationAtStart" value="false" />'; - echo '<param name="ShowGotoBar" value="false" />'; - echo '<param name="EnableFullScreenControls" value="true" />'; - echo "\n<embed src=\"$fullurl\" name=\"msplayer\" type=\"$mimetype\" "; - echo ' ShowControls="1" AutoRewind="1" AutoStart="1" Autosize="0" EnableContextMenu="1"'; - echo ' TransparentAtStart="0" AnimationAtStart="0" ShowGotoBar="0" EnableFullScreenControls="1"'; - echo ' pluginspage="http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/">'; - echo '</embed>'; - echo '</object>'; - echo "</p></center>"; - - } else if ($resourcetype == "quicktime") { - - echo "<center><p>"; - echo '<object classid="CLSID:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"'; - echo ' codebase="http://www.apple.com/qtactivex/qtplugin.cab" '; - echo ' height="450" width="600"'; - echo ' id="quicktime" align="" type="application/x-oleobject">'; - echo "<param name=\"src\" value=\"$fullurl\" />"; - echo '<param name="autoplay" value="true" />'; - echo '<param name="loop" value="true" />'; - echo '<param name="controller" value="true" />'; - echo '<param name="scale" value="aspect" />'; - echo "\n<embed src=\"$fullurl\" name=\"quicktime\" type=\"$mimetype\" "; - echo ' height="450" width="600" scale="aspect"'; - echo ' autoplay="true" controller="true" loop="true" '; - echo ' pluginspage="http://quicktime.apple.com/">'; - echo '</embed>'; - echo '</object>'; - echo "</p></center>"; - } - - if (trim($resource->intro)) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - - if ($inpopup) { - echo "<center><p>(<a href=\"$fullurl\">$strdirectlink</a>)</p></center>"; - } else { - $spacer = new html_image(); - $spacer->height = 20; - $spacer->width = 20; - echo $OUTPUT->spacer($spacer) . '<br />'; - print_footer($course); - } - - } else { // Display the resource on it's own - if (!empty($localpath)) { // Show a link to help work around browser security - echo '<div class="mdl-right helplink">'; - link_to_popup_window ('/mod/resource/type/file/localpath.php', get_string('localfile', 'resource'), get_string('localfilehelp','resource'), 400, 500, get_string('localfilehelp', 'resource')); - echo '</div>'; - echo "<center><p>(<a href=\"$fullurl\">$fullurl</a>)</p></center>"; - } - redirect($fullurl); - } - -} - - -//backwards compatible with existing resources -function set_encrypted_parameter() { - global $CFG; - - if (!empty($this->resource->reference) && file_exists($CFG->dirroot ."/mod/resource/type/file/externserverfile.php")) { - include $CFG->dirroot ."/mod/resource/type/file/externserverfile.php"; - if (function_exists('extern_server_file')) { - return extern_server_file($this->resource->reference); - } - } - return md5(getremoteaddr().$CFG->resource_secretphrase); -} - - -function setup_preprocessing(&$defaults){ - - if (!isset($defaults['popup'])) { - // use form defaults - - } else if (!empty($defaults['popup'])) { - $defaults['windowpopup'] = 1; - if (array_key_exists('popup', $defaults)) { - $rawoptions = explode(',', $defaults['popup']); - foreach ($rawoptions as $rawoption) { - $option = explode('=', trim($rawoption)); - $defaults[$option[0]] = $option[1]; - } - } - } else { - $defaults['windowpopup'] = 0; - if (array_key_exists('options', $defaults)) { - $defaults['framepage'] = ($defaults['options']=='frame'); - } - } - /// load up any stored parameters - if (!empty($defaults['alltext'])) { - $parray = explode(',', $defaults['alltext']); - $i=0; - foreach ($parray as $rawpar) { - list($param, $varname) = explode('=', $rawpar); - $defaults["parse$i"] = $varname; - $defaults["parameter$i"] = $param; - $i++; - } - } -} - -function setup_elements(&$mform) { - global $CFG, $RESOURCE_WINDOW_OPTIONS; - - $this->set_parameters(); // set the parameter array for the form - - $mform->addElement('text', 'reference', get_string('location'), array('size'=>'48')); - - $options = 'menubar,location,toolbar,scrollbars,resizable,width=750,height=500'; - - $button = $mform->addElement('button', 'browsebutton', 'Browse for content in hive...'); - $url = '/mod/resource/type/repository/hive/openlitebrowse.php'; - $buttonattributes = array('title'=>'Browse for content in hive', 'onclick'=>"return openpopup('$url', '".$button->getName()."', '$options', 0);"); - $button->updateAttributes($buttonattributes); - - $button = $mform->addElement('button', 'browsebutton', 'Search for content in Hive...'); - $url = '/mod/resource/type/repository/hive/openlitesearch.php'; - $buttonattributes = array('title'=>'Search for content in Hive', 'onclick'=>"return openpopup('$url', '".$button->getName()."', '$options', 0);"); - $button->updateAttributes($buttonattributes); - - $button = $mform->addElement('button', 'browsebutton', 'Add new item to Hive...'); - $url = '/mod/resource/type/repository/hive/openlitepublish.php'; - $buttonattributes = array('title'=>'Add new item to Hive', 'onclick'=>"return openpopup('$url', '".$button->getName()."', '$options', 0);"); - $button->updateAttributes($buttonattributes); - - $mform->addElement('header', 'displaysettings', get_string('display', 'resource')); - - $woptions = array(0 => get_string('pagewindow', 'resource'), 1 => get_string('newwindow', 'resource')); - $mform->addElement('select', 'windowpopup', get_string('display', 'resource'), $woptions); - $mform->setDefault('windowpopup', !empty($CFG->resource_popup)); - - $mform->addElement('checkbox', 'framepage', get_string('frameifpossible', 'resource')); - $mform->setDefault('framepage', 0); - $mform->disabledIf('framepage', 'windowpopup', 'eq', 1); - $mform->setAdvanced('framepage'); - - foreach ($RESOURCE_WINDOW_OPTIONS as $option) { - if ($option == 'height' or $option == 'width') { - $mform->addElement('text', $option, get_string('new'.$option, 'resource'), array('size'=>'4')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } else { - $mform->addElement('checkbox', $option, get_string('new'.$option, 'resource')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } - $mform->setAdvanced($option); - } - - $mform->addElement('header', 'parameters', get_string('parameters', 'resource')); - - $options = array(); - $options['-'] = get_string('chooseparameter', 'resource').'...'; - $optgroup = ''; - foreach ($this->parameters as $pname=>$param) { - if ($param['value']=='/optgroup') { - $optgroup = ''; - continue; - } - if ($param['value']=='optgroup') { - $optgroup = $param['langstr']; - continue; - } - $options[$pname] = $optgroup.' - '.$param['langstr']; - } - - for ($i = 0; $i < $this->maxparameters; $i++) { - $parametername = "parameter$i"; - $parsename = "parse$i"; - $group = array(); - $group[] =& $mform->createElement('text', $parsename, '', array('size'=>'12'));//TODO: accessiblity - $group[] =& $mform->createElement('select', $parametername, '', $options);//TODO: accessiblity - $mform->addGroup($group, 'pargroup'.$i, get_string('variablename', 'resource').'='.get_string('parameter', 'resource'), ' ', false); - $mform->setAdvanced('pargroup'.$i); - - $mform->setDefault($parametername, '-'); - } -} - -} - -?> diff --git a/mod/resource/type/text/resource.class.php b/mod/resource/type/text/resource.class.php deleted file mode 100644 index bfd6a8e88d29d..0000000000000 --- a/mod/resource/type/text/resource.class.php +++ /dev/null @@ -1,208 +0,0 @@ -<?php // $Id$ - -class resource_text extends resource_base { - - -function resource_text($cmid=0) { - parent::resource_base($cmid); -} - -function add_instance($resource) { - $this->_postprocess($resource); - return parent::add_instance($resource); -} - - -function update_instance($resource) { - $this->_postprocess($resource); - return parent::update_instance($resource); -} - -function _postprocess(&$resource) { - global $RESOURCE_WINDOW_OPTIONS; - $alloptions = $RESOURCE_WINDOW_OPTIONS; - - if ($resource->windowpopup) { - $optionlist = array(); - foreach ($alloptions as $option) { - $optionlist[] = $option."=".$resource->$option; - unset($resource->$option); - } - $resource->popup = implode(',', $optionlist); - unset($resource->windowpopup); - $resource->options = ''; - - } else { - if (empty($resource->blockdisplay)) { - $resource->options = ''; - } else { - $resource->options = 'showblocks'; - } - unset($resource->blockdisplay); - $resource->popup = ''; - } -} - -function display() { - global $CFG, $PAGE; - - $formatoptions = new object(); - $formatoptions->noclean = true; - - /// Are we displaying the course blocks? - if ($this->resource->options == 'showblocks') { - - parent::display_course_blocks_start(); - - if (trim(strip_tags($this->resource->alltext))) { - echo format_text($this->resource->alltext, FORMAT_MOODLE, $formatoptions, $this->course->id); - if (has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $this->cm->id))) { - resource_portfolio_caller::add_button($this); - } - } - - parent::display_course_blocks_end(); - - } else { - - /// Set up generic stuff first, including checking for access - parent::display(); - - /// Set up some shorthand variables - $cm = $this->cm; - $course = $this->course; - $resource = $this->resource; - - $pagetitle = strip_tags($course->shortname.': '.format_string($resource->name)); - $inpopup = optional_param('inpopup', '', PARAM_BOOL); - - if ($resource->popup) { - if ($inpopup) { /// Popup only - add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", - $resource->id, $cm->id); - print_header(); - print_simple_box(format_text($resource->alltext, $resource->reference, $formatoptions, $course->id), - "center", "", "", "20"); - print_footer($course); - if (has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $this->cm->id))) { - resource_portfolio_caller::add_button($this); - } - } else { /// Make a page and a pop-up window - $navigation = build_navigation($this->navlinks, $cm); - - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, update_module_button($cm->id, $course->id, $this->strresource), - navmenu($course, $cm)); - - $PAGE->requires->js_function_call('openpopup', Array("/mod/resource/view.php?inpopup=true&id={$cm->id}","resource{$resource->id}",$resource->popup)); - - if (trim(strip_tags($resource->intro))) { - print_simple_box(format_module_intro('resource', $resource, $cm->id), "center"); - } - - $link = "<a href=\"$CFG->wwwroot/mod/resource/view.php?inpopup=true&amp;id={$cm->id}\" onclick=\"this.target='resource{$resource->id}'; return openpopup('/mod/resource/view.php?inpopup=true&amp;id={$cm->id}', 'resource{$resource->id}','{$resource->popup}');\">".format_string($resource->name,true)."</a>"; - - echo '<div class="popupnotice">'; - print_string('popupresource', 'resource'); - echo '<br />'; - print_string('popupresourcelink', 'resource', $link); - echo '</div>'; - - print_footer($course); - } - } else { /// not a popup at all - - add_to_log($course->id, "resource", "view", "view.php?id={$cm->id}", $resource->id, $cm->id); - $navigation = build_navigation($this->navlinks, $cm); - - print_header($pagetitle, $course->fullname, $navigation, - "", "", true, update_module_button($cm->id, $course->id, $this->strresource), - navmenu($course, $cm)); - - print_simple_box(format_text($resource->alltext, $resource->reference, $formatoptions, $course->id), - "center", "", "", "20"); - - if (has_capability('mod/resource:exportresource', get_context_instance(CONTEXT_MODULE, $this->cm->id))) { - resource_portfolio_caller::add_button($this); - } - $strlastmodified = get_string("lastmodified"); - echo "<div class=\"modified\">$strlastmodified: ".userdate($resource->timemodified)."</div>"; - - print_footer($course); - } - - } - -} - - -function setup_preprocessing(&$defaults){ - - if (!isset($defaults['popup'])) { - // use form defaults - - } else if (!empty($defaults['popup'])) { - $defaults['windowpopup'] = 1; - if (array_key_exists('popup', $defaults)) { - $rawoptions = explode(',', $defaults['popup']); - foreach ($rawoptions as $rawoption) { - $option = explode('=', trim($rawoption)); - $defaults[$option[0]] = $option[1]; - } - } - } else { - $defaults['windowpopup'] = 0; - if (array_key_exists('options', $defaults)) { - $defaults['blockdisplay'] = ($defaults['options']=='showblocks'); - } - } -} - -function setup_elements(&$mform) { - global $CFG, $RESOURCE_WINDOW_OPTIONS; - - $mform->addElement('textarea', 'alltext', get_string('fulltext', 'resource'), array('cols'=>85, 'rows'=>30)); - $mform->setType('alltext', PARAM_RAW); - $mform->setHelpButton('alltext', array('reading', 'writing', 'richtext2'), false, 'editorhelpbutton'); - $mform->addRule('alltext', get_string('required'), 'required', null, 'client'); - - $mform->addElement('format', 'reference', get_string('format'), null, false); - $mform->setDefault('reference', FORMAT_PLAIN); - - $mform->addElement('header', 'displaysettings', get_string('display', 'resource')); - - $woptions = array(0 => get_string('pagewindow', 'resource'), 1 => get_string('newwindow', 'resource')); - $mform->addElement('select', 'windowpopup', get_string('display', 'resource'), $woptions); - $mform->setDefault('windowpopup', !empty($CFG->resource_popup)); - - $mform->addElement('checkbox', 'blockdisplay', get_string('showcourseblocks', 'resource')); - $mform->setDefault('blockdisplay', 0); - $mform->disabledIf('blockdisplay', 'windowpopup', 'eq', 1); - $mform->setAdvanced('blockdisplay'); - - foreach ($RESOURCE_WINDOW_OPTIONS as $option) { - if ($option == 'height' or $option == 'width') { - $mform->addElement('text', $option, get_string('new'.$option, 'resource'), array('size'=>'4')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } else { - $mform->addElement('checkbox', $option, get_string('new'.$option, 'resource')); - $mform->setDefault($option, $CFG->{'resource_popup'.$option}); - $mform->disabledIf($option, 'windowpopup', 'eq', 0); - } - $mform->setAdvanced($option); - } -} - - -function portfolio_prepare_package($exporter) { - return parent::portfolio_prepare_package_online($exporter, true); -} - -function portfolio_get_sha1() { - return parent::portfolio_get_sha1_online(true); -} - -} - -?> diff --git a/mod/resource/version.php b/mod/resource/version.php index dfebaf1e04f09..5526ee6e8f222 100644 --- a/mod/resource/version.php +++ b/mod/resource/version.php @@ -1,12 +1,29 @@ -<?php // $Id$ +<?php -//////////////////////////////////////////////////////////////////////////////// -// Code fragment to define the module version etc. -// This fragment is called by /admin/index.php -//////////////////////////////////////////////////////////////////////////////// +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. -$module->version = 2009042001; -$module->requires = 2009041700; // Requires this Moodle version +/** + * Resource module version information + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +$module->version = 2009080500; +$module->requires = 2009073101; // Requires this Moodle version $module->cron = 0; -?> diff --git a/mod/resource/view.php b/mod/resource/view.php index 1cb3f80d5a192..74e1143158d7e 100644 --- a/mod/resource/view.php +++ b/mod/resource/view.php @@ -1,47 +1,88 @@ -<?php // $Id$ - - require_once("../../config.php"); - require_once("lib.php"); - require_once($CFG->libdir . '/completionlib.php'); - - $id = optional_param('id', 0, PARAM_INT); // Course Module ID - $r = optional_param('r', 0, PARAM_INT); // Resource - - if ($r) { // Two ways to specify the resource - if (! $resource = $DB->get_record('resource', array('id'=>$r))) { - print_error('invalidid', 'resource'); - } - - if (! $cm = get_coursemodule_from_instance('resource', $resource->id, $resource->course)) { - print_error('invalidcoursemodule'); - } - - } else if ($id) { - if (! $cm = get_coursemodule_from_id('resource', $id)) { - print_error('invalidcoursemodule'); - } - - if (! $resource = $DB->get_record('resource', array('id'=>$cm->instance))) { - print_error('invalidid', 'resource'); - } - } else { +<?php + +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>. + +/** + * Resource module version information + * + * @package mod-resource + * @copyright 2009 Petr Skoda (http://skodak.org) + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +require('../../config.php'); +require_once($CFG->dirroot.'/mod/resource/locallib.php'); + +$id = optional_param('id', 0, PARAM_INT); // Course Module ID +$r = optional_param('r', 0, PARAM_INT); // Resource instance ID +$redirect = optional_param('redirect', 0, PARAM_BOOL); + +if ($r) { + if (!$resource = $DB->get_record('resource', array('id'=>$r))) { + resource_redirect_if_migrated($r, 0); print_error('invalidaccessparameter'); } + $cm = get_coursemodule_from_instance('resource', $resource->id, $resource->course, false, MUST_EXIST); - if (! $course = $DB->get_record('course', array('id'=>$cm->course))) { - print_error('invalidcourseid'); +} else { + if (!$cm = get_coursemodule_from_id('resource', $id)) { + resource_redirect_if_migrated(0, $id); + print_error('invalidcoursemodule'); } + $resource = $DB->get_record('resource', array('id'=>$cm->instance), '*', MUST_EXIST); +} + +$course = $DB->get_record('course', array('id'=>$cm->course), '*', MUST_EXIST); + +require_course_login($course, true, $cm); +$context = get_context_instance(CONTEXT_MODULE, $cm->id); + +add_to_log($course->id, 'resource', 'view', 'view.php?id='.$cm->id, $resource->id, $cm->id); + +$PAGE->set_url('mod/resource/view.php', array('id' => $cm->id)); + +if ($resource->tobemigrated) { + resource_print_tobemigrated($resource, $cm, $course); + die; +} - require_course_login($course, true, $cm); +$fs = get_file_storage(); +$pathnamehash = sha1($context->id.'resource_content0'.$resource->mainfile); +if (!$file = $fs->get_file_by_hash($pathnamehash)) { + resource_print_filenotfound($resource, $cm, $course); + die; +} - require ($CFG->dirroot.'/mod/resource/type/'.$resource->type.'/resource.class.php'); - $resourceclass = 'resource_'.$resource->type; - $resourceinstance = new $resourceclass($cm->id); +if ($redirect) { + // coming from course page or url index page + // this redirect trick solves caching problems when tracking views ;-) + $path = '/'.$context->id.'/resource_content/'.$resource->revision.$file->get_filepath().$file->get_filename(); + $fullurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', $path, false); + redirect($fullurl); +} - // Mark activity viewed before we display it because some resource types - // do not return from display() - $completion=new completion_info($course); - $completion->set_module_viewed($cm); +switch (resource_get_final_display_type($resource)) { + case RESOURCELIB_DISPLAY_EMBED: + resource_display_embed($resource, $cm, $course, $file); + break; + case RESOURCELIB_DISPLAY_FRAME: + resource_display_frame($resource, $cm, $course, $file); + break; + default: + resource_print_workaround($resource, $cm, $course, $file); + break; +} - $resourceinstance->display(); -?> diff --git a/theme/standard/styles_color.css b/theme/standard/styles_color.css index 1d93c2d7f4f24..bd7eec9c05bef 100644 --- a/theme/standard/styles_color.css +++ b/theme/standard/styles_color.css @@ -936,6 +936,14 @@ table.message_search_results td { border-color: #DDDDDD; } +/*** + *** Modules: general + ***/ + +.mod_introbox { + border-color:#DDDDDD; +} + /*** *** Modules: Chat ***/ @@ -1301,40 +1309,6 @@ css id's of question bank*/ *** Modules: Resource ***/ -.ims-nav-dimmed { - color: #AAAAAA; - text-decoration: none; -} - -.ims-nav-button a:link, -.ims-nav-button a:visited, -.ims-nav-button a:hover { - color: #000; - text-decoration: none; -} - -.ims-nav-dimmed, -.ims-nav-button a:link, -.ims-nav-button a:visited { - border-top: 1px solid #cecece; - border-bottom: 2px solid #4a4a4a; - border-left: 1px solid #cecece; - border-right: 2px solid #4a4a4a; -} - -.ims-nav-button a:hover { - border-bottom: 1px solid #cecece; - border-top: 2px solid #4a4a4a; - border-right: 1px solid #cecece; - border-left: 2px solid #4a4a4a; -} - -#ims-contentframe, -#ims-contentframe-no-nav { - border-color: #cecece; -} - - /*** *** Modules: Scorm ***/ diff --git a/theme/standard/styles_fonts.css b/theme/standard/styles_fonts.css index d883c02eab165..3dcda73c195ff 100644 --- a/theme/standard/styles_fonts.css +++ b/theme/standard/styles_fonts.css @@ -1099,8 +1099,15 @@ body#mod-forum-index .generalbox .cell { text-decoration:underline; } +/*** + *** Modules: Resource + ***/ + +.mod-page .modified { + font-size:0.6em; +} - /*** +/*** *** Modules: Resource ***/ @@ -1112,19 +1119,6 @@ body#mod-forum-index .generalbox .cell { font-size:0.6em; } -.ims-nav-dimmed, -.ims-nav-button { - font-size:0.8em; -} - -#ims-toc-selected { - font-weight: bold; -} - -#ims-menudiv { - font-size:0.8em; -} - /*** *** Modules: Scorm ***/ diff --git a/theme/standard/styles_layout.css b/theme/standard/styles_layout.css index f522f24bd0cb7..a14666476e0c7 100644 --- a/theme/standard/styles_layout.css +++ b/theme/standard/styles_layout.css @@ -3787,6 +3787,27 @@ body#user-index .rolesform { text-align:center; } +/*** + *** Modules: general + ***/ + +.mod_introbox { + border-width:1px; + border-style:solid; + margin-top: 1em; + margin-bottom: 1em; + padding:10px; + width:90%; + margin-left:auto; + margin-right:auto; +} + +table.mod_index { + width:90%; + margin-left:auto; + margin-right:auto; +} + /*** *** Modules: Assignment ***/ @@ -3938,6 +3959,17 @@ table.presets { margin-right: auto; } +/*** + *** + *** Modules: Folder + ***/ + +#mod-folder-view .foldertree { + width: 90%; + margin-left: auto; + margin-right: auto; +} + /*** *** Modules: Forum ***/ @@ -5318,52 +5350,6 @@ body.jsenabled #quizcontentsblock .repaginatecommand #repaginatecommand{ margin:40px; } -.ims-nav-bar { - margin-top:0.2em; - position: relative; -} - -.ims-nav-button a, -.ims-nav-dimmed { - padding-left:1em; - padding-right:1em; - padding-top:0.2em; - padding-bottom:0.2em; -} - -#ims-containerdiv { - margin-top:0.2em; -} - -#ims-menudiv { - padding-top:1em; - padding-right:0.2em; - position:absolute; - width:250px; - overflow:auto; -} - -#ims-menudiv ol { - margin:0em; - list-style-type:none; - padding-left:1em; -} - -#ims-contentframe { - position:absolute; - left:260px; - border:1px solid; - width:640px; - height:480px; -} - -#ims-contentframe-no-nav { - position:absolute; - border:1px solid; - width:640px; - height:480px; -} - #mod-resource-view div#footer { margin-top: 5px; }