Create the coursemodule to hold the file/content that has been uploaded
14265
protected function create_course_module() {
        global $CFG;
        require_once($CFG->dirroot.'/course/modlib.php');
        list($module, $context, $cw, $cm, $data) = prepare_new_moduleinfo_data($this->course, $this->module->name, $this->section);

        $data->coursemodule = $data->id = add_course_module($data);
        $this->cm = $data;
    }
1177550
public function set_module_viewed() {
        $completion = new completion_info($this->get_course());
        $completion->set_module_viewed($this->get_course_module());

        // Trigger the course module viewed event.
        $assigninstance = $this->get_instance();
        $params = [
            'objectid' => $assigninstance->id,
            'context' => $this->get_context()
        ];
        if ($this->is_blind_marking()) {
            $params['anonymous'] = 1;
        }

        $event = \mod_assign\event\course_module_viewed::create($params);

        $event->add_record_snapshot('assign', $assigninstance);
        $event->trigger();
    }
718121
def dump_course(self, courseid):
        
        filepath = os.path.join(self.backup_dir, courseid, datetime.datetime.now().strftime("%Y%m%d.%H%M%S") + ".zip")

        if not os.path.exists(os.path.dirname(filepath)):
            os.makedirs(os.path.dirname(filepath))

        with zipfile.ZipFile(filepath, "w", allowZip64=True) as zipf:
            aggregations = self.database.aggregations.find({"courseid": courseid})
            zipf.writestr("aggregations.json", bson.json_util.dumps(aggregations), zipfile.ZIP_DEFLATED)

            user_tasks = self.database.user_tasks.find({"courseid": courseid})
            zipf.writestr("user_tasks.json", bson.json_util.dumps(user_tasks), zipfile.ZIP_DEFLATED)

            submissions = self.database.submissions.find({"courseid": courseid})
            zipf.writestr("submissions.json", bson.json_util.dumps(submissions), zipfile.ZIP_DEFLATED)

            submissions.rewind()

            for submission in submissions:
                for key in ["input", "archive"]:
                    if key in submission and type(submission[key]) == bson.objectid.ObjectId:
                        infile = self.submission_manager.get_gridfs().get(submission[key])
                        zipf.writestr(key + "/" + str(submission[key]) + ".data", infile.read(), zipfile.ZIP_DEFLATED)

        self._logger.info("Course %s dumped to backup directory.", courseid)
        self.wipe_course(courseid)
499342
public function define_course_plugin_structure() {
        global $DB;

        // Since this method is executed before the restore we can do some pre-checks here.
        // In case of merging backup into existing course find the current number of sections.
        $target = $this->step->get_task()->get_target();
        if (($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) &&
                $this->is_pre_33_backup()) {
            $maxsection = $DB->get_field_sql(
                'SELECT max(section) FROM {course_sections} WHERE course = ?',
                [$this->step->get_task()->get_courseid()]);
            $this->originalnumsections = (int)$maxsection;
        }

        // Dummy path element is needed in order for after_restore_course() to be called.
        return [new restore_path_element('dummy_course', $this->get_pathfor('/dummycourse'))];
    }
150648
public function definition () {
        $mform = $this->_form;

        $mform->addElement('header', 'generalhdr', get_string('general'));

        $mform->addElement('filepicker', 'coursefile', get_string('coursefile', 'tool_uploadcourse'));
        $mform->addRule('coursefile', null, 'required');
        $mform->addHelpButton('coursefile', 'coursefile', 'tool_uploadcourse');

        $choices = csv_import_reader::get_delimiter_list();
        $mform->addElement('select', 'delimiter_name', get_string('csvdelimiter', 'tool_uploadcourse'), $choices);
        if (array_key_exists('cfg', $choices)) {
            $mform->setDefault('delimiter_name', 'cfg');
        } else if (get_string('listsep', 'langconfig') == ';') {
            $mform->setDefault('delimiter_name', 'semicolon');
        } else {
            $mform->setDefault('delimiter_name', 'comma');
        }
        $mform->addHelpButton('delimiter_name', 'csvdelimiter', 'tool_uploadcourse');

        $choices = core_text::get_encodings();
        $mform->addElement('select', 'encoding', get_string('encoding', 'tool_uploadcourse'), $choices);
        $mform->setDefault('encoding', 'UTF-8');
        $mform->addHelpButton('encoding', 'encoding', 'tool_uploadcourse');

        $choices = array('10' => 10, '20' => 20, '100' => 100, '1000' => 1000, '100000' => 100000);
        $mform->addElement('select', 'previewrows', get_string('rowpreviewnum', 'tool_uploadcourse'), $choices);
        $mform->setType('previewrows', PARAM_INT);
        $mform->addHelpButton('previewrows', 'rowpreviewnum', 'tool_uploadcourse');

        $this->add_import_options();

        $mform->addElement('hidden', 'showpreview', 1);
        $mform->setType('showpreview', PARAM_INT);

        $this->add_action_buttons(false, get_string('preview', 'tool_uploadcourse'));
    }
746270
def _construct_module(info, target):
    """"""

    for path in paths:
        real_path = os.path.abspath(os.path.join(target, path.format(**info)))
        log("Making directory '%s'" % real_path)
        os.makedirs(real_path)

    # pprint(info)
    for item in templates.values():
        source = os.path.join('dev/templates', item[0])
        filename = os.path.abspath(
            os.path.join(target, item[1].format(**info)))
        log("Creating file from template '%s'" % filename,
            emitter='MANAGE')
        write_template_file(source, filename, info)
813900
function makeModule(index) {

		var stored, src, srcPath, relpath;

		// Prepare module
		var module  = new Module({
			 uid:    index
			,req:    []
			,path:   index
			,relpath: null
			,isNodeModule: false
			,isAsyncModule: arequirePath === index
			,arequirePath:  arequirePath
			,index:  index
		});

		if(~module.path.indexOf('/node_modules/')) module.isNodeModule = true;

		relpath = path.relative(process.cwd(), module.path);
		relpath = !/^\./.test(relpath) ? './' + relpath : relpath;
		module.relpath = relpath;

		debug('makeModule for %s', relpath);

		// Check for stored version of this path
		stored = _.find(modules, function(p) {
			return module.path === p.path;
		});
		if(stored) {
			debug('allready stored : return (absolute path match)');
			return stored;
		}

		// Read source
		src           = fs.readFileSync(module.path, 'utf8');
		module.mtime  = fs.statSync(module.path).mtime;
		module.uid    = getUID({src: src, path:module.path, options: options});

		// Check for stored version with same uid
		stored = _.find(modules, function(p) {
			return module.uid  === p.uid;
		});
		if(stored) {
			debug('allready stored : return (md5 hash match)');
			return stored;
		}

		// Save module
		modules.push(module);

		// Do not parse ?
		module.notparsed = _.find(noparse, function(np) {
			if(np instanceof RegExp) {
				return np.test(module.path);
			} else if ('string'   == typeof np) {
				return minimatch(module.path, np);
			} else if ('function' == typeof np) {
				return np(module.path, module);
			} else {
				return false;
			}
		});

		// Parse
		if(module.notparsed) {
			debug('  no parse');
		} else {
			debug('  run parse');
			src = parse(src, module, makeModule, options);
		}

		// Store the module source :
		module.source = src;


		// Return the module object

		debug('end %s', relpath);
		return module;
	}
424966
private function publishModule()
    {
        $from = base_path('vendor/typicms/objects/src');
        $to = base_path('Modules/'.$this->module);

        if ($this->files->isDirectory($from)) {
            $this->publishDirectory($from, $to);
        } else {
            $this->error("Can’t locate path: <{$from}>");
        }
    }
88514
function getSplitModule(content, constraints) {
    var src = '', lastIdx = 0, currentNamespace;
    content.replace(/\/\*\*\* @namespace (\w+) \*\*\*\/\n|$/g, function(match, nextNamespace, idx) {
      if (!currentNamespace || constraints[currentNamespace]) {
        src += content.slice(lastIdx, idx);
      }
      currentNamespace = (nextNamespace || '').toLowerCase();
      lastIdx = idx;
    });
    return src;
  }
827031
function uploadToUpyun(path, file, __newFile, done) {
  var options = this.options;
  var upyun = getInstance(options);
  upyun.uploadFile(path, file, __newFile.headers['content-type'], true, function (err, data) {
    if (err) {
      return done(err);
    }
    if (!data) {
      return done(new Error('Upload failed!'));
    }
    if (data && data.statusCode != 200) {
      return done(new Error(data.error['message']));
    }
    __newFile.fd = options.domain + path;
    return done();
  });
}
529373
def exec_module(self, module):
        """"""
        path = [os.path.dirname(module.__file__)]  # file should have been resolved before (module creation)
        file = None
        try:
            file, pathname, description = imp.find_module(module.__name__.rpartition('.')[-1], path)
            module = imp.load_module(module.__name__, file, pathname, description)
        finally:
            if file:
                file.close()
839334
private function saveFile(): void
    {
        $sourceCode = Helpers::tabsToSpaces((string) $this->DTOFile);

        $fullPath = implode('/', [
            dirname(__DIR__, 7) . '/src',
            $this->inputData['namespace'],
            $this->inputData['module'] . 'Module',
            $this->inputData['type'],
            $this->inputData['class'] . $this->inputData['type'] . '.php'
        ]);

        $dirname = dirname($fullPath);

        if (!is_dir($dirname)) {
            mkdir($dirname, 0755, true);
        }

        $handle = fopen($fullPath, 'w');
        fwrite($handle, $sourceCode);
        fclose($handle);
    }
910203
function initModule(modName, mod) {
        console.log("Initialising "+modName);
        if (mod.init !== undefined)
          mod.init();
      }
832036
public function definition () {
        global $CFG;

        $mform   = $this->_form;
        $data    = $this->_customdata['data'];
        $courseconfig = get_config('moodlecourse');

        // Import options.
        $this->add_import_options();

        // Course options.
        $mform->addElement('header', 'courseoptionshdr', get_string('courseprocess', 'tool_uploadcourse'));
        $mform->setExpanded('courseoptionshdr', true);

        $mform->addElement('text', 'options[shortnametemplate]', get_string('shortnametemplate', 'tool_uploadcourse'),
            'maxlength="100" size="20"');
        $mform->setType('options[shortnametemplate]', PARAM_RAW);
        $mform->addHelpButton('options[shortnametemplate]', 'shortnametemplate', 'tool_uploadcourse');
        $mform->hideIf('options[shortnametemplate]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_CREATE_OR_UPDATE);
        $mform->hideIf('options[shortnametemplate]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_UPDATE_ONLY);

        // Restore file is not in the array options on purpose, because formslib can't handle it!
        $contextid = $this->_customdata['contextid'];
        $mform->addElement('hidden', 'contextid', $contextid);
        $mform->setType('contextid', PARAM_INT);
        $mform->addElement('filepicker', 'restorefile', get_string('templatefile', 'tool_uploadcourse'));
        $mform->addHelpButton('restorefile', 'templatefile', 'tool_uploadcourse');

        $mform->addElement('text', 'options[templatecourse]', get_string('coursetemplatename', 'tool_uploadcourse'));
        $mform->setType('options[templatecourse]', PARAM_TEXT);
        $mform->addHelpButton('options[templatecourse]', 'coursetemplatename', 'tool_uploadcourse');

        $mform->addElement('selectyesno', 'options[reset]', get_string('reset', 'tool_uploadcourse'));
        $mform->setDefault('options[reset]', 0);
        $mform->hideIf('options[reset]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_CREATE_NEW);
        $mform->hideIf('options[reset]', 'options[mode]', 'eq', tool_uploadcourse_processor::MODE_CREATE_ALL);
        $mform->disabledIf('options[reset]', 'options[allowresets]', 'eq', 0);
        $mform->addHelpButton('options[reset]', 'reset', 'tool_uploadcourse');

        // Default values.
        $mform->addElement('header', 'defaultheader', get_string('defaultvalues', 'tool_uploadcourse'));
        $mform->setExpanded('defaultheader', true);

        $displaylist = core_course_category::make_categories_list('moodle/course:create');
        $mform->addElement('select', 'defaults[category]', get_string('coursecategory'), $displaylist);
        $mform->addHelpButton('defaults[category]', 'coursecategory');

        $choices = array();
        $choices['0'] = get_string('hide');
        $choices['1'] = get_string('show');
        $mform->addElement('select', 'defaults[visible]', get_string('coursevisibility'), $choices);
        $mform->addHelpButton('defaults[visible]', 'coursevisibility');
        $mform->setDefault('defaults[visible]', $courseconfig->visible);

        $mform->addElement('date_time_selector', 'defaults[startdate]', get_string('startdate'));
        $mform->addHelpButton('defaults[startdate]', 'startdate');
        $mform->setDefault('defaults[startdate]', time() + 3600 * 24);

        $mform->addElement('date_time_selector', 'defaults[enddate]', get_string('enddate'), array('optional' => true));
        $mform->addHelpButton('defaults[enddate]', 'enddate');

        $courseformats = get_sorted_course_formats(true);
        $formcourseformats = array();
        foreach ($courseformats as $courseformat) {
            $formcourseformats[$courseformat] = get_string('pluginname', "format_$courseformat");
        }
        $mform->addElement('select', 'defaults[format]', get_string('format'), $formcourseformats);
        $mform->addHelpButton('defaults[format]', 'format');
        $mform->setDefault('defaults[format]', $courseconfig->format);

        if (!empty($CFG->allowcoursethemes)) {
            $themeobjects = get_list_of_themes();
            $themes=array();
            $themes[''] = get_string('forceno');
            foreach ($themeobjects as $key => $theme) {
                if (empty($theme->hidefromselector)) {
                    $themes[$key] = get_string('pluginname', 'theme_'.$theme->name);
                }
            }
            $mform->addElement('select', 'defaults[theme]', get_string('forcetheme'), $themes);
        }

        $languages = array();
        $languages[''] = get_string('forceno');
        $languages += get_string_manager()->get_list_of_translations();
        $mform->addElement('select', 'defaults[lang]', get_string('forcelanguage'), $languages);
        $mform->setDefault('defaults[lang]', $courseconfig->lang);

        $options = range(0, 10);
        $mform->addElement('select', 'defaults[newsitems]', get_string('newsitemsnumber'), $options);
        $mform->addHelpButton('defaults[newsitems]', 'newsitemsnumber');
        $mform->setDefault('defaults[newsitems]', $courseconfig->newsitems);

        $mform->addElement('selectyesno', 'defaults[showgrades]', get_string('showgrades'));
        $mform->addHelpButton('defaults[showgrades]', 'showgrades');
        $mform->setDefault('defaults[showgrades]', $courseconfig->showgrades);

        $mform->addElement('selectyesno', 'defaults[showreports]', get_string('showreports'));
        $mform->addHelpButton('defaults[showreports]', 'showreports');
        $mform->setDefault('defaults[showreports]', $courseconfig->showreports);

        if (!empty($CFG->legacyfilesinnewcourses)) {
            $mform->addElement('select', 'defaults[legacyfiles]', get_string('courselegacyfiles'), $choices);
            $mform->addHelpButton('defaults[legacyfiles]', 'courselegacyfiles');
            if (!isset($courseconfig->legacyfiles)) {
                $courseconfig->legacyfiles = 0;
            }
            $mform->setDefault('defaults[legacyfiles]', $courseconfig->legacyfiles);
        }

        $choices = get_max_upload_sizes($CFG->maxbytes);
        $mform->addElement('select', 'defaults[maxbytes]', get_string('maximumupload'), $choices);
        $mform->addHelpButton('defaults[maxbytes]', 'maximumupload');
        $mform->setDefault('defaults[maxbytes]', $courseconfig->maxbytes);

        $choices = array();
        $choices[NOGROUPS] = get_string('groupsnone', 'group');
        $choices[SEPARATEGROUPS] = get_string('groupsseparate', 'group');
        $choices[VISIBLEGROUPS] = get_string('groupsvisible', 'group');
        $mform->addElement('select', 'defaults[groupmode]', get_string('groupmode', 'group'), $choices);
        $mform->addHelpButton('defaults[groupmode]', 'groupmode', 'group');
        $mform->setDefault('defaults[groupmode]', $courseconfig->groupmode);

        $mform->addElement('selectyesno', 'defaults[groupmodeforce]', get_string('groupmodeforce', 'group'));
        $mform->addHelpButton('defaults[groupmodeforce]', 'groupmodeforce', 'group');
        $mform->setDefault('defaults[groupmodeforce]', $courseconfig->groupmodeforce);

        // Completion tracking.
        if (!empty($CFG->enablecompletion)) {
            $mform->addElement('selectyesno', 'defaults[enablecompletion]', get_string('enablecompletion', 'completion'));
            $mform->setDefault('defaults[enablecompletion]', $courseconfig->enablecompletion);
            $mform->addHelpButton('defaults[enablecompletion]', 'enablecompletion', 'completion');
        }

        // Hidden fields.
        $mform->addElement('hidden', 'importid');
        $mform->setType('importid', PARAM_INT);

        $mform->addElement('hidden', 'previewrows');
        $mform->setType('previewrows', PARAM_INT);

        $this->add_action_buttons(true, get_string('uploadcourses', 'tool_uploadcourse'));

        $this->set_data($data);
    }
1007815
private function publishModule()
    {
        $from = base_path('vendor/typicms/'.$this->module.'/src');
        $to = base_path('Modules/'.ucfirst($this->module));

        if ($this->files->isDirectory($from)) {
            $this->publishDirectory($from, $to);
        } else {
            $this->error("Can’t locate path: <{$from}>");
        }

        $this->info('Publishing complete for module ['.ucfirst($this->module).']!');
    }
930300
static function createClass( $tpl,
                                 $module,
                                 $stepArray,
                                 $basePath,
                                 $storageName = false,
                                 $metaData = false )
    {
        if ( !$storageName )
        {
            $storageName = 'eZWizard';
        }

        if ( !$metaData )
        {
            $http = eZHTTPTool::instance();
            $metaData = $http->sessionVariable( $storageName . '_meta' );
        }

        if ( !isset( $metaData['current_step'] ) ||
             $metaData['current_step'] < 0 )
        {
            $metaData['current_step'] = 0;
            eZDebug::writeNotice( 'Setting wizard step to : ' . $metaData['current_step'], __METHOD__ );
        }
        $currentStep = $metaData['current_step'];

        if ( count( $stepArray ) <= $currentStep )
        {
            eZDebug::writeError( 'Invalid wizard step count: ' . $currentStep, __METHOD__ );
            return false;
        }

        $filePath = $basePath . $stepArray[$currentStep]['file'];
        if ( !file_exists( $filePath ) )
        {
            eZDebug::writeError( 'Wizard file not found : ' . $filePath, __METHOD__ );
            return false;
        }

        include_once( $filePath );

        $className = $stepArray[$currentStep]['class'];
        eZDebug::writeNotice( 'Creating class : ' . $className, __METHOD__ );
        $returnClass =  new $className( $tpl, $module, $storageName );

        if ( isset( $stepArray[$currentStep]['operation'] ) )
        {
            $operation = $stepArray[$currentStep]['operation'];
            return $returnClass->$operation();
            eZDebug::writeNotice( 'Running : "' . $className . '->' . $operation . '()". Specified in StepArray', __METHOD__ );
        }

        if ( isset( $metaData['current_stage'] ) )
        {
            $returnClass->setMetaData( 'current_stage', $metaData['current_stage'] );
            eZDebug::writeNotice( 'Setting wizard stage to : ' . $metaData['current_stage'], __METHOD__ );
        }

        return $returnClass;
    }
1189969
function loadModule( state, resourcePath ) {
	try {
		var key = path.resolve( resourcePath );
		delete require.cache[ key ];
		var modFn = require( resourcePath );
		var args = getArguments( modFn );
		args.shift();
		if ( args.length ) {
			return state.fount.resolve( args )
				.then( function( deps ) {
					var argList = _.map( args, function( arg ) {
						return deps[ arg ];
					} );
					argList.unshift( state.host );
					var mod = modFn.apply( modFn, argList );
					attachPath( state, mod, resourcePath );
					return mod;
				} );
		} else {
			var mod = modFn( state.host );
			attachPath( state, mod, resourcePath );
			return when( mod );
		}
	} catch ( err ) {
		console.error( 'Error loading resource module at %s with: %s', resourcePath, err.stack );
		return when( [] );
	}
}