Converts /MOODLE_BACKUP/COURSE/MODULES/MOD/RESOURCE data

This methods detects the resource type and eventually re-dispatches it to the
corresponding resource successor (url, forum, page, imscp).
438100
public function process_resource(array $data, array $raw) {
        global $CFG;
        require_once("$CFG->libdir/resourcelib.php");

        // replay the upgrade step 2009042001
        if ($CFG->texteditors !== 'textarea') {
            $data['intro']       = text_to_html($data['intro'], false, false, true);
            $data['introformat'] = FORMAT_HTML;
        }

        // fix invalid null popup and options data
        if (!array_key_exists('popup', $data) or is_null($data['popup'])) {
            $data['popup'] = '';
        }
        if (!array_key_exists ('options', $data) or is_null($data['options'])) {
            $data['options'] = '';
        }

        // decide if the legacy resource should be handled by a successor module
        if ($successor = $this->get_successor($data['type'], $data['reference'])) {
            // the instance id will be kept
            $instanceid = $data['id'];

            // move the instance from the resource's modinfo stash to the successor's
            // modinfo stash
            $resourcemodinfo  = $this->converter->get_stash('modinfo_resource');
            $successormodinfo = $this->converter->get_stash('modinfo_'.$successor->get_modname());
            $successormodinfo['instances'][$instanceid] = $resourcemodinfo['instances'][$instanceid];
            unset($resourcemodinfo['instances'][$instanceid]);
            $this->converter->set_stash('modinfo_resource', $resourcemodinfo);
            $this->converter->set_stash('modinfo_'.$successor->get_modname(), $successormodinfo);

            // get the course module information for the legacy resource module
            $cminfo = $this->get_cminfo($instanceid);

            // use the version of the successor instead of the current mod/resource
            // beware - the version.php declares info via $module object, do not use
            // a variable of such name here
            $plugin = new stdClass();
            $plugin->version = null;
            $module = $plugin;
            include $CFG->dirroot.'/mod/'.$successor->get_modname().'/version.php';
            $cminfo['version'] = $plugin->version;

            // stash the new course module information for this successor
            $cminfo['modulename'] = $successor->get_modname();
            $this->converter->set_stash('cminfo_'.$cminfo['modulename'], $cminfo, $instanceid);

            // rewrite the coursecontents stash
            $coursecontents = $this->converter->get_stash('coursecontents');
            $coursecontents[$cminfo['id']]['modulename'] = $successor->get_modname();
            $this->converter->set_stash('coursecontents', $coursecontents);

            // delegate the processing to the successor handler
            return $successor->process_legacy_resource($data, $raw);
        }

        // no successor is interested in this record, convert it to the new mod_resource (aka File module)

        $resource = array();
        $resource['id']              = $data['id'];
        $resource['name']            = $data['name'];
        $resource['intro']           = $data['intro'];
        $resource['introformat']     = $data['introformat'];
        $resource['tobemigrated']    = 0;
        $resource['legacyfiles']     = RESOURCELIB_LEGACYFILES_ACTIVE;
        $resource['legacyfileslast'] = null;
        $resource['filterfiles']     = 0;
        $resource['revision']        = 1;
        $resource['timemodified']    = $data['timemodified'];

        // populate display and displayoptions fields
        $options = array('printintro' => 1);
        if ($data['options'] == 'frame') {
            $resource['display'] = RESOURCELIB_DISPLAY_FRAME;

        } else if ($data['options'] == 'objectframe') {
            $resource['display'] = RESOURCELIB_DISPLAY_EMBED;

        } else if ($data['options'] == 'forcedownload') {
            $resource['display'] = RESOURCELIB_DISPLAY_DOWNLOAD;

        } else if ($data['popup']) {
            $resource['display'] = RESOURCELIB_DISPLAY_POPUP;
            $rawoptions = explode(',', $data['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);

        // get the course module id and context id
        $instanceid     = $resource['id'];
        $currentcminfo  = $this->get_cminfo($instanceid);
        $moduleid       = $currentcminfo['id'];
        $contextid      = $this->converter->get_contextid(CONTEXT_MODULE, $moduleid);

        // get a fresh new file manager for this instance
        $this->fileman = $this->converter->get_file_manager($contextid, 'mod_resource');

        // convert course files embedded into the intro
        $this->fileman->filearea = 'intro';
        $this->fileman->itemid   = 0;
        $resource['intro'] = moodle1_converter::migrate_referenced_files($resource['intro'], $this->fileman);

        // convert the referenced file itself as a main file in the content area
        $reference = $data['reference'];
        if (strpos($reference, '$@FILEPHP@$') === 0) {
            $reference = str_replace(array('$@FILEPHP@$', '$@SLASH@$', '$@FORCEDOWNLOAD@$'), array('', '/', ''), $reference);
        }
        $this->fileman->filearea = 'content';
        $this->fileman->itemid   = 0;

        // Rebuild the file path.
        $curfilepath = '/';
        if ($reference) {
            $curfilepath = pathinfo('/'.$reference, PATHINFO_DIRNAME);
            if ($curfilepath != '/') {
                $curfilepath .= '/';
            }
        }
        try {
            $this->fileman->migrate_file('course_files/'.$reference, $curfilepath, null, 1);
        } catch (moodle1_convert_exception $e) {
            // the file probably does not exist
            $this->log('error migrating the resource main file', backup::LOG_WARNING, 'course_files/'.$reference);
        }

        // write resource.xml
        $this->open_xml_writer("activities/resource_{$moduleid}/resource.xml");
        $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $moduleid,
            'modulename' => 'resource', 'contextid' => $contextid));
        $this->write_xml('resource', $resource, array('/resource/id'));
        $this->xmlwriter->end_tag('activity');
        $this->close_xml_writer();

        // write inforef.xml
        $this->open_xml_writer("activities/resource_{$currentcminfo['id']}/inforef.xml");
        $this->xmlwriter->begin_tag('inforef');
        $this->xmlwriter->begin_tag('fileref');
        foreach ($this->fileman->get_fileids() as $fileid) {
            $this->write_xml('file', array('id' => $fileid));
        }
        $this->xmlwriter->end_tag('fileref');
        $this->xmlwriter->end_tag('inforef');
        $this->close_xml_writer();
    }
1251517
def get_resource_data(incoming_request):
    """"""
    content_type = incoming_request.headers['Content-type'].split(';')[0]
    if ('Content-type' not in incoming_request.headers or
            content_type in JSON_CONTENT_TYPES):
        return incoming_request.json
    elif content_type in HTML_CONTENT_TYPES:
        if not incoming_request.form:
            raise InvalidAPIUsage(400)
        return incoming_request.form
    else:
        # HTTP 415: Unsupported Media Type
        raise InvalidAPIUsage(
            415,
            UNSUPPORTED_CONTENT_TYPE_MESSAGE.format(
                types=incoming_request.headers['Content-type']))
676307
def get_matching_resource_types(resource_type, resource_id,**kwargs):
    
    resource_i = None
    if resource_type == 'NETWORK':
        resource_i = db.DBSession.query(Network).filter(Network.id==resource_id).one()
    elif resource_type == 'NODE':
        resource_i = db.DBSession.query(Node).filter(Node.id==resource_id).one()
    elif resource_type == 'LINK':
        resource_i = db.DBSession.query(Link).filter(Link.id==resource_id).one()
    elif resource_type == 'GROUP':
        resource_i = db.DBSession.query(ResourceGroup).filter(ResourceGroup.id==resource_id).one()

    matching_types = get_types_by_attr(resource_i)
    return matching_types
130544
def update_resources(self, data, type_, names=None, languages=None):
        
        UpdateResources(self.filename, data, type_, names, languages)
1050397
def resolve_resource_type(self, resource_dict):
        
        if not self.can_resolve(resource_dict):
            raise TypeError("Resource dict has missing or invalid value for key Type. Event Type is: {}.".format(
                    resource_dict.get('Type')))
        if resource_dict['Type'] not in self.resource_types:
            raise TypeError("Invalid resource type {resource_type}".format(resource_type=resource_dict['Type']))
        return self.resource_types[resource_dict['Type']]
823565
public function process_legacy_resource(array $data, array $raw = null) {

        $instanceid    = $data['id'];
        $currentcminfo = $this->get_cminfo($instanceid);
        $moduleid      = $currentcminfo['id'];
        $contextid     = $this->converter->get_contextid(CONTEXT_MODULE, $moduleid);

        // Prepare the new imscp instance record.
        $imscp                  = array();
        $imscp['id']            = $data['id'];
        $imscp['name']          = $data['name'];
        $imscp['intro']         = $data['intro'];
        $imscp['introformat']   = $data['introformat'];
        $imscp['revision']      = 1;
        $imscp['keepold']       = 1;
        $imscp['structure']     = null;
        $imscp['timemodified']  = $data['timemodified'];

        // Prepare a fresh new file manager for this instance.
        $this->fileman = $this->converter->get_file_manager($contextid, 'mod_imscp');

        // Convert course files embedded into the intro.
        $this->fileman->filearea = 'intro';
        $this->fileman->itemid   = 0;
        $imscp['intro'] = moodle1_converter::migrate_referenced_files($imscp['intro'], $this->fileman);

        // Migrate package backup file.
        if ($data['reference']) {
            $packagename = basename($data['reference']);
            $packagepath = $this->converter->get_tempdir_path().'/moddata/resource/'.$data['id'].'/'.$packagename;
            if (file_exists($packagepath)) {
                $this->fileman->filearea = 'backup';
                $this->fileman->itemid   = 1;
                $this->fileman->migrate_file('moddata/resource/'.$data['id'].'/'.$packagename);
            } else {
                $this->log('missing imscp package', backup::LOG_WARNING, 'moddata/resource/'.$data['id'].'/'.$packagename);
            }
        }

        // Migrate extracted package data.
        $this->fileman->filearea = 'content';
        $this->fileman->itemid   = 1;
        $this->fileman->migrate_directory('moddata/resource/'.$data['id']);

        // Parse manifest.
        $structure = $this->parse_structure($this->converter->get_tempdir_path().
                    '/moddata/resource/'.$data['id'].'/imsmanifest.xml', $imscp, $contextid);
        $imscp['structure'] = is_array($structure) ? serialize($structure) : null;

        // Write imscp.xml.
        $this->open_xml_writer("activities/imscp_{$moduleid}/imscp.xml");
        $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $moduleid,
            'modulename' => 'imscp', 'contextid' => $contextid));
        $this->write_xml('imscp', $imscp, array('/imscp/id'));
        $this->xmlwriter->end_tag('activity');
        $this->close_xml_writer();

        // Write inforef.xml.
        $this->open_xml_writer("activities/imscp_{$moduleid}/inforef.xml");
        $this->xmlwriter->begin_tag('inforef');
        $this->xmlwriter->begin_tag('fileref');
        foreach ($this->fileman->get_fileids() as $fileid) {
            $this->write_xml('file', array('id' => $fileid));
        }
        $this->xmlwriter->end_tag('fileref');
        $this->xmlwriter->end_tag('inforef');
        $this->close_xml_writer();
    }
648428
def resource_url(self, entity_id, name, revision):
        '''
        
        '''
        return '{}/{}/resource/{}/{}'.format(self.url,
                                             _get_path(entity_id),
                                             name,
                                             revision)
707019
async def convert_local(path, to_type):
    '''
    
    '''
    # Now find path between types
    typed_foreign_res = TypedLocalResource(path)
    original_ts = typed_foreign_res.typestring
    conversion_path = singletons.converter_graph.find_path(
        original_ts, to_type)
    # print('Conversion path: ', conversion_path)

    # Loop through each step in graph path and convert
    for is_first, is_last, path_step in first_last_iterator(conversion_path):
        converter_class, from_ts, to_ts = path_step
        converter = converter_class()
        in_resource = TypedLocalResource(path, from_ts)
        if is_first:  # Ensure first resource is just the source one
            in_resource = typed_foreign_res
        out_resource = TypedLocalResource(path, to_ts)

        if is_last:
            out_resource = TypedPathedLocalResource(path, to_ts)
        await converter.convert(in_resource, out_resource)
1295020
def get_resource_types(self):
        
        resource_types = set()
        for model in self.models():
            for field in self.model_file_fields(model):
                resource_type = field.storage.RESOURCE_TYPE
                resource_types.add(resource_type)
        return resource_types
245950
def resource_type_type(loader):
    

    def impl(string):
        t_resources = loader.get_models('common.models#ResourceTypes')
        if set(string) - set("sco"):
            raise ValueError
        return t_resources(_str=''.join(set(string)))

    return impl
182829
def update_resources_from_datafile(self, srcpath, type_, names=None, 
                                       languages=None):
        
        UpdateResourcesFromDataFile(self.filename, srcpath, type_, names, 
                                    languages)
174662
def dump_resource(resource, stream, content_type=None):
    
    if content_type is None:
        content_type = CsvMime
    rpr = as_representer(resource, content_type)
    rpr.to_stream(resource, stream)
748197
def singular_subresource(raml_resource, route_name):
    
    static_parent = get_static_parent(raml_resource, method='POST')
    if static_parent is None:
        return False
    schema = resource_schema(static_parent) or {}
    properties = schema.get('properties', {})
    if route_name not in properties:
        return False

    db_settings = properties[route_name].get('_db_settings', {})
    is_obj = db_settings.get('type') == 'relationship'
    single_obj = not db_settings.get('uselist', True)
    return is_obj and single_obj
1342145
def expand_resource_type(types)
      output = [types].flatten.map do |t|
        if t.class.to_s =~ /Puppet::Pops::Types/
          to_resource_declaration(t)
        else
          t
        end
      end
      output
    end
608660
def _migrate_subresource(subresource, parent, migrations):
    
    for key, doc in getattr(parent, subresource.parent_key, {}).items():
        for migration in migrations['migrations']:
            instance = migration(subresource(id=key, **doc))
            parent._resource['doc_version'] = unicode(migration.version)

            instance = _migrate_subresources(
                instance,
                migrations['subresources']
            )

        doc = instance._resource
        doc.pop('id', None)
        doc.pop(instance.resource_type + '_id', None)

        getattr(parent, subresource.parent_key)[key] = doc

    return parent
892387
def rtype_to_model(rtype):
    

    models = goldman.config.MODELS
    for model in models:
        if rtype.lower() == model.RTYPE.lower():
            return model
    raise ValueError('%s resource type not registered' % rtype)
745522
def update_resource(self, resource):
        ''''''
        index = self.resources.index(resource)
        data = {
            'resources__{index}'.format(index=index): resource
        }
        self.update(**data)
        self.reload()
        post_save.send(self.__class__, document=self)