Exemple #1
0
def get_layer_config(request, typename, permission='base.view_resourcebase',
                   msg=_PERMISSION_GENERIC, **kwargs):
                       
    try:
        layer = _resolve_layer(request, typename, "base.view_resourcebase", _PERMISSION_VIEW )
    except Exception as e:
        pprint("Error on resolving layer")
        pprint("Message: "+ e.message + "/nType: "+str(type(e)))

    config = layer.attribute_config()
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True
    
    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))
    
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    
    return context_dict
Exemple #2
0
def layer_detail(request, layername, template='layers/layer_detail.html'):

    layer = _resolve_layer(request, layername, 'base.view_resourcebase', _PERMISSION_MSG_VIEW)
    layer_bbox = layer.bbox
    # assert False, str(layer_bbox)
    bbox = list(layer_bbox[0:4])
    config = layer.attribute_config()

    #Add required parameters for GXP lazy-loading
    config["srs"] = layer.srid
    config["title"] = layer.title
    config["bbox"] =  [float(coord) for coord in bbox] \
        if layer.srid == "EPSG:4326" else llbbox_to_mercator([float(coord) for coord in bbox])

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {"ptype":service.ptype, "remote": True, "url": service.base_url, "name": service.name}
        maplayer = GXPLayer(name = layer.typename, ows_url = layer.ows_url, layer_params=json.dumps( config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name = layer.typename, ows_url = layer.ows_url, layer_params=json.dumps( config))

    # Update count for popularity ranking.
    Layer.objects.filter(id=layer.id).update(popular_count=layer.popular_count +1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
    }

    context_dict["viewer"] = json.dumps(map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY', 'leaflet')

    if layer.storeType=='dataStore':
        links = layer.link_set.download().filter(
        name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
        name__in=settings.DOWNLOAD_FORMATS_RASTER)


    context_dict["links"] = links

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #3
0
def create_arcgis_links(instance):
    kmz_link = instance.ows_url + '?f=kmz'

    Link.objects.get_or_create(resource= instance.resourcebase_ptr,
                        url=kmz_link,
                        defaults=dict(
                            extension='kml',
                            name="View in Google Earth",
                            mime='text/xml',
                            link_type='data',
                        )
                    )


    # Create legend.
    legend_url = instance.ows_url + 'legend?f=json'

    Link.objects.get_or_create(resource= instance.resourcebase_ptr,
                        url=legend_url,
                        defaults=dict(
                            extension='json',
                            name=_('Legend'),
                            url=legend_url,
                            mime='application/json',
                            link_type='json',
                        )
                    )



    mercator_bbox = llbbox_to_mercator(instance.bbox)


    # Create thumbnails.

    #FIXME(Ariel): Construct the bbox parameter from the above object.
    # Hardcoding it for now.
    bbox = '0%2C0%2C10018754.17%2C10018754.17'

    thumbnail_remote_url = instance.ows_url + 'export?LAYERS=show%3A0&TRANSPARENT=true&FORMAT=png&BBOX=' + bbox + '&SIZE=200%2C150&F=image&BBOXSR=900913&IMAGESR=900913'
    create_thumbnail(instance, thumbnail_remote_url)
Exemple #4
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    # Transform WGS84 to Mercator.
    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    #^^ start check if layer's dbf file is within limits for conversion
    print 'debug'
    MAX_CONVERT_MB = settings.MAX_DOCUMENT_SIZE
    try:
        layer_dbf = LayerFile.objects.get(upload_session=layer.upload_session, name='dbf')
        layer_dbf_path = settings.PROJECT_ROOT + layer_dbf.file.url
        print layer_dbf_path
        if (os.path.getsize(layer_dbf_path) / 1024 / 1024) > MAX_CONVERT_MB:
            layer_dbf = None
    except LayerFile.DoesNotExist:
        layer_dbf = None
    #^^ end
    
    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        'layer_dbf': layer_dbf #^^
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')

    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #5
0
def layer_metadata(
        request,
        layername,
        template='layers/layer_metadata.html',
        ajax=True):
    layer = _resolve_layer(
        request,
        layername,
        'base.change_resourcebase_metadata',
        _PERMISSION_MSG_METADATA)
    layer_attribute_set = inlineformset_factory(
        Layer,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )
    topic_category = layer.category

    poc = layer.poc
    metadata_author = layer.metadata_author

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.alternate,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.alternate,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(
            settings,
            'DEFAULT_MAP_CRS',
            'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config(request)[1] if la.ows_url is None]

    if request.method == "POST":
        if layer.metadata_uploaded_preserve:  # layer metadata cannot be edited
            out = {
                'success': False,
                'errors': METADATA_UPLOADED_PRESERVE_ERROR
            }
            return HttpResponse(
                json.dumps(out),
                content_type='application/json',
                status=400)

        layer_form = LayerForm(request.POST, instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            request.POST,
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(request.POST, prefix="category_choice_field", initial=int(
            request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
        tkeywords_form = TKeywordForm(
            request.POST,
            prefix="tkeywords")

    else:
        layer_form = LayerForm(instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

        # Keywords from THESAURI management
        layer_tkeywords = layer.tkeywords.all()
        tkeywords_list = ''
        lang = 'en'  # TODO: use user's language
        if layer_tkeywords and len(layer_tkeywords) > 0:
            tkeywords_ids = layer_tkeywords.values_list('id', flat=True)
            if hasattr(settings, 'THESAURI'):
                for el in settings.THESAURI:
                    thesaurus_name = el['name']
                    try:
                        t = Thesaurus.objects.get(identifier=thesaurus_name)
                        for tk in t.thesaurus.filter(pk__in=tkeywords_ids):
                            tkl = tk.keyword.filter(lang=lang)
                            if len(tkl) > 0:
                                tkl_ids = ",".join(
                                    map(str, tkl.values_list('id', flat=True)))
                                tkeywords_list += "," + \
                                    tkl_ids if len(
                                        tkeywords_list) > 0 else tkl_ids
                    except BaseException:
                        tb = traceback.format_exc()
                        logger.error(tb)

        tkeywords_form = TKeywordForm(
            prefix="tkeywords",
            initial={'tkeywords': tkeywords_list})

    if request.method == "POST" and layer_form.is_valid() and attribute_form.is_valid(
    ) and category_form.is_valid() and tkeywords_form.is_valid():
        new_poc = layer_form.cleaned_data['poc']
        new_author = layer_form.cleaned_data['metadata_author']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(
                    request.POST,
                    prefix="poc",
                    instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.is_valid():
                if len(poc_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = poc_form._errors.setdefault(
                        'profile', ErrorList())
                    errors.append(
                        _('You must set a point of contact for this resource'))
                    poc = None
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST, prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.is_valid():
                if len(author_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = author_form._errors.setdefault(
                        'profile', ErrorList())
                    errors.append(
                        _('You must set an author for this resource'))
                    metadata_author = None
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        for form in attribute_form.cleaned_data:
            la = Attribute.objects.get(id=int(form['id'].id))
            la.description = form["description"]
            la.attribute_label = form["attribute_label"]
            la.visible = form["visible"]
            la.display_order = form["display_order"]
            la.save()

        if new_poc is not None or new_author is not None:
            if new_poc is not None:
                layer.poc = new_poc
            if new_author is not None:
                layer.metadata_author = new_author

        new_keywords = [x.strip() for x in layer_form.cleaned_data['keywords']]
        if new_keywords is not None:
            layer.keywords.clear()
            layer.keywords.add(*new_keywords)

        try:
            the_layer = layer_form.save()
        except BaseException:
            tb = traceback.format_exc()
            if tb:
                logger.debug(tb)
            the_layer = layer

        up_sessions = UploadSession.objects.filter(layer=the_layer.id)
        if up_sessions.count() > 0 and up_sessions[0].user != the_layer.owner:
            up_sessions.update(user=the_layer.owner)

        if new_category is not None:
            Layer.objects.filter(id=the_layer.id).update(
                category=new_category
            )

        if getattr(settings, 'SLACK_ENABLED', False):
            try:
                from geonode.contrib.slack.utils import build_slack_message_layer, send_slack_messages
                send_slack_messages(
                    build_slack_message_layer(
                        "layer_edit", the_layer))
            except BaseException:
                print "Could not send slack message."

        if not ajax:
            return HttpResponseRedirect(
                reverse(
                    'layer_detail',
                    args=(
                        layer.service_typename,
                    )))

        message = layer.alternate

        try:
            # Keywords from THESAURI management
            tkeywords_to_add = []
            tkeywords_cleaned = tkeywords_form.clean()
            if tkeywords_cleaned and len(tkeywords_cleaned) > 0:
                tkeywords_ids = []
                for i, val in enumerate(tkeywords_cleaned):
                    try:
                        cleaned_data = [value for key, value in tkeywords_cleaned[i].items(
                        ) if 'tkeywords-tkeywords' in key.lower() and 'autocomplete' not in key.lower()]
                        tkeywords_ids.extend(map(int, cleaned_data[0]))
                    except BaseException:
                        pass

                if hasattr(settings, 'THESAURI'):
                    for el in settings.THESAURI:
                        thesaurus_name = el['name']
                        try:
                            t = Thesaurus.objects.get(
                                identifier=thesaurus_name)
                            for tk in t.thesaurus.all():
                                tkl = tk.keyword.filter(pk__in=tkeywords_ids)
                                if len(tkl) > 0:
                                    tkeywords_to_add.append(tkl[0].keyword_id)
                        except BaseException:
                            tb = traceback.format_exc()
                            logger.error(tb)

            layer.tkeywords.add(*tkeywords_to_add)
        except BaseException:
            tb = traceback.format_exc()
            logger.error(tb)

        return HttpResponse(json.dumps({'message': message}))

    if settings.ADMIN_MODERATE_UPLOADS:
        if not request.user.is_superuser:
            layer_form.fields['is_published'].widget.attrs.update({'disabled': 'true'})
        if not request.user.is_superuser and not request.user.is_staff:
            can_change_metadata = request.user.has_perm(
                'change_resourcebase_metadata',
                layer.get_self_resource())
            try:
                is_manager = request.user.groupmember_set.all().filter(role='manager').exists()
            except:
                is_manager = False
            if not is_manager or not can_change_metadata:
                layer_form.fields['is_approved'].widget.attrs.update({'disabled': 'true'})

    if poc is not None:
        layer_form.fields['poc'].initial = poc.id
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = True
    else:
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = False

    if metadata_author is not None:
        layer_form.fields['metadata_author'].initial = metadata_author.id
        author_form = ProfileForm(prefix="author")
        author_form.hidden = True
    else:
        author_form = ProfileForm(prefix="author")
        author_form.hidden = False

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    viewer = json.dumps(map_obj.viewer_json(
        request.user, access_token, * (NON_WMS_BASE_LAYERS + [maplayer])))

    metadataxsl = False
    if "geonode.contrib.metadataxsl" in settings.INSTALLED_APPS:
        metadataxsl = True

    metadata_author_groups = []
    if request.user.is_superuser or request.user.is_staff:
        metadata_author_groups = GroupProfile.objects.all()
    else:
        all_metadata_author_groups = chain(
            request.user.group_list_all().distinct(),
            GroupProfile.objects.exclude(access="private").exclude(access="public-invite"))
        [metadata_author_groups.append(item) for item in all_metadata_author_groups
            if item not in metadata_author_groups]

    return render_to_response(template, RequestContext(request, {
        "resource": layer,
        "layer": layer,
        "layer_form": layer_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "attribute_form": attribute_form,
        "category_form": category_form,
        "tkeywords_form": tkeywords_form,
        "viewer": viewer,
        "preview": getattr(settings, 'LAYER_PREVIEW_LIBRARY', 'leaflet'),
        "crs": getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'),
        "metadataxsl": metadataxsl,
        "freetext_readonly": getattr(
            settings,
            'FREETEXT_KEYWORDS_READONLY',
            False),
        "metadata_author_groups": metadata_author_groups,
        "GROUP_MANDATORY_RESOURCES":
            getattr(settings, 'GROUP_MANDATORY_RESOURCES', False),
    }))
Exemple #6
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    try:
        user_role = request.GET['user_role']
    except:
        user_role=None

    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    user = request.user
    edit_permit = False
    if layer.owner == user and layer.status in ['DRAFT', 'ACTIVE', 'DENIED']:
        edit_permit = True
    elif user in layer.group.get_managers() and layer.status in ['PENDING', 'ACTIVE', 'DENIED']:
        edit_permit = True

    if not edit_permit and layer.status=='ACTIVE':
        edit_permit = True

    # if the edit request is not valid then just return from here
    if not edit_permit:
        return HttpResponse(
                        loader.render_to_string(
                            '401.html', RequestContext(
                            request, {
                            'error_message': _("You dont have permission to edit this layer.")})), status=401)
        # return  HttpResponse('You dont have permission to edit this layer')

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, limit=10,
                                           offset=offset, filter=filter)
            all_granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, filter=filter)
        except:
            granules = {"features": []}
            all_granules = {"features": []}
    approve_form = ResourceApproveForm()
    deny_form = ResourceDenyForm()
    metadata_field_list = ['owner', 'title', 'date', 'date_type', 'edition', 'abstract', 'purpose',
                           'maintenance_frequency', 'regions', 'restriction_code_type', 'constraints_other', 'license',
                           'language', 'spatial_representation_type', 'resource_type', 'temporal_extent_start',
                           'temporal_extent_end', 'supplemental_information', 'data_quality_statement', 'thumbnail_url',
                            'elevation_regex', 'time_regex', 'keywords',
                           'category']
    if request.user == layer.owner or request.user in layer.group.get_managers():
        if not layer.attributes:
            messages.info(request, 'Please update layer metadata, missing some informations')
        elif not layer.metadata_author:
            messages.info(request, 'Please update layer metadata, missing some informations')
        else:
            for field in metadata_field_list:
                if not getattr(layer, layer._meta.get_field(field).name):
                    messages.info(request, 'Please update layer metadata, missing some informations')
                    break


    # layer_name = layer.service_typename
    # geoserver_user = OGC_SERVER['default']['USER']
    # geoserver_password = OGC_SERVER['default']['PASSWORD']
    # style_url = OGC_SERVER['default']['PUBLIC_LOCATION'] + "rest/layers/" + layer_name + ".json"
    # response1 = requests.get(style_url, auth=HTTPBasicAuth(geoserver_user, geoserver_password))
    # sld_file_name_url = response1.json()['layer']['defaultStyle']['href']
    # response2 = requests.get(sld_file_name_url, auth=HTTPBasicAuth(geoserver_user, geoserver_password))
    # file_name = response2.json()['style']['filename']
    # sld_file_url = OGC_SERVER['default']['PUBLIC_LOCATION'] + "rest/styles/" + file_name
    # sld_content = requests.get(sld_file_url, auth=HTTPBasicAuth(geoserver_user, geoserver_password)).content
    #
    # xlink = ''
    # try:
    #     dict1 = xmltodict.parse(sld_content)
    #     dict2 = dict1['sld:StyledLayerDescriptor']['sld:NamedLayer']['sld:UserStyle']['sld:FeatureTypeStyle']\
    #     ['sld:Rule']['sld:PointSymbolizer']
    #     xlink = dict2['sld:Graphic']['sld:ExternalGraphic']['sld:OnlineResource']['@xlink:href']
    # except:
    #     pass
    xlink = style_chart_legend_color(layer)

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
        "user_role": user_role,
        "approve_form": approve_form,
        "deny_form": deny_form,
        "denied_comments": LayerAuditActivity.objects.filter(layer_submission_activity__layer=layer),
        "status": layer.status,
        "chart_link" : xlink
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')

    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
    def get_context_data(self, **kwargs):
        request = self.request
        if request and 'access_token' in request.session:
            access_token = request.session['access_token']
        else:
            access_token = None

        snapshot = self.kwargs.get('snapshot')

        DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request)

        layers = Layer.objects.all()

        if request.method == 'GET' and 'copy' in request.GET:
            """Prepare context data."""
            request = self.request
            mapid = self.request.GET['copy']

            map_obj = _resolve_map(
                request, mapid, 'base.view_resourcebase', _PERMISSION_MSG_VIEW)

            if snapshot is None:
                config = map_obj.viewer_json(request)
            else:
                config = snapshot_config(snapshot, map_obj, request)
            # list all required layers
            map_layers = MapLayer.objects.filter(
                map_id=mapid).order_by('stack_order')
            context = {
                'config': json.dumps(config),
                'create': False,
                'layers': layers,
                'map': map_obj,
                'map_layers': map_layers,
                'preview': getattr(
                    settings,
                    'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY',
                    '')
            }
            return context
        else:
            if request.method == 'GET':
                params = request.GET
            elif request.method == 'POST':
                params = request.POST
            else:
                return self.render_to_response(status=405)

            if 'layer' in params:
                bbox = None
                map_obj = Map(projection=getattr(
                    settings, 'DEFAULT_MAP_CRS', 'EPSG:3857'))

                for layer_name in params.getlist('layer'):
                    try:
                        layer = _resolve_layer(request, layer_name)
                    except ObjectDoesNotExist:
                        # bad layer, skip
                        continue

                    if not request.user.has_perm(
                            'view_resourcebase',
                            obj=layer.get_self_resource()):
                        # invisible layer, skip inclusion
                        continue

                    layer_bbox = layer.bbox
                    # assert False, str(layer_bbox)
                    if bbox is None:
                        bbox = list(layer_bbox[0:4])
                    else:
                        bbox[0] = min(bbox[0], layer_bbox[0])
                        bbox[1] = min(bbox[1], layer_bbox[1])
                        bbox[2] = max(bbox[2], layer_bbox[2])
                        bbox[3] = max(bbox[3], layer_bbox[3])

                    config = layer.attribute_config()

                    # Add required parameters for GXP lazy-loading
                    config["title"] = layer.title
                    config["queryable"] = True

                    config["srs"] = getattr(settings,
                                            'DEFAULT_MAP_CRS', 'EPSG:3857')
                    config["bbox"] = bbox if config["srs"] != 'EPSG:3857' \
                        else llbbox_to_mercator(
                        [float(coord) for coord in bbox])

                    if layer.storeType == "remoteStore":
                        service = layer.remote_service
                        # Probably not a good idea to send the access token to every remote service.
                        # This should never match, so no access token should be sent to remote services.
                        ogc_server_url = urlparse.urlsplit(
                            ogc_server_settings.PUBLIC_LOCATION).netloc
                        service_url = urlparse.urlsplit(
                            service.base_url).netloc

                        if access_token and ogc_server_url == service_url and \
                                'access_token' not in service.base_url:
                            url = '%s?access_token=%s' % (service.base_url, access_token)
                        else:
                            url = service.base_url
                        map_layers = MapLayer(map=map_obj,
                                              name=layer.typename,
                                              ows_url=layer.ows_url,
                                              layer_params=json.dumps(config),
                                              visibility=True,
                                              source_params=json.dumps({
                                                "ptype": service.ptype,
                                                "remote": True,
                                                "url": url,
                                                "name": service.name,
                                                "title": "[R] %s" % service.title}))
                    else:
                        ogc_server_url = urlparse.urlsplit(
                            ogc_server_settings.PUBLIC_LOCATION).netloc
                        layer_url = urlparse.urlsplit(layer.ows_url).netloc

                        if access_token and ogc_server_url == layer_url and \
                                'access_token' not in layer.ows_url:
                            url = layer.ows_url + '?access_token=' + \
                                  access_token
                        else:
                            url = layer.ows_url
                        map_layers = MapLayer(
                            map=map_obj,
                            name=layer.typename,
                            ows_url=url,
                            # use DjangoJSONEncoder to handle Decimal values
                            layer_params=json.dumps(
                                config,
                                cls=DjangoJSONEncoder),
                            visibility=True
                        )

                if bbox and len(bbox) >= 4:
                    minx, miny, maxx, maxy = [float(coord) for coord in bbox]
                    x = (minx + maxx) / 2
                    y = (miny + maxy) / 2

                    if getattr(settings,
                               'DEFAULT_MAP_CRS', 'EPSG:3857') == "EPSG:4326":
                        center = list((x, y))
                    else:
                        center = list(forward_mercator((x, y)))

                    if center[1] == float('-inf'):
                        center[1] = 0

                    BBOX_DIFFERENCE_THRESHOLD = 1e-5

                    # Check if the bbox is invalid
                    valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
                    valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD

                    if valid_x:
                        width_zoom = math.log(360 / abs(maxx - minx), 2)
                    else:
                        width_zoom = 15

                    if valid_y:
                        height_zoom = math.log(360 / abs(maxy - miny), 2)
                    else:
                        height_zoom = 15

                    map_obj.center_x = center[0]
                    map_obj.center_y = center[1]
                    map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

                map_obj.handle_moderated_uploads()

                if snapshot is None:
                    config = map_obj.viewer_json(request)
                else:
                    config = snapshot_config(snapshot, map_obj, request)

                config['fromLayer'] = True
                context = {
                    'config': json.dumps(config),
                    'create': True,
                    'layers': layers,
                    'map': map_obj,
                    'map_layers': map_layers,
                    'preview': getattr(
                        settings,
                        'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY',
                        '')
                }

            else:
                # list all required layers
                layers = Layer.objects.all()
                context = {
                    'create': True,
                    'layers': layers
                }
            return context
Exemple #8
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    try:
        user_role = request.GET['user_role']
    except:
        user_role=None

    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    user = request.user
    edit_permit = False
    if layer.owner == user and layer.status in ['DRAFT', 'ACTIVE', 'DENIED']:
        edit_permit = True
    elif user in layer.group.get_managers() and layer.status in ['PENDING', 'ACTIVE', 'DENIED']:
        edit_permit = True

    if not edit_permit and layer.status=='ACTIVE':
        edit_permit = True

    # if the edit request is not valid then just return from here
    if not edit_permit:
        return  HttpResponse('you dont have permission to edit this layer')

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, limit=10,
                                           offset=offset, filter=filter)
            all_granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, filter=filter)
        except:
            granules = {"features": []}
            all_granules = {"features": []}
    approve_subjects_file = open("geonode/approve_comment_subjects.txt", "r")
    approve_comment_subjects = [line for line in approve_subjects_file ]
    deney_subjects_file = open("geonode/deny_comment_subject.txt", "r")
    deney_comment_subjects = [line for line in deney_subjects_file ]
    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
        "user_role": user_role,
        "deney_comment_subjects":deney_comment_subjects,
        "approve_comment_subjects": approve_comment_subjects,
        "denied_comments": LayerAuditActivity.objects.filter(layer_submission_activity__layer=layer),
        "status": layer.status
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')

    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #9
0
def data_request_profile(request, pk, template='datarequests/profile_detail.html'):

    request_profile = get_object_or_404(DataRequestProfile, pk=pk)

    if not request.user.is_superuser:
        raise PermissionDenied
    

    #if not request_profile.date:
    #    raise Http404
    
    context_dict={"request_profile": request_profile}
    
    if request_profile.jurisdiction_shapefile:
        layer = request_profile.jurisdiction_shapefile
        # assert False, str(layer_bbox)
        config = layer.attribute_config()
        # Add required parameters for GXP lazy-loading
        layer_bbox = layer.bbox
        bbox = [float(coord) for coord in list(layer_bbox[0:4])]
        srid = layer.srid

        # Transform WGS84 to Mercator.
        config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
        config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

        config["title"] = layer.title
        config["queryable"] = True

        if layer.storeType == "remoteStore":
            service = layer.service
            source_params = {
                "ptype": service.ptype,
                "remote": True,
                "url": service.base_url,
                "name": service.name}
            maplayer = GXPLayer(
                name=layer.typename,
                ows_url=layer.ows_url,
                layer_params=json.dumps(config),
                source_params=json.dumps(source_params))
        else:
            maplayer = GXPLayer(
                name=layer.typename,
                ows_url=layer.ows_url,
                layer_params=json.dumps(config))

        # center/zoom don't matter; the viewer will center on the layer bounds
        map_obj = GXPMap(projection="EPSG:900913")
        NON_WMS_BASE_LAYERS = [
            la for la in default_map_config()[1] if la.ows_url is None]

        metadata = layer.link_set.metadata().filter(
            name__in=settings.DOWNLOAD_FORMATS_METADATA)

        context_dict ["resource"] = layer
        context_dict ["permissions_json"] = _perms_info_json(layer)
        context_dict ["documents"] = get_related_documents(layer)
        context_dict ["metadata"] =  metadata
        context_dict ["is_layer"] = True
        context_dict ["wps_enabled"] = settings.OGC_SERVER['default']['WPS_ENABLED'],

        context_dict["viewer"] = json.dumps(
            map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
        context_dict["preview"] = getattr(
            settings,
            'LAYER_PREVIEW_LIBRARY',
            'leaflet')

        if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
            if layer.storeType == 'dataStore':
                links = layer.link_set.download().filter(
                    name__in=settings.DOWNLOAD_FORMATS_VECTOR)
            else:
                links = layer.link_set.download().filter(
                    name__in=settings.DOWNLOAD_FORMATS_RASTER)
            context_dict["links"] = links

        if settings.SOCIAL_ORIGINS:
            context_dict["social_links"] = build_social_links(request, layer)

    context_dict["request_reject_form"]= DataRequestProfileRejectForm(instance=request_profile)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #10
0
def map_embed_widget(request,
                     mapid,
                     template='leaflet/maps/map_embed_widget.html'):
    """Display code snippet for embedding widget.

    :param request: The request from the frontend.
    :type request: HttpRequest

    :param mapid: The id of the map.
    :type mapid: String

    :return: formatted code.
    """

    map_obj = _resolve_map(request, mapid, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)
    map_bbox = map_obj.bbox_string.split(',')

    map_layers = MapLayer.objects.filter(map_id=mapid).order_by('stack_order')
    layers = []
    for layer in map_layers:
        if layer.group != 'background':
            layers.append(layer)

    if map_obj.srid != 'EPSG:3857':
        map_bbox = [float(coord) for coord in map_bbox]
    else:
        map_bbox = llbbox_to_mercator([float(coord) for coord in map_bbox])

    if map_bbox and len(map_bbox) >= 4:
        minx, miny, maxx, maxy = [float(coord) for coord in map_bbox]
        x = (minx + maxx) / 2
        y = (miny + maxy) / 2

        if getattr(settings, 'DEFAULT_MAP_CRS') == "EPSG:3857":
            center = list((x, y))
        else:
            center = list(forward_mercator((x, y)))

        if center[1] == float('-inf'):
            center[1] = 0

        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        # Check if the bbox is invalid
        valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD
        valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD

        if valid_x:
            width_zoom = math.log(360 / abs(maxx - minx), 2)
        else:
            width_zoom = 15

        if valid_y:
            height_zoom = math.log(360 / abs(maxy - miny), 2)
        else:
            height_zoom = 15

        map_obj.center_x = center[0]
        map_obj.center_y = center[1]
        map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

    context = {'resource': map_obj, 'map_bbox': map_bbox, 'map_layers': layers}
    message = render(request, template, context)
    return HttpResponse(message)
Exemple #11
0
def get_layer_config(request,
                     typename,
                     permission='base.view_resourcebase',
                     msg=_PERMISSION_GENERIC,
                     **kwargs):

    layer = False
    try:
        pprint(typename)
        layer = _resolve_layer(request, typename, "base.view_resourcebase",
                               _PERMISSION_VIEW)
    except Exception as e:
        pprint("Error on resolving layer")
        pprint("Message: " + e.message + "/nType: " + str(type(e)))

    if layer is False:
        raise Http404()

    config = layer.attribute_config()
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, *(NON_WMS_BASE_LAYERS + [maplayer])))

    return context_dict
Exemple #12
0
def layer_metadata(request, layername, template='layers/layer_metadata.html', ajax=True):
    layer = _resolve_layer(
        request,
        layername,
        'base.change_resourcebase_metadata',
        _PERMISSION_MSG_METADATA)
    layer_attribute_set = inlineformset_factory(
        Layer,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )
    topic_category = layer.category

    poc = layer.poc
    metadata_author = layer.metadata_author

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config(request)[1] if la.ows_url is None]

    if request.method == "POST":
        if layer.metadata_uploaded_preserve:  # layer metadata cannot be edited
            out = {
                'success': False,
                'errors': METADATA_UPLOADED_PRESERVE_ERROR
            }
            return HttpResponse(
                json.dumps(out),
                content_type='application/json',
                status=400)

        layer_form = LayerForm(request.POST, instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            request.POST,
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(
                request.POST["category_choice_field"]) if "category_choice_field" in request.POST else None)
        tkeywords_form = TKeywordForm(
            request.POST,
            prefix="tkeywords")

    else:
        layer_form = LayerForm(instance=layer, prefix="resource")
        attribute_form = layer_attribute_set(
            instance=layer,
            prefix="layer_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

        # Keywords from THESAURI management
        layer_tkeywords = layer.tkeywords.all()
        tkeywords_list = ''
        lang = 'en'  # TODO: use user's language
        if layer_tkeywords and len(layer_tkeywords) > 0:
            tkeywords_ids = layer_tkeywords.values_list('id', flat=True)
            if hasattr(settings, 'THESAURI'):
                for el in settings.THESAURI:
                    thesaurus_name = el['name']
                    try:
                        t = Thesaurus.objects.get(identifier=thesaurus_name)
                        for tk in t.thesaurus.filter(pk__in=tkeywords_ids):
                            tkl = tk.keyword.filter(lang=lang)
                            if len(tkl) > 0:
                                tkl_ids = ",".join(map(str, tkl.values_list('id', flat=True)))
                                tkeywords_list += "," + tkl_ids if len(tkeywords_list) > 0 else tkl_ids
                    except:
                        tb = traceback.format_exc()
                        logger.error(tb)

        tkeywords_form = TKeywordForm(
            prefix="tkeywords",
            initial={'tkeywords': tkeywords_list})

    if request.method == "POST" and layer_form.is_valid(
    ) and attribute_form.is_valid() and category_form.is_valid() and tkeywords_form.is_valid():
        new_poc = layer_form.cleaned_data['poc']
        new_author = layer_form.cleaned_data['metadata_author']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(
                    request.POST,
                    prefix="poc",
                    instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.is_valid():
                if len(poc_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = poc_form._errors.setdefault('profile', ErrorList())
                    errors.append(_('You must set a point of contact for this resource'))
                    poc = None
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST, prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.is_valid():
                if len(author_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = author_form._errors.setdefault('profile', ErrorList())
                    errors.append(_('You must set an author for this resource'))
                    metadata_author = None
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        for form in attribute_form.cleaned_data:
            la = Attribute.objects.get(id=int(form['id'].id))
            la.description = form["description"]
            la.attribute_label = form["attribute_label"]
            la.visible = form["visible"]
            la.display_order = form["display_order"]
            la.save()

        if new_poc is not None or new_author is not None:
            if new_poc is not None:
                layer.poc = new_poc
            if new_author is not None:
                layer.metadata_author = new_author

        new_keywords = [x.strip() for x in layer_form.cleaned_data['keywords']]
        if new_keywords is not None:
            layer.keywords.clear()
            layer.keywords.add(*new_keywords)

        try:
            the_layer = layer_form.save()
        except:
            tb = traceback.format_exc()
            if tb:
                logger.debug(tb)
            the_layer = layer

        up_sessions = UploadSession.objects.filter(layer=the_layer.id)
        if up_sessions.count() > 0 and up_sessions[0].user != the_layer.owner:
            up_sessions.update(user=the_layer.owner)

        if new_category is not None:
            Layer.objects.filter(id=the_layer.id).update(
                category=new_category
                )

        if getattr(settings, 'SLACK_ENABLED', False):
            try:
                from geonode.contrib.slack.utils import build_slack_message_layer, send_slack_messages
                send_slack_messages(build_slack_message_layer("layer_edit", the_layer))
            except:
                print "Could not send slack message."

        if not ajax:
            return HttpResponseRedirect(
                reverse(
                    'layer_detail',
                    args=(
                       layer.service_typename,
                    )))

        message = layer.typename

        try:
            # Keywords from THESAURI management
            tkeywords_to_add = []
            tkeywords_cleaned = tkeywords_form.clean()
            if tkeywords_cleaned and len(tkeywords_cleaned) > 0:
                tkeywords_ids = []
                for i, val in enumerate(tkeywords_cleaned):
                    try:
                        cleaned_data = [value for key, value
                                        in tkeywords_cleaned[i].items()
                                        if 'tkeywords-tkeywords' in key.lower() and 'autocomplete' not in key.lower()]
                        tkeywords_ids.extend(map(int, cleaned_data[0]))
                    except:
                        pass

                if hasattr(settings, 'THESAURI'):
                    for el in settings.THESAURI:
                        thesaurus_name = el['name']
                        try:
                            t = Thesaurus.objects.get(identifier=thesaurus_name)
                            for tk in t.thesaurus.all():
                                tkl = tk.keyword.filter(pk__in=tkeywords_ids)
                                if len(tkl) > 0:
                                    tkeywords_to_add.append(tkl[0].keyword_id)
                        except:
                            tb = traceback.format_exc()
                            logger.error(tb)

            layer.tkeywords.add(*tkeywords_to_add)
        except:
            tb = traceback.format_exc()
            logger.error(tb)

        return HttpResponse(json.dumps({'message': message}))

    if poc is not None:
        layer_form.fields['poc'].initial = poc.id
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = True
    else:
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = False

    if metadata_author is not None:
        layer_form.fields['metadata_author'].initial = metadata_author.id
        author_form = ProfileForm(prefix="author")
        author_form.hidden = True
    else:
        author_form = ProfileForm(prefix="author")
        author_form.hidden = False

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    viewer = json.dumps(
        map_obj.viewer_json(request.user, access_token, * (NON_WMS_BASE_LAYERS + [maplayer])))

    metadataxsl = False
    if "geonode.contrib.metadataxsl" in settings.INSTALLED_APPS:
        metadataxsl = True

    return render_to_response(template, RequestContext(request, {
        "resource": layer,
        "layer": layer,
        "layer_form": layer_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "attribute_form": attribute_form,
        "category_form": category_form,
        "tkeywords_form": tkeywords_form,
        "viewer": viewer,
        "preview": getattr(settings, 'LAYER_PREVIEW_LIBRARY', 'leaflet'),
        "crs": getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'),
        "metadataxsl": metadataxsl,
        "freetext_readonly": getattr(settings, 'FREETEXT_KEYWORDS_READONLY', False)
    }))
Exemple #13
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _("You are not permitted to view this layer"))

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True
    if layer.default_style:
        config["styles"] = layer.default_style.name

    if layer.storeType == "remoteStore":
        source_srid = None
        # Only grab the service proj/bbox if it is valid
        if None not in layer.service.bbox[0:4]:
            bbox = [float(coord) for coord in list(layer.service.bbox[0:4])]
            source_srid = layer.service.srid
        # Otherwise try the service directly
        # This is needed since previous services registered
        # did not store the bbox/srid in the model
        else:
            try:
                service_handler = get_service_handler(
                    base_url=layer.service.base_url,
                    service_type=layer.service.type)
                if getattr(service_handler.parsed_service, 'initialExtent',
                           None):
                    bbox[0] = service_handler.parsed_service.initialExtent[
                        'xmin']
                    bbox[1] = service_handler.parsed_service.initialExtent[
                        'ymin']
                    bbox[2] = service_handler.parsed_service.initialExtent[
                        'xmax']
                    bbox[3] = service_handler.parsed_service.initialExtent[
                        'ymax']
                else:
                    logger.info(
                        'Could not retrieve extent from service: {0}'.format(
                            layer.service))
                if getattr(service_handler.parsed_service, 'spatialReference',
                           None):
                    source_srid = \
                        service_handler.parsed_service.spatialReference[
                            'latestWkid']
                else:
                    logger.info(
                        'Could not retrieve srid from service: {0}'.format(
                            layer.service))
            except Exception as e:
                logger.info('Failed to access service endpoint: {0}'.format(
                    layer.service.base_url))
                logger.info('Caught error: {0}'.format(e))
        if source_srid is None:
            source_srid = layer.srid
        target_srid = 3857 if config["srs"] == 'EPSG:900913' else config["srs"]
        reprojected_bbox = bbox_to_projection(bbox,
                                              source_srid=source_srid,
                                              target_srid=target_srid)
        bbox = reprojected_bbox[:4]
        config['bbox'] = [float(coord) for coord in bbox]
        service = layer.service
        source_url = service.base_url
        use_proxy = (callable(uses_proxy_route)
                     and uses_proxy_route(service.base_url))
        components = urlsplit(service.base_url)
        query_params = None
        if components.query:
            query_params = OrderedDict(
                parse_qsl(components.query, keep_blank_values=True))
            removed_query = [
                components.scheme, components.netloc, components.path, None,
                components.fragment
            ]
            source_url = urlunsplit(removed_query)
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": source_url,
            "name": service.name,
            "use_proxy": use_proxy
        }
        if query_params is not None:
            source_params["params"] = query_params
        if layer.alternate is not None:
            config["layerid"] = layer.alternate
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(id=layer.id).update(
            popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                limit=10,
                offset=offset,
                filter=filter)
            all_granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                filter=filter)
        except:
            granules = {"features": []}
            all_granules = {"features": []}

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
    }

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    if bbox is not None:
        minx, miny, maxx, maxy = [float(coord) for coord in bbox]
        x = (minx + maxx) / 2
        y = (miny + maxy) / 2

        if layer.is_remote or getattr(settings, 'DEFAULT_MAP_CRS',
                                      'EPSG:900913') == "EPSG:4326":
            center = list((x, y))
        else:
            center = list(forward_mercator((x, y)))

        if center[1] == float('-inf'):
            center[1] = 0

        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        # Check if the bbox is invalid
        valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD
        valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD

        if valid_x:
            width_zoom = math.log(360 / abs(maxx - minx), 2)
        else:
            width_zoom = 15

        if valid_y:
            height_zoom = math.log(360 / abs(maxy - miny), 2)
        else:
            height_zoom = 15

        map_obj.center_x = center[0]
        map_obj.center_y = center[1]
        map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, access_token,
                            *(default_map_config(request)[1] + [maplayer])))

    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                      'leaflet')
    context_dict["crs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)
    links_view = [
        item for idx, item in enumerate(links)
        if item.url and 'wms' in item.url or 'gwc' in item.url
    ]
    links_download = [
        item for idx, item in enumerate(links)
        if item.url and 'wms' not in item.url and 'gwc' not in item.url
    ]
    for item in links_view:
        if item.url and access_token:
            item.url = "%s&access_token=%s&time=%s" % \
                       (item.url, access_token, "0/9999")
    for item in links_download:
        if item.url and access_token:
            item.url = "%s&access_token=%s" % (item.url, access_token)

    if request.user.has_perm('view_resourcebase', layer.get_self_resource()):
        context_dict["links"] = links_view
    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links_download"] = links_download

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #14
0
    # Transform WGS84 to Mercator.
    #config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    #config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])
    #config["title"] = layer.title
    #config["queryable"] = True
=======
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    if hasattr(layer, 'srid'):
        config['crs'] = {
            'type': 'name',
            'properties': layer.srid
        }
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True
>>>>>>> e7605f5980062789a1dfe0321b74882a9af32ed6

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.alternate,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
def layer_detail(request, layername, template='layers/layer_detail.html'):

    #if template:
        #logger.warning('Template param not expected: %s', template)

    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    # Transform WGS84 to Mercator.
    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    granule_filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            granule_filter = None
            try:
                if request.GET["filter"]:
                    granule_filter = request.GET["filter"]
            except:
                pass

            schema = cat.mosaic_coverage_schema(coverages['coverages']['coverage'][0]['name'], store)
            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, limit=10, offset=offset, filter=granule_filter)
            all_granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, filter=granule_filter)

        except:
            granules = {"features": []}
            all_granules = {"features": []}

            import traceback
            traceback.print_exc()

        #print (' +++++++++++++++++++++++++++++++++++++++++ \n' + str(granules) + '\n +++++++++++++++++++++++++++++++++++++++++ ')

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "is_owner": request.user == layer.owner,
        "is_superuser": request.user.is_superuser,

        "granules": granules,
        "all_granules": all_granules,
        "filter": granule_filter,
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')

    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    #if request.user.is_superuser:
        #logger.debug("Dispatching to admin page")
    #else:
        #logger.debug("Dispatching to user page")

    #template = 'layers/layer_detail_admin.html' if request.user.is_superuser else 'layers/layer_detail_user.html'

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #16
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.alternate,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.alternate,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    layer.view_count_up(request.user)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(
            settings,
            'DEFAULT_MAP_CRS',
            'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config(request)[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except BaseException:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                limit=10,
                offset=offset,
                filter=filter)
            all_granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'], store, filter=filter)
        except BaseException:
            granules = {"features": []}
            all_granules = {"features": []}

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
    }

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    context_dict["viewer"] = json.dumps(map_obj.viewer_json(
        request.user, access_token, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')
    context_dict["crs"] = getattr(
        settings,
        'DEFAULT_MAP_CRS',
        'EPSG:900913')

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)
    links_view = [item for idx, item in enumerate(links) if
                  item.url and 'wms' in item.url or 'gwc' in item.url]
    links_download = [item for idx, item in enumerate(
        links) if item.url and 'wms' not in item.url and 'gwc' not in item.url]
    for item in links_view:
        if item.url and access_token and 'access_token' not in item.url:
            params = {'access_token': access_token}
            item.url = Request('GET', item.url, params=params).prepare().url
    for item in links_download:
        if item.url and access_token and 'access_token' not in item.url:
            params = {'access_token': access_token}
            item.url = Request('GET', item.url, params=params).prepare().url

    if request.user.has_perm('view_resourcebase', layer.get_self_resource()):
        context_dict["links"] = links_view
    if request.user.has_perm(
        'download_resourcebase',
            layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links_download"] = links_download

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)
    layers_names = layer.alternate
    try:
        if 'geonode' in layers_names:
            workspace, name = layers_names.split(':', 1)
        else:
            name = layers_names
    except:
        print "Can not identify workspace type and layername"

    context_dict["layer_name"] = json.dumps(layers_names)

    try:
        # get type of layer (raster or vector)
        if layer.storeType == 'coverageStore':
            context_dict["layer_type"] = "raster"
        elif layer.storeType == 'dataStore':
            context_dict["layer_type"] = "vector"

            location = "{location}{service}".format(** {
                'location': settings.OGC_SERVER['default']['LOCATION'],
                'service': 'wms',
            })
            # get schema for specific layer
            username = settings.OGC_SERVER['default']['USER']
            password = settings.OGC_SERVER['default']['PASSWORD']
            schema = get_schema(location, name, username=username, password=password)

            # get the name of the column which holds the geometry
            if 'the_geom' in schema['properties']:
                schema['properties'].pop('the_geom', None)
            elif 'geom' in schema['properties']:
                schema['properties'].pop("geom", None)

            # filter the schema dict based on the values of layers_attributes
            layer_attributes_schema = []
            for key in schema['properties'].keys():
                    layer_attributes_schema.append(key)

            filtered_attributes = layer_attributes_schema
            context_dict["schema"] = schema
            context_dict["filtered_attributes"] = filtered_attributes

    except:
        print "Possible error with OWSLib. Turning all available properties to string"

    # maps owned by user needed to fill the "add to existing map section" in template
    if request.user.is_authenticated():
        context_dict["maps"] = Map.objects.filter(owner=request.user)
    return render_to_response(template, RequestContext(request, context_dict))
Exemple #17
0
def data_request_detail(request, pk, template='datarequests/data_detail.html'):

    data_request = get_object_or_404(DataRequest, pk=pk)

    if not request.user.is_superuser and not data_request.profile == request.user:
        return HttpResponseRedirect('/forbidden')

    context_dict={"data_request": data_request}
    context_dict['data_types'] = data_request.data_type.names()
    context_dict['sucs']=data_request.suc.names()
    context_dict['max_ftp_size']=settings.MAX_FTP_SIZE
    pprint(context_dict ['sucs'])
    pprint("dr.pk="+str(data_request.pk))

    if data_request.profile:
        context_dict['profile'] = data_request.profile

    if data_request.profile_request:
        context_dict['profile_request'] = data_request.profile_request

    if data_request.jurisdiction_shapefile:
         layer = data_request.jurisdiction_shapefile
         # assert False, str(layer_bbox)
         config = layer.attribute_config()
         # Add required parameters for GXP lazy-loading
         layer_bbox = layer.bbox
         bbox = [float(coord) for coord in list(layer_bbox[0:4])]
         srid = layer.srid

         # Transform WGS84 to Mercator.
         config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
         config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

         config["title"] = layer.title
         config["queryable"] = True

         if layer.storeType == "remoteStore":
             service = layer.service
             source_params = {
                 "ptype": service.ptype,
                 "remote": True,
                 "url": service.base_url,
                 "name": service.name}
             maplayer = GXPLayer(
                 name=layer.typename,
                 ows_url=layer.ows_url,
                 layer_params=json.dumps(config),
                 source_params=json.dumps(source_params))
         else:
             maplayer = GXPLayer(
                 name=layer.typename,
                 ows_url=layer.ows_url,
                 layer_params=json.dumps(config))

         # center/zoom don't matter; the viewer will center on the layer bounds
         map_obj = GXPMap(projection="EPSG:900913")
         NON_WMS_BASE_LAYERS = [
             la for la in default_map_config()[1] if la.ows_url is None]

         metadata = layer.link_set.metadata().filter(
             name__in=settings.DOWNLOAD_FORMATS_METADATA)

         context_dict ["resource"] = layer
         context_dict ["permissions_json"] = _perms_info_json(layer)
         context_dict ["documents"] = get_related_documents(layer)
         context_dict ["metadata"] =  metadata
         context_dict ["is_layer"] = True
         context_dict ["wps_enabled"] = settings.OGC_SERVER['default']['WPS_ENABLED'],

         context_dict["viewer"] = json.dumps(
             map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
         context_dict["preview"] = getattr(
             settings,
             'LAYER_PREVIEW_LIBRARY',
             'leaflet')

         if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
             if layer.storeType == 'dataStore':
                 links = layer.link_set.download().filter(
                     name__in=settings.DOWNLOAD_FORMATS_VECTOR)
             else:
                 links = layer.link_set.download().filter(
                     name__in=settings.DOWNLOAD_FORMATS_RASTER)
             context_dict["links"] = links

    context_dict["request_reject_form"]= DataRequestRejectForm(instance=data_request)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #18
0
def map_embed_widget(request, mapid,
                     template='leaflet/maps/map_embed_widget.html'):
    """Display code snippet for embedding widget.

    :param request: The request from the frontend.
    :type request: HttpRequest

    :param mapid: The id of the map.
    :type mapid: String

    :return: formatted code.
    """
    map_obj = _resolve_map(request,
                           mapid,
                           'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)
    map_bbox = map_obj.bbox_string.split(',')

    # Sanity Checks
    for coord in map_bbox:
        if not coord:
            return

    map_layers = MapLayer.objects.filter(
        map_id=mapid).order_by('stack_order')
    layers = []
    for layer in map_layers:
        if layer.group != 'background':
            layers.append(layer)

    if map_obj.srid != 'EPSG:3857':
        map_bbox = [float(coord) for coord in map_bbox]
    else:
        map_bbox = llbbox_to_mercator([float(coord) for coord in map_bbox])

    if map_bbox and len(map_bbox) >= 4:
        minx, miny, maxx, maxy = [float(coord) for coord in map_bbox]
        x = (minx + maxx) / 2
        y = (miny + maxy) / 2

        if getattr(settings, 'DEFAULT_MAP_CRS') == "EPSG:3857":
            center = list((x, y))
        else:
            center = list(forward_mercator((x, y)))

        if center[1] == float('-inf'):
            center[1] = 0

        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        # Check if the bbox is invalid
        valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
        valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD

        if valid_x:
            width_zoom = math.log(360 / abs(maxx - minx), 2)
        else:
            width_zoom = 15

        if valid_y:
            height_zoom = math.log(360 / abs(maxy - miny), 2)
        else:
            height_zoom = 15

        map_obj.center_x = center[0]
        map_obj.center_y = center[1]
        map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

    context = {
        'resource': map_obj,
        'map_bbox': map_bbox,
        'map_layers': layers
    }
    message = render(request, template, context)
    return HttpResponse(message)
Exemple #19
0
def new_map_config(request):
    '''
    View that creates a new map.

    If the query argument 'copy' is given, the initial map is
    a copy of the map with the id specified, otherwise the
    default map configuration is used.  If copy is specified
    and the map specified does not exist a 404 is returned.
    '''
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config()

    if request.method == 'GET' and 'copy' in request.GET:
        mapid = request.GET['copy']
        if not mapid.isdigit():
            map_obj = _resolve_map_custom(request, mapid, 'urlsuffix',
                                          'base.view_resourcebase')
        else:
            map_obj = _resolve_map(request, mapid, 'base.view_resourcebase')

        map_obj.abstract = DEFAULT_ABSTRACT
        map_obj.title = DEFAULT_TITLE
        if request.user.is_authenticated(): map_obj.owner = request.user
        config = map_obj.viewer_json(request.user)
        del config['id']
    else:
        if request.method == 'GET':
            params = request.GET
        elif request.method == 'POST':
            params = request.POST
        else:
            return HttpResponse(status=405)

        if 'layer' in params:
            bbox = None
            map_obj = Map(projection="EPSG:900913")
            layers = []
            for layer_name in params.getlist('layer'):
                try:
                    layer = _resolve_layer(request, layer_name)
                except ObjectDoesNotExist:
                    # bad layer, skip
                    continue

                if not request.user.has_perm('view_resourcebase',
                                             obj=layer.get_self_resource()):
                    # invisible layer, skip inclusion
                    continue

                layer_bbox = layer.bbox
                # assert False, str(layer_bbox)
                if bbox is None:
                    bbox = list(layer_bbox[0:4])
                else:
                    bbox[0] = min(bbox[0], layer_bbox[0])
                    bbox[1] = max(bbox[1], layer_bbox[1])
                    bbox[2] = min(bbox[2], layer_bbox[2])
                    bbox[3] = max(bbox[3], layer_bbox[3])

                config = layer.attribute_config()

                #Add required parameters for GXP lazy-loading
                config["srs"] = layer.srid
                config["title"] = layer.title
                config["bbox"] =  [float(coord) for coord in bbox] \
                    if layer.srid == "EPSG:4326" else llbbox_to_mercator([float(coord) for coord in bbox])
                config["queryable"] = True

                if layer.storeType == "remoteStore":
                    service = layer.service
                    maplayer = MapLayer(map=map_obj,
                                        name=layer.typename,
                                        ows_url=layer.ows_url,
                                        layer_params=json.dumps(config),
                                        visibility=True,
                                        source_params=json.dumps({
                                            "ptype":
                                            service.ptype,
                                            "remote":
                                            True,
                                            "url":
                                            service.base_url,
                                            "name":
                                            service.name
                                        }))
                else:
                    maplayer = MapLayer(map=map_obj,
                                        name=layer.typename,
                                        ows_url=layer.ows_url,
                                        layer_params=json.dumps(config),
                                        visibility=True)

                layers.append(maplayer)

            if bbox is not None:
                minx, miny, maxx, maxy = [float(c) for c in bbox]
                x = (minx + maxx) / 2
                y = (miny + maxy) / 2

                center = list(forward_mercator((x, y)))
                if center[1] == float('-inf'):
                    center[1] = 0

                BBOX_DIFFERENCE_THRESHOLD = 1e-5

                #Check if the bbox is invalid
                valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD
                valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD

                if valid_x:
                    width_zoom = math.log(360 / abs(maxx - minx), 2)
                else:
                    width_zoom = 15

                if valid_y:
                    height_zoom = math.log(360 / abs(maxy - miny), 2)
                else:
                    height_zoom = 15

                map_obj.center_x = center[0]
                map_obj.center_y = center[1]
                map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

            config = map_obj.viewer_json(request.user,
                                         *(DEFAULT_BASE_LAYERS + layers))
            config['fromLayer'] = True
        else:
            config = DEFAULT_MAP_CONFIG
    return json.dumps(config)
Exemple #20
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')

    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #21
0
def layer_detail(request, layername, template='layers/layer_detail.html'):

    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)
    layer_bbox = layer.bbox
    # assert False, str(layer_bbox)
    bbox = list(layer_bbox[0:4])
    config = layer.attribute_config()

    #Add required parameters for GXP lazy-loading
    config["srs"] = layer.srid
    config["title"] = layer.title
    config["bbox"] =  [float(coord) for coord in bbox] \
        if layer.srid == "EPSG:4326" else llbbox_to_mercator([float(coord) for coord in bbox])

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking.
    Layer.objects.filter(id=layer.id).update(
        popular_count=layer.popular_count + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, *(NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                      'leaflet')

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)

    context_dict["links"] = links

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #22
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config(request)[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, limit=10,
                                           offset=offset, filter=filter)
            all_granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, filter=filter)
        except:
            granules = {"features": []}
            all_granules = {"features": []}

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
    }

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, access_token, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')
    context_dict["crs"] = getattr(
        settings,
        'DEFAULT_MAP_CRS',
        'EPSG:900913')

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)
    links_view = [item for idx, item in enumerate(links) if
                  item.url and 'wms' in item.url or 'gwc' in item.url]
    links_download = [item for idx, item in enumerate(links) if
                      item.url and 'wms' not in item.url and 'gwc' not in item.url]
    for item in links_view:
        if item.url and access_token and 'access_token' not in item.url:
            item.url = "%s&access_token=%s" % (item.url, access_token)
    for item in links_download:
        if item.url and access_token and 'access_token' not in item.url:
            item.url = "%s&access_token=%s" % (item.url, access_token)

    if request.user.has_perm('view_resourcebase', layer.get_self_resource()):
        context_dict["links"] = links_view
    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links_download"] = links_download

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #23
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    # tile shapefile ng settings.tile
    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)

    # check if problematic in geoserver
    cat = gs_catalog
    try:
        gs_layer = cat.get_layer(layername)
        gs_layer.resource.latlon_bbox
    except:
        print 'GEOSERVER LAYER ERROR'
        return HttpResponse(loader.render_to_string(
            'layers/layer_error.html',
            RequestContext(request, {'error_message': _("Error in layer.")})),
                            status=404)
        # return HttpResponse(status=404)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()
    # print layername
    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(id=layer.id).update(
            popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }
    context_dict["phillidar2keyword"] = "PhilLiDAR2"
    context_dict["phillidar1keyword"] = "UPD"

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, *(NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                      'leaflet')

    #pprint('CONTEXT DICTIONARY')
    #pprint(context_dict)
    #pprint('END')
    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    if request.method == 'POST':
        #pprint(request.POST)
        form = AnonDownloaderForm(request.POST)
        out = {}
        if form.is_valid():
            #pprint(form)
            out['success'] = True
            anondownload = form.save()
            anondownload.anon_layer = Layer.objects.get(
                typename=layername).typename
            anondownload.save()
        else:
            #pprint(form)
            errormsgs = []
            for e in form.errors.values():
                errormsgs.extend([escape(v) for v in e])
            out['success'] = False
            out['errors'] = form.errors
            out['errormsgs'] = errormsgs
        if out['success']:
            status_code = 200
        else:
            status_code = 400
        # Handle form
        pprint(status_code)
        return HttpResponse(status=status_code)
    else:
        # Render form
        form = AnonDownloaderForm()
    context_dict["anon_form"] = form
    context_dict["layername"] = layername
    return render_to_response(template, RequestContext(request, context_dict))
Exemple #24
0
    def get_context_data(self, **kwargs):
        request = self.request
        if request and 'access_token' in request.session:
            access_token = request.session['access_token']
        else:
            access_token = None

        DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request)

        layers = Layer.objects.all()

        if request.method == 'GET' and 'copy' in request.GET:
            """Prepare context data."""
            request = self.request
            mapid = self.request.GET['copy']

            map_obj = _resolve_map(request, mapid, 'base.view_resourcebase',
                                   _PERMISSION_MSG_VIEW)

            config = map_obj.viewer_json(request)

            # list all required layers
            map_layers = MapLayer.objects.filter(
                map_id=mapid).order_by('stack_order')
            context = {
                'config':
                json.dumps(config),
                'create':
                False,
                'layers':
                layers,
                'map':
                map_obj,
                'map_layers':
                map_layers,
                'preview':
                getattr(settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY',
                        'leaflet')
            }
            return context
        else:
            if request.method == 'GET':
                params = request.GET
            elif request.method == 'POST':
                params = request.POST
            else:
                return self.render_to_response(status=405)

            if 'layer' in params:
                bbox = None
                map_obj = Map(projection=getattr(settings, 'DEFAULT_MAP_CRS',
                                                 'EPSG:3857'))

                for layer_name in params.getlist('layer'):
                    try:
                        layer = _resolve_layer(request, layer_name)
                    except ObjectDoesNotExist:
                        # bad layer, skip
                        continue

                    if not request.user.has_perm(
                            'view_resourcebase',
                            obj=layer.get_self_resource()):
                        # invisible layer, skip inclusion
                        continue

                    layer_bbox = layer.bbox
                    # assert False, str(layer_bbox)
                    if bbox is None:
                        bbox = list(layer_bbox[0:4])
                    else:
                        bbox[0] = min(bbox[0], layer_bbox[0])
                        bbox[1] = min(bbox[1], layer_bbox[1])
                        bbox[2] = max(bbox[2], layer_bbox[2])
                        bbox[3] = max(bbox[3], layer_bbox[3])

                    config = layer.attribute_config()

                    # Add required parameters for GXP lazy-loading
                    config["title"] = layer.title
                    config["queryable"] = True

                    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS',
                                            'EPSG:3857')
                    config["bbox"] = bbox if config["srs"] != 'EPSG:3857' \
                        else llbbox_to_mercator(
                        [float(coord) for coord in bbox])

                    if layer.storeType == "remoteStore":
                        service = layer.remote_service
                        # Probably not a good idea to send the access token to every remote service.
                        # This should never match, so no access token should be sent to remote services.
                        ogc_server_url = urlsplit(
                            ogc_server_settings.PUBLIC_LOCATION).netloc
                        service_url = urlsplit(service.base_url).netloc

                        if access_token and ogc_server_url == service_url and \
                                'access_token' not in service.base_url:
                            url = '%s?access_token=%s' % (service.base_url,
                                                          access_token)
                        else:
                            url = service.base_url
                        map_layers = MapLayer(map=map_obj,
                                              name=layer.typename,
                                              ows_url=layer.ows_url,
                                              layer_params=json.dumps(config),
                                              visibility=True,
                                              source_params=json.dumps({
                                                  "ptype":
                                                  service.ptype,
                                                  "remote":
                                                  True,
                                                  "url":
                                                  url,
                                                  "name":
                                                  service.name,
                                                  "title":
                                                  "[R] %s" % service.title
                                              }))
                    else:
                        ogc_server_url = urlsplit(
                            ogc_server_settings.PUBLIC_LOCATION).netloc
                        layer_url = urlsplit(layer.ows_url).netloc

                        if access_token and ogc_server_url == layer_url and \
                                'access_token' not in layer.ows_url:
                            url = layer.ows_url + '?access_token=' + \
                                access_token
                        else:
                            url = layer.ows_url
                        map_layers = MapLayer(
                            map=map_obj,
                            name=layer.typename,
                            ows_url=url,
                            # use DjangoJSONEncoder to handle Decimal values
                            layer_params=json.dumps(config,
                                                    cls=DjangoJSONEncoder),
                            visibility=True)

                if bbox and len(bbox) >= 4:
                    minx, miny, maxx, maxy = [float(coord) for coord in bbox]
                    x = (minx + maxx) / 2
                    y = (miny + maxy) / 2

                    if getattr(settings, 'DEFAULT_MAP_CRS',
                               'EPSG:3857') == "EPSG:4326":
                        center = list((x, y))
                    else:
                        center = list(forward_mercator((x, y)))

                    if center[1] == float('-inf'):
                        center[1] = 0

                    BBOX_DIFFERENCE_THRESHOLD = 1e-5

                    # Check if the bbox is invalid
                    valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD
                    valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD

                    if valid_x:
                        width_zoom = math.log(360 / abs(maxx - minx), 2)
                    else:
                        width_zoom = 15

                    if valid_y:
                        height_zoom = math.log(360 / abs(maxy - miny), 2)
                    else:
                        height_zoom = 15

                    map_obj.center_x = center[0]
                    map_obj.center_y = center[1]
                    map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

                map_obj.handle_moderated_uploads()

                config = map_obj.viewer_json(request)
                config['fromLayer'] = True
                context = {
                    'config':
                    json.dumps(config),
                    'create':
                    True,
                    'layers':
                    layers,
                    'map':
                    map_obj,
                    'map_layers':
                    map_layers,
                    'preview':
                    getattr(settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY',
                            'leaflet')
                }

            else:
                # list all required layers
                layers = Layer.objects.all()
                context = {'create': True, 'layers': layers}
            return context
Exemple #25
0
def gxp2wm(config, map_obj=None):
    """
    Convert a GeoNode map json or string config to the WorldMap client format.
    """
    config_is_string = False
    # let's first see if it is a string, in which case must be converted to json
    if isinstance(config, basestring):
        config = json.loads(config)
        config_is_string = True

    if map_obj:
        config['id'] = map_obj.id

    topics = TopicCategory.objects.all()
    topicArray = []
    for topic in topics:
        topicArray.append([topic.identifier, topic.gn_description])
    topicArray.append(['General', 'General'])
    groups = set()

    config['topic_categories'] = topicArray

    config['proxy'] = '/proxy/?url='

    # TODO check permissions here
    config['edit_map'] = True

    # 3 different layer types
    #
    # 1. background layer: group: background, ows_url: None
    #
    # 2. WM local layer:
    #    ows_url: http://localhost:8080/geoserver/wms,
    #    layer_params = {"selected": true, "title": "camer_hyd_basins_vm0_2007",
    #       "url": "http://localhost:8080/geoserver/wms",
    #       "tiled": true, "detail_url": "http://worldmap.harvard.edu/data/geonode:camer_hyd_basins_vm0_2007",
    #       "local": true,
    #       "llbbox": [-94.549682617, 9.553222656, -82.972412109, 18.762207031]}
    #
    # 3. WM remote layer (HH):
    #    ows_url:
    #    http://192.168.33.15:8002/registry/hypermap/layer/13ff2fea-d479-4fc7-87a6-3eab7d349def/map/wmts/market/default_grid/$%7Bz%7D/$%7Bx%7D/$%7By%7D.png
    #    layer_params = {"title": "market", "selected": true,
    #       "detail_url": "http://192.168.33.15:8002/registry/hypermap/layer/13ff2fea-d479-4fc7-87a6-3eab7d349def/",
    #       "local": false}

    # let's detect WM or HH layers and alter configuration as needed
    bbox = [-180, -90, 180, 90]
    valid_layers = []
    for layer_config in config['map']['layers']:
        is_valid = True
        is_wm = False
        is_hh = False
        if 'source' not in layer_config:
            is_valid = False
            print 'Skipping this layer as it is missing source... %s' % layer_config
        else:
            source_id = layer_config['source']
            source = config['sources'][source_id]
            if 'url' in source:
                source_url = source['url']
                # hack
                source_url = source_url.replace('https', 'http')
                if settings.GEOSERVER_PUBLIC_LOCATION in source_url:
                    config['sources'][source_id]['url'] = source_url
                    if 'name' in layer_config:
                        is_wm = True
                if 'registry/hypermap' in source_url:
                    is_hh = True
            group = 'General'
            layer_config['tiled'] = True
            if is_wm:
                source = layer_config['source']
                config['sources'][source]['ptype'] = 'gxp_gnsource'
                config['sources'][source]['url'] = config['sources'][source]['url'].replace('ows', 'wms')
                layer_config['local'] = True
                layer_config['queryable'] = True
                alternate = layer_config['name']
                layer = None
                try:
                    layer = Layer.objects.get(alternate=alternate)
                except Layer.DoesNotExist:
                    is_valid = False
                    print 'Skipping this layer as it is not existing in GeoNode... %s' % layer_config
                if layer:
                    layer_config['attributes'] = (get_layer_attributes(layer))
                    layer_config['url'] = layer.ows_url.replace('ows', 'wms')
                    if 'styles' not in layer_config:
                        if layer.default_style:
                            layer_config['styles'] = [layer.default_style.name, ]
                        else:
                            if layer.styles.all().count() > 0:
                                layer_config['styles'] = [layer.styles.all()[0].name, ]
                    else:
                        if type(layer_config['styles']) == unicode:
                            try:
                                layer_config['styles'] = ast.literal_eval(layer_config['styles'])
                            except: # noqa
                                layer_config['styles'] = [layer_config['styles'], ]
                    if 'styles' not in layer_config:
                        is_valid = False
                        print 'Skipping this layer as it has not a style... %s' % layer_config
                    if layer.category:
                        group = layer.category.gn_description
                    layer_config["srs"] = getattr(
                        settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
                    bbox = layer.bbox[:-1]
                    # WorldMap GXP use a different bbox representation than GeoNode
                    bbox = [bbox[0], bbox[2], bbox[1], bbox[3]]
                    layer_config["bbox"] = [float(coord) for coord in bbox] if layer_config["srs"] != 'EPSG:900913' \
                        else llbbox_to_mercator([float(coord) for coord in bbox])
            if is_hh:
                layer_config['local'] = False
                layer_config['styles'] = ''
                hh_url = (
                            '%smap/wmts/%s/default_grid/${z}/${x}/${y}.png' %
                            (layer_config['detail_url'], layer_config['name'])
                )
                layer_config['url'] = hh_url
            if is_wm or is_hh:
                # bbox
                layer_config['llbbox'] = [float(coord) for coord in bbox]
                # group
                if 'group' not in layer_config:
                    layer_config['group'] = group
                else:
                    group = layer_config['group']
                if group not in groups:
                    groups.add(group)
                # let's make sure the group exists in topicArray (it could be a custom group create from user in GXP)
                is_in_topicarray = False
                for cat in topicArray:
                    if group == cat[1]:
                        is_in_topicarray = True
                if not is_in_topicarray:
                    topicArray.append([group, group])
        if is_valid:
            valid_layers.append(layer_config)

    config['map']['layers'] = valid_layers
    config['map']['groups'] = []

    # about and groups from existing map
    if map_obj:
        config['about']['introtext'] = map_obj.extmap.content_map
        config['about']['urlsuffix'] = map_obj.urlsuffix
        if map_obj.extmap.group_params:
            config["map"]["groups"] = uniqifydict(json.loads(map_obj.extmap.group_params), 'group')
    else:
        # TODO check if this works with different languages
        config['about']['introtext'] = unicode(settings.DEFAULT_MAP_ABSTRACT)

    if not [d for d in config['map']['groups'] if d['group'] == group]:
        for group in groups:
            config['map']['groups'].append({"expanded": "true", "group": group})

    if config_is_string:
        config = json.dumps(config)

    return config
Exemple #26
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(id=layer.id).update(
            popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, *(NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                      'leaflet')

    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #27
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _("You are not permitted to view this layer"))

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True
    if layer.default_style:
        config["styles"] = layer.default_style.name

    if layer.storeType == "remoteStore":
        source_srid = None
        # Only grab the service proj/bbox if it is valid
        if None not in layer.service.bbox[0:4]:
            bbox = [float(coord) for coord in list(layer.service.bbox[0:4])]
            source_srid = layer.service.srid
        # Otherwise try the service directly
        # This is needed since previous services registered
        # did not store the bbox/srid in the model
        else:
            try:
                service_handler = get_service_handler(
                    base_url=layer.service.base_url,
                    service_type=layer.service.type)
                if getattr(service_handler.parsed_service, 'initialExtent',
                           None):
                    bbox[0] = service_handler.parsed_service.initialExtent[
                        'xmin']
                    bbox[1] = service_handler.parsed_service.initialExtent[
                        'ymin']
                    bbox[2] = service_handler.parsed_service.initialExtent[
                        'xmax']
                    bbox[3] = service_handler.parsed_service.initialExtent[
                        'ymax']
                else:
                    logger.info('Could not retrieve extent from service: {0}'
                                .format(layer.service))
                if getattr(service_handler.parsed_service, 'spatialReference',
                           None):
                    source_srid = \
                        service_handler.parsed_service.spatialReference[
                            'latestWkid']
                else:
                    logger.info('Could not retrieve srid from service: {0}'
                                .format(layer.service))
            except Exception as e:
                logger.info('Failed to access service endpoint: {0}'
                            .format(layer.service.base_url))
                logger.info('Caught error: {0}'.format(e))
        if source_srid is None:
            source_srid = layer.srid
        target_srid = 3857 if config["srs"] == 'EPSG:900913' else config["srs"]
        reprojected_bbox = bbox_to_projection(bbox, source_srid=source_srid,
                                              target_srid=target_srid)
        bbox = reprojected_bbox[:4]
        config['bbox'] = [float(coord) for coord in bbox]
        service = layer.service
        source_url = service.base_url
        use_proxy = (callable(uses_proxy_route) and
                     uses_proxy_route(service.base_url))
        components = urlsplit(service.base_url)
        query_params = None
        if components.query:
            query_params = OrderedDict(
                parse_qsl(components.query, keep_blank_values=True))
            removed_query = [components.scheme, components.netloc,
                             components.path,
                             None, components.fragment]
            source_url = urlunsplit(removed_query)
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": source_url,
            "name": service.name,
            "use_proxy": use_proxy}
        if query_params is not None:
            source_params["params"] = query_params
        if layer.alternate is not None:
            config["layerid"] = layer.alternate
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'], store, limit=10,
                offset=offset, filter=filter)
            all_granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'], store,
                filter=filter)
        except:
            granules = {"features": []}
            all_granules = {"features": []}

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
    }

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    if bbox is not None:
        minx, miny, maxx, maxy = [float(coord) for coord in bbox]
        x = (minx + maxx) / 2
        y = (miny + maxy) / 2

        if layer.is_remote or getattr(settings, 'DEFAULT_MAP_CRS',
                                      'EPSG:900913') == "EPSG:4326":
            center = list((x, y))
        else:
            center = list(forward_mercator((x, y)))

        if center[1] == float('-inf'):
            center[1] = 0

        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        # Check if the bbox is invalid
        valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
        valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD

        if valid_x:
            width_zoom = math.log(360 / abs(maxx - minx), 2)
        else:
            width_zoom = 15

        if valid_y:
            height_zoom = math.log(360 / abs(maxy - miny), 2)
        else:
            height_zoom = 15

        map_obj.center_x = center[0]
        map_obj.center_y = center[1]
        map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, access_token,
                            *(default_map_config(request)[1] + [maplayer])))

    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')
    context_dict["crs"] = getattr(
        settings,
        'DEFAULT_MAP_CRS',
        'EPSG:900913')

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)
    links_view = [item for idx, item in enumerate(links) if
                  item.url and 'wms' in item.url or 'gwc' in item.url]
    links_download = [item for idx, item in enumerate(links) if
                      item.url and 'wms' not in item.url and
                      'gwc' not in item.url]
    for item in links_view:
        if item.url and access_token:
            item.url = "%s&access_token=%s&time=%s" % \
                       (item.url, access_token, "0/9999")
    for item in links_download:
        if item.url and access_token:
            item.url = "%s&access_token=%s" % (item.url, access_token)

    if request.user.has_perm('view_resourcebase', layer.get_self_resource()):
        context_dict["links"] = links_view
    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links_download"] = links_download

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
def create_from_layer_list(user, layers, title, abstract):

    newmap = Map()

    """Copied from maps.models and fixed
    """
    newmap.owner = user
    newmap.title = title
    newmap.abstract = abstract
    newmap.projection = "EPSG:900913"
    newmap.zoom = 0
    newmap.center_x = 0
    newmap.center_y = 0
    #bbox = None
    index = 0
    incr_bbox = None

    DEFAULT_BASE_LAYERS = settings.MAP_BASELAYERS

    is_published = True
    if settings.RESOURCE_PUBLISHING:
        is_published = False
    newmap.is_published = is_published

    # Save the map in order to create an id in the database
    # used below for the maplayers.
    newmap.save()

    # Add background layers

    for layer in DEFAULT_BASE_LAYERS:
        logger.info("Adding baselayer %r", layer)
        maplayer = layer_from_viewer_config(MapLayer,
            layer,
            layer['source'],  # source
            index)
        if not maplayer.group == 'background':
            logger.info("Skipping not base layer %r", layer)
            continue
        if 'name' not in layer or not layer['name']:
            logger.info("Unnamed base layer %r", layer)
            maplayer.name = 'UNNAMED BACKGROUND LAYER'

        maplayer.map = newmap
        maplayer.save()
        index += 1

    # Add local layers

    for layer in layers:
        if not isinstance(layer, Layer):
            try:
                layer = Layer.objects.get(typename=layer)
            except ObjectDoesNotExist:
                raise Exception(
                    'Could not find layer with name %s' %
                    layer)

        if not user.has_perm(
                'base.view_resourcebase',
                obj=layer.resourcebase_ptr):
            # invisible layer, skip inclusion or raise Exception?
            raise Exception(
                'User %s tried to create a map with layer %s without having premissions' %
                (user, layer))

        ### Add required parameters for GXP lazy-loading

        # compute (incremental) bbox
        layer_bbox = layer.bbox
        if incr_bbox is None:
            incr_bbox = list(layer_bbox[0:4])
        else:
            incr_bbox[0] = min(incr_bbox[0], layer_bbox[0])
            incr_bbox[1] = max(incr_bbox[1], layer_bbox[1])
            incr_bbox[2] = min(incr_bbox[2], layer_bbox[2])
            incr_bbox[3] = max(incr_bbox[3], layer_bbox[3])

        config = layer.attribute_config()

        config["title"] = layer.title
        config["queryable"] = True
        config["srs"] = layer.srid if layer.srid != "EPSG:4326" else "EPSG:900913"
        config["bbox"] = llbbox_to_mercator([float(coord) for coord in incr_bbox])

        #if layer.storeType == "remoteStore":
            #service = layer.service
            #maplayer = MapLayer(map=map_obj,
                                #name=layer.typename,
                                #ows_url=layer.ows_url,
                                #layer_params=json.dumps(config),
                                #visibility=True,
                                #source_params=json.dumps({
                                    #"ptype": service.ptype,
                                    #"remote": True,
                                    #"url": service.base_url,
                                    #"name": service.name}))
        #else:
            #maplayer = MapLayer(
                #map=map_obj,
                #name=layer.typename,
                #ows_url=layer.ows_url,
                #layer_params=json.dumps(config),
                #visibility=True
            #)

        MapLayer.objects.create(
            map=newmap,
            name=layer.typename,
            ows_url=layer.ows_url,
            stack_order=index,
            visibility=True,
            layer_params=json.dumps(config)
        )

        index += 1

    # Set bounding box based on all layers extents.
    bbox = newmap.get_bbox_from_layers(newmap.local_layers)

    newmap.set_bounds_from_bbox(bbox)

    newmap.set_missing_info()

    # Save again to persist the zoom and bbox changes and
    # to generate the thumbnail.
    newmap.save()

    return newmap
Exemple #29
0
def tiled_view(request, overlay="geonode:index", template="maptiles/maptiles_map.html"):
    if request.method == "POST":
        pprint(request.POST)
    layer = _resolve_layer(request, overlay, "base.view_resourcebase", _PERMISSION_VIEW )
    config = layer.attribute_config()
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    # Transform WGS84 to Mercator.
    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    #if request.user != layer.owner and not request.user.is_superuser:
    #    Layer.objects.filter(
    #        id=layer.id).update(popular_count=F('popular_count') + 1)
    
    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')
        
    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    #if settings.SOCIAL_ORIGINS:
    #    context_dict["social_links"] = build_social_links(request, layer)
    #print context_dict
    
    return render_to_response(template, RequestContext(request, context_dict))
Exemple #30
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)
    # assert False, str(layer_bbox)
    config = layer.attribute_config()
    #print layername
    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    # Transform WGS84 to Mercator.
    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    context_dict = {
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')

    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    if request.method == 'POST':
        form = AnonDownloaderForm(request.POST)
        out = {}
        if form.is_valid():
            out['success'] = True
            pprint(form.cleaned_data)
            anondownload = form.save()
            anondownload.anon_layer = Layer.objects.get(typename = layername)
            anondownload.save()
        else:
            errormsgs = []
            for e in form.errors.values():
                errormsgs.extend([escape(v) for v in e])
            out['success'] = False
            out['errors'] = form.errors
            out['errormsgs'] = errormsgs
        if out['success']:
            status_code = 200
        else:
            status_code = 400
        #Handle form
        return HttpResponse(status=status_code)
    else:
        #Render form
        form = AnonDownloaderForm()
    context_dict["anon_form"] = form
    context_dict["layername"] = layername
    return render_to_response(template, RequestContext(request, context_dict))
Exemple #31
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    if hasattr(layer, 'srid'):
        config['crs'] = {'type': 'name', 'properties': layer.srid}
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.alternate,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.alternate,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    layer.view_count_up(request.user)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config(request)[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    all_times = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except BaseException:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                limit=10,
                offset=offset,
                filter=filter)
            all_granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                filter=filter)
        except BaseException:
            granules = {"features": []}
            all_granules = {"features": []}

    if 'geonode.geoserver' in settings.INSTALLED_APPS:
        from geonode.geoserver.views import get_capabilities
        if layer.has_time:
            workspace, layername = layer.alternate.split(":")
            # WARNING Please make sure to have enabled DJANGO CACHE as per
            # https://docs.djangoproject.com/en/2.0/topics/cache/#filesystem-caching
            wms_capabilities_resp = get_capabilities(request,
                                                     layer.id,
                                                     tolerant=True)
            if wms_capabilities_resp.status_code >= 200 and wms_capabilities_resp.status_code < 400:
                wms_capabilities = wms_capabilities_resp.getvalue()
                if wms_capabilities:
                    import xml.etree.ElementTree as ET
                    e = ET.fromstring(wms_capabilities)
                    for atype in e.findall(
                            "Capability/Layer/Layer[Name='%s']/Extent" %
                        (layername)):
                        dim_name = atype.get('name')
                        if dim_name:
                            dim_name = str(dim_name).lower()
                            if dim_name == 'time':
                                dim_values = atype.text
                                if dim_values:
                                    all_times = dim_values.split(",")
                                    break

    group = None
    if layer.group:
        try:
            group = GroupProfile.objects.get(slug=layer.group.name)
        except GroupProfile.DoesNotExist:
            group = None
    # a flag to be used for qgis server
    show_popup = False
    if 'show_popup' in request.GET and request.GET["show_popup"]:
        show_popup = True

    context_dict = {
        'resource': layer,
        'group': group,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "all_times": all_times,
        "show_popup": show_popup,
        "filter": filter,
    }

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, access_token,
                            *(NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings,
                                      'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY',
                                      'geoext')
    context_dict["crs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')

    # provide bbox in EPSG:4326 for leaflet
    if context_dict["preview"] == 'leaflet':
        srid, wkt = layer.geographic_bounding_box.split(';')
        srid = re.findall(r'\d+', srid)
        geom = GEOSGeometry(wkt, srid=int(srid[0]))
        geom.transform(4326)
        context_dict["layer_bbox"] = ','.join([str(c) for c in geom.extent])

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)
    links_view = [
        item for idx, item in enumerate(links)
        if item.url and 'wms' in item.url or 'gwc' in item.url
    ]
    links_download = [
        item for idx, item in enumerate(links)
        if item.url and 'wms' not in item.url and 'gwc' not in item.url
    ]
    for item in links_view:
        if item.url and access_token and 'access_token' not in item.url:
            params = {'access_token': access_token}
            item.url = Request('GET', item.url, params=params).prepare().url
    for item in links_download:
        if item.url and access_token and 'access_token' not in item.url:
            params = {'access_token': access_token}
            item.url = Request('GET', item.url, params=params).prepare().url

    if request.user.has_perm('view_resourcebase', layer.get_self_resource()):
        context_dict["links"] = links_view
    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links_download"] = links_download

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)
    layers_names = layer.alternate
    try:
        if settings.DEFAULT_WORKSPACE and settings.DEFAULT_WORKSPACE in layers_names:
            workspace, name = layers_names.split(':', 1)
        else:
            name = layers_names
    except:
        print "Can not identify workspace type and layername"

    context_dict["layer_name"] = json.dumps(layers_names)

    try:
        # get type of layer (raster or vector)
        if layer.storeType == 'coverageStore':
            context_dict["layer_type"] = "raster"
        elif layer.storeType == 'dataStore':
            if layer.has_time:
                context_dict["layer_type"] = "vector_time"
            else:
                context_dict["layer_type"] = "vector"

            location = "{location}{service}".format(
                **{
                    'location': settings.OGC_SERVER['default']['LOCATION'],
                    'service': 'wms',
                })
            # get schema for specific layer
            username = settings.OGC_SERVER['default']['USER']
            password = settings.OGC_SERVER['default']['PASSWORD']
            schema = get_schema(location,
                                name,
                                username=username,
                                password=password)

            # get the name of the column which holds the geometry
            if 'the_geom' in schema['properties']:
                schema['properties'].pop('the_geom', None)
            elif 'geom' in schema['properties']:
                schema['properties'].pop("geom", None)

            # filter the schema dict based on the values of layers_attributes
            layer_attributes_schema = []
            for key in schema['properties'].keys():
                layer_attributes_schema.append(key)

            filtered_attributes = layer_attributes_schema
            context_dict["schema"] = schema
            context_dict["filtered_attributes"] = filtered_attributes

    except:
        print "Possible error with OWSLib. Turning all available properties to string"

    # maps owned by user needed to fill the "add to existing map section" in template
    if request.user.is_authenticated():
        context_dict["maps"] = Map.objects.filter(owner=request.user)
    return TemplateResponse(request, template,
                            RequestContext(request, context_dict))
Exemple #32
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.alternate,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.alternate,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    layer.view_count_up(request.user)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(
            settings,
            'DEFAULT_MAP_CRS',
            'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config(request)[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except BaseException:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                limit=10,
                offset=offset,
                filter=filter)
            all_granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'], store, filter=filter)
        except BaseException:
            granules = {"features": []}
            all_granules = {"features": []}

    group = None
    if layer.group:
        try:
            group = GroupProfile.objects.get(slug=layer.group.name)
        except GroupProfile.DoesNotExist:
            group = None
    context_dict = {
        'resource': layer,
        'group': group,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
    }

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    context_dict["viewer"] = json.dumps(map_obj.viewer_json(
        request.user, access_token, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')
    context_dict["crs"] = getattr(
        settings,
        'DEFAULT_MAP_CRS',
        'EPSG:900913')

    # provide bbox in EPSG:4326 for leaflet
    if context_dict["preview"] == 'leaflet':
        srid, wkt = layer.geographic_bounding_box.split(';')
        srid = re.findall(r'\d+', srid)
        geom = GEOSGeometry(wkt, srid=int(srid[0]))
        geom.transform(4326)
        context_dict["layer_bbox"] = ','.join([str(c) for c in geom.extent])

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)
    links_view = [item for idx, item in enumerate(links) if
                  item.url and 'wms' in item.url or 'gwc' in item.url]
    links_download = [item for idx, item in enumerate(
        links) if item.url and 'wms' not in item.url and 'gwc' not in item.url]
    for item in links_view:
        if item.url and access_token and 'access_token' not in item.url:
            params = {'access_token': access_token}
            item.url = Request('GET', item.url, params=params).prepare().url
    for item in links_download:
        if item.url and access_token and 'access_token' not in item.url:
            params = {'access_token': access_token}
            item.url = Request('GET', item.url, params=params).prepare().url

    if request.user.has_perm('view_resourcebase', layer.get_self_resource()):
        context_dict["links"] = links_view
    if request.user.has_perm(
        'download_resourcebase',
            layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links_download"] = links_download

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)
    layers_names = layer.alternate
    try:
        if 'geonode' in layers_names:
            workspace, name = layers_names.split(':', 1)
        else:
            name = layers_names
    except:
        print "Can not identify workspace type and layername"

    context_dict["layer_name"] = json.dumps(layers_names)

    try:
        # get type of layer (raster or vector)
        if layer.storeType == 'coverageStore':
            context_dict["layer_type"] = "raster"
        elif layer.storeType == 'dataStore':
            context_dict["layer_type"] = "vector"

            location = "{location}{service}".format(** {
                'location': settings.OGC_SERVER['default']['LOCATION'],
                'service': 'wms',
            })
            # get schema for specific layer
            username = settings.OGC_SERVER['default']['USER']
            password = settings.OGC_SERVER['default']['PASSWORD']
            schema = get_schema(location, name, username=username, password=password)

            # get the name of the column which holds the geometry
            if 'the_geom' in schema['properties']:
                schema['properties'].pop('the_geom', None)
            elif 'geom' in schema['properties']:
                schema['properties'].pop("geom", None)

            # filter the schema dict based on the values of layers_attributes
            layer_attributes_schema = []
            for key in schema['properties'].keys():
                    layer_attributes_schema.append(key)

            filtered_attributes = layer_attributes_schema
            context_dict["schema"] = schema
            context_dict["filtered_attributes"] = filtered_attributes

    except:
        print "Possible error with OWSLib. Turning all available properties to string"

    # maps owned by user needed to fill the "add to existing map section" in template
    if request.user.is_authenticated():
        context_dict["maps"] = Map.objects.filter(owner=request.user)
    return TemplateResponse(
        request, template, RequestContext(request, context_dict))
Exemple #33
0
def dataset_metadata(request,
                     layername,
                     template='datasets/dataset_metadata.html',
                     ajax=True):
    try:
        layer = _resolve_dataset(request, layername,
                                 'base.change_resourcebase_metadata',
                                 _PERMISSION_MSG_METADATA)
    except PermissionDenied as e:
        return HttpResponse(Exception(_("Not allowed"), e), status=403)
    except Exception as e:
        raise Http404(Exception(_("Not found"), e))
    if not layer:
        raise Http404(_("Not found"))

    dataset_attribute_set = inlineformset_factory(
        Dataset,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )
    current_keywords = [keyword.name for keyword in layer.keywords.all()]
    topic_category = layer.category

    topic_thesaurus = layer.tkeywords.all()
    # Add metadata_author or poc if missing
    layer.add_missing_metadata_author_or_poc()

    poc = layer.poc
    metadata_author = layer.metadata_author

    # assert False, str(dataset_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    dataset_bbox = layer.bbox
    bbox = [float(coord) for coord in list(dataset_bbox[0:4])]
    if hasattr(layer, 'srid'):
        config['crs'] = {'type': 'name', 'properties': layer.srid}
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857')
    config["bbox"] = bbox if config["srs"] != 'EPSG:3857' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Dataset.objects.filter(id=layer.id).update(
            popular_count=F('popular_count') + 1)

    if request.method == "POST":
        if layer.metadata_uploaded_preserve:  # layer metadata cannot be edited
            out = {
                'success': False,
                'errors': METADATA_UPLOADED_PRESERVE_ERROR
            }
            return HttpResponse(json.dumps(out),
                                content_type='application/json',
                                status=400)

        thumbnail_url = layer.thumbnail_url
        dataset_form = DatasetForm(request.POST,
                                   instance=layer,
                                   prefix="resource",
                                   user=request.user)
        if not dataset_form.is_valid():
            logger.error(
                f"Dataset Metadata form is not valid: {dataset_form.errors}")
            out = {
                'success':
                False,
                'errors': [
                    f"{x}: {y[0].messages[0]}"
                    for x, y in dataset_form.errors.as_data().items()
                ]
            }
            return HttpResponse(json.dumps(out),
                                content_type='application/json',
                                status=400)
        if not layer.thumbnail_url:
            layer.thumbnail_url = thumbnail_url
        attribute_form = dataset_attribute_set(
            request.POST,
            instance=layer,
            prefix="dataset_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        if not attribute_form.is_valid():
            logger.error(
                f"Dataset Attributes form is not valid: {attribute_form.errors}"
            )
            out = {
                'success':
                False,
                "errors": [
                    re.sub(re.compile('<.*?>'), '', str(err))
                    for err in attribute_form.errors
                ]
            }
            return HttpResponse(json.dumps(out),
                                content_type='application/json',
                                status=400)
        category_form = CategoryForm(
            request.POST,
            prefix="category_choice_field",
            initial=int(request.POST["category_choice_field"])
            if "category_choice_field" in request.POST
            and request.POST["category_choice_field"] else None)
        if not category_form.is_valid():
            logger.error(
                f"Dataset Category form is not valid: {category_form.errors}")
            out = {
                'success':
                False,
                'errors': [
                    re.sub(re.compile('<.*?>'), '', str(err))
                    for err in category_form.errors
                ]
            }
            return HttpResponse(json.dumps(out),
                                content_type='application/json',
                                status=400)
        if hasattr(settings, 'THESAURUS'):
            tkeywords_form = TKeywordForm(request.POST)
        else:
            tkeywords_form = ThesaurusAvailableForm(request.POST,
                                                    prefix='tkeywords')
            #  set initial values for thesaurus form
        if not tkeywords_form.is_valid():
            logger.error(
                f"Dataset Thesauri Keywords form is not valid: {tkeywords_form.errors}"
            )
            out = {
                'success':
                False,
                'errors': [
                    re.sub(re.compile('<.*?>'), '', str(err))
                    for err in tkeywords_form.errors
                ]
            }
            return HttpResponse(json.dumps(out),
                                content_type='application/json',
                                status=400)
    else:
        dataset_form = DatasetForm(instance=layer,
                                   prefix="resource",
                                   user=request.user)
        dataset_form.disable_keywords_widget_for_non_superuser(request.user)
        attribute_form = dataset_attribute_set(
            instance=layer,
            prefix="dataset_attribute_set",
            queryset=Attribute.objects.order_by('display_order'))
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

        # Create THESAURUS widgets
        lang = settings.THESAURUS_DEFAULT_LANG if hasattr(
            settings, 'THESAURUS_DEFAULT_LANG') else 'en'
        if hasattr(settings, 'THESAURUS') and settings.THESAURUS:
            warnings.warn(
                'The settings for Thesaurus has been moved to Model, \
            this feature will be removed in next releases', DeprecationWarning)
            dataset_tkeywords = layer.tkeywords.all()
            tkeywords_list = ''
            if dataset_tkeywords and len(dataset_tkeywords) > 0:
                tkeywords_ids = dataset_tkeywords.values_list('id', flat=True)
                if hasattr(settings, 'THESAURUS') and settings.THESAURUS:
                    el = settings.THESAURUS
                    thesaurus_name = el['name']
                    try:
                        t = Thesaurus.objects.get(identifier=thesaurus_name)
                        for tk in t.thesaurus.filter(pk__in=tkeywords_ids):
                            tkl = tk.keyword.filter(lang=lang)
                            if len(tkl) > 0:
                                tkl_ids = ",".join(
                                    map(str, tkl.values_list('id', flat=True)))
                                tkeywords_list += f",{tkl_ids}" if len(
                                    tkeywords_list) > 0 else tkl_ids
                    except Exception:
                        tb = traceback.format_exc()
                        logger.error(tb)
            tkeywords_form = TKeywordForm(instance=layer)
        else:
            tkeywords_form = ThesaurusAvailableForm(prefix='tkeywords')
            #  set initial values for thesaurus form
            for tid in tkeywords_form.fields:
                values = []
                values = [
                    keyword.id for keyword in topic_thesaurus
                    if int(tid) == keyword.thesaurus.id
                ]
                tkeywords_form.fields[tid].initial = values

    if request.method == "POST" and dataset_form.is_valid(
    ) and attribute_form.is_valid() and category_form.is_valid(
    ) and tkeywords_form.is_valid():
        new_poc = dataset_form.cleaned_data['poc']
        new_author = dataset_form.cleaned_data['metadata_author']

        if new_poc is None:
            if poc is None:
                poc_form = ProfileForm(request.POST,
                                       prefix="poc",
                                       instance=poc)
            else:
                poc_form = ProfileForm(request.POST, prefix="poc")
            if poc_form.is_valid():
                if len(poc_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = poc_form._errors.setdefault(
                        'profile', ErrorList())
                    errors.append(
                        _('You must set a point of contact for this resource'))
                    poc = None
            if poc_form.has_changed and poc_form.is_valid():
                new_poc = poc_form.save()

        if new_author is None:
            if metadata_author is None:
                author_form = ProfileForm(request.POST,
                                          prefix="author",
                                          instance=metadata_author)
            else:
                author_form = ProfileForm(request.POST, prefix="author")
            if author_form.is_valid():
                if len(author_form.cleaned_data['profile']) == 0:
                    # FIXME use form.add_error in django > 1.7
                    errors = author_form._errors.setdefault(
                        'profile', ErrorList())
                    errors.append(
                        _('You must set an author for this resource'))
                    metadata_author = None
            if author_form.has_changed and author_form.is_valid():
                new_author = author_form.save()

        new_category = None
        if category_form and 'category_choice_field' in category_form.cleaned_data and\
                category_form.cleaned_data['category_choice_field']:
            new_category = TopicCategory.objects.get(
                id=int(category_form.cleaned_data['category_choice_field']))

        for form in attribute_form.cleaned_data:
            la = Attribute.objects.get(id=int(form['id'].id))
            la.description = form["description"]
            la.attribute_label = form["attribute_label"]
            la.visible = form["visible"]
            la.display_order = form["display_order"]
            la.featureinfo_type = form["featureinfo_type"]
            la.save()

        if new_poc is not None or new_author is not None:
            if new_poc is not None:
                layer.poc = new_poc
            if new_author is not None:
                layer.metadata_author = new_author

        new_keywords = current_keywords if request.keyword_readonly else dataset_form.cleaned_data[
            'keywords']
        new_regions = [x.strip() for x in dataset_form.cleaned_data['regions']]

        layer.keywords.clear()
        if new_keywords:
            layer.keywords.add(*new_keywords)
        layer.regions.clear()
        if new_regions:
            layer.regions.add(*new_regions)
        layer.category = new_category

        from geonode.upload.models import Upload

        up_sessions = Upload.objects.filter(
            resource_id=layer.resourcebase_ptr_id)
        if up_sessions.count() > 0 and up_sessions[0].user != layer.owner:
            up_sessions.update(user=layer.owner)

        register_event(request, EventType.EVENT_CHANGE_METADATA, layer)
        if not ajax:
            return HttpResponseRedirect(layer.get_absolute_url())

        message = layer.alternate

        try:
            if not tkeywords_form.is_valid():
                return HttpResponse(
                    json.dumps({'message': "Invalid thesaurus keywords"},
                               status_code=400))

            thesaurus_setting = getattr(settings, 'THESAURUS', None)
            if thesaurus_setting:
                tkeywords_data = tkeywords_form.cleaned_data['tkeywords']
                tkeywords_data = tkeywords_data.filter(
                    thesaurus__identifier=thesaurus_setting['name'])
                layer.tkeywords.set(tkeywords_data)
            elif Thesaurus.objects.all().exists():
                fields = tkeywords_form.cleaned_data
                layer.tkeywords.set(tkeywords_form.cleanx(fields))

        except Exception:
            tb = traceback.format_exc()
            logger.error(tb)

        resource_manager.update(
            layer.uuid,
            instance=layer,
            notify=True,
            extra_metadata=json.loads(
                dataset_form.cleaned_data['extra_metadata']))
        return HttpResponse(json.dumps({'message': message}))

    if settings.ADMIN_MODERATE_UPLOADS:
        if not request.user.is_superuser:
            can_change_metadata = request.user.has_perm(
                'change_resourcebase_metadata', layer.get_self_resource())
            try:
                is_manager = request.user.groupmember_set.all().filter(
                    role='manager').exists()
            except Exception:
                is_manager = False

            if not is_manager or not can_change_metadata:
                if settings.RESOURCE_PUBLISHING:
                    dataset_form.fields['is_published'].widget.attrs.update(
                        {'disabled': 'true'})
                dataset_form.fields['is_approved'].widget.attrs.update(
                    {'disabled': 'true'})

    if poc is not None:
        dataset_form.fields['poc'].initial = poc.id
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = True
    else:
        poc_form = ProfileForm(prefix="poc")
        poc_form.hidden = False

    if metadata_author is not None:
        dataset_form.fields['metadata_author'].initial = metadata_author.id
        author_form = ProfileForm(prefix="author")
        author_form.hidden = True
    else:
        author_form = ProfileForm(prefix="author")
        author_form.hidden = False

    metadata_author_groups = get_user_visible_groups(request.user)

    register_event(request, 'view_metadata', layer)
    return render(
        request,
        template,
        context={
            "resource":
            layer,
            "dataset":
            layer,
            "dataset_form":
            dataset_form,
            "poc_form":
            poc_form,
            "author_form":
            author_form,
            "attribute_form":
            attribute_form,
            "category_form":
            category_form,
            "tkeywords_form":
            tkeywords_form,
            "preview":
            getattr(settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY',
                    'mapstore'),
            "crs":
            getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857'),
            "metadataxsl":
            getattr(settings, 'GEONODE_CATALOGUE_METADATA_XSL', True),
            "freetext_readonly":
            getattr(settings, 'FREETEXT_KEYWORDS_READONLY', False),
            "metadata_author_groups":
            metadata_author_groups,
            "TOPICCATEGORY_MANDATORY":
            getattr(settings, 'TOPICCATEGORY_MANDATORY', False),
            "GROUP_MANDATORY_RESOURCES":
            getattr(settings, 'GROUP_MANDATORY_RESOURCES', False),
            "UI_MANDATORY_FIELDS":
            list(
                set(getattr(settings, 'UI_DEFAULT_MANDATORY_FIELDS', []))
                | set(getattr(settings, 'UI_REQUIRED_FIELDS', [])))
        })
Exemple #34
0
def pdf_metadata_layer(request, layername, template='layers/pdf_metadata_layer.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    layer_attribute_set = inlineformset_factory(
        Layer,
        Attribute,
        extra=0,
        form=LayerAttributeForm,
    )
    topic_category = layer.category

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    # Transform WGS84 to Mercator.
    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)



    context_dict = {
        "resource": layer,
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
    }


    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')

    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    html = render_to_string('layers/pdf_metadata_layer.html', {
                                                                'pagesize': 'A4',
                                                                'resource': layer,
                                                                }, context_instance=RequestContext(request))

    return generar_pdf(html)
Exemple #35
0
def layer_detail(request, layername, template='layers/layer_detail.html'):

    #if template:
    #logger.warning('Template param not expected: %s', template)

    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    srid = layer.srid

    # Transform WGS84 to Mercator.
    config["srs"] = srid if srid != "EPSG:4326" else "EPSG:900913"
    config["bbox"] = llbbox_to_mercator([float(coord) for coord in bbox])

    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(id=layer.id).update(
            popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection="EPSG:900913")
    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    granule_filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            granule_filter = None
            try:
                if request.GET["filter"]:
                    granule_filter = request.GET["filter"]
            except:
                pass

            schema = cat.mosaic_coverage_schema(
                coverages['coverages']['coverage'][0]['name'], store)
            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                limit=10,
                offset=offset,
                filter=granule_filter)
            all_granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                filter=granule_filter)

        except:
            granules = {"features": []}
            all_granules = {"features": []}

            import traceback
            traceback.print_exc()

        #print (' +++++++++++++++++++++++++++++++++++++++++ \n' + str(granules) + '\n +++++++++++++++++++++++++++++++++++++++++ ')

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "is_owner": request.user == layer.owner,
        "is_superuser": request.user.is_superuser,
        "granules": granules,
        "all_granules": all_granules,
        "filter": granule_filter,
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, *(NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                      'leaflet')

    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    #if request.user.is_superuser:
    #logger.debug("Dispatching to admin page")
    #else:
    #logger.debug("Dispatching to user page")

    #template = 'layers/layer_detail_admin.html' if request.user.is_superuser else 'layers/layer_detail_user.html'

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #36
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    layer = _resolve_layer(
        request,
        layername,
        'base.view_resourcebase',
        _PERMISSION_MSG_VIEW)

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name}
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config),
            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(
            name=layer.typename,
            ows_url=layer.ows_url,
            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(
            id=layer.id).update(popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config(request)[1] if la.ows_url is None]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, limit=10,
                                           offset=offset, filter=filter)
            all_granules = cat.mosaic_granules(coverages['coverages']['coverage'][0]['name'], store, filter=filter)
        except:
            granules = {"features": []}
            all_granules = {"features": []}

    context_dict = {
        "resource": layer,
        'perms_list': get_perms(request.user, layer.get_self_resource()),
        "permissions_json": _perms_info_json(layer),
        "documents": get_related_documents(layer),
        "metadata": metadata,
        "is_layer": True,
        "wps_enabled": settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules": granules,
        "all_granules": all_granules,
        "filter": filter,
    }

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        u = uuid.uuid1()
        access_token = u.hex

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, access_token, * (NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(
        settings,
        'LAYER_PREVIEW_LIBRARY',
        'leaflet')
    context_dict["crs"] = getattr(
        settings,
        'DEFAULT_MAP_CRS',
        'EPSG:900913')

    if layer.storeType == 'dataStore':
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_VECTOR)
    else:
        links = layer.link_set.download().filter(
            name__in=settings.DOWNLOAD_FORMATS_RASTER)
    links_view = [item for idx, item in enumerate(links) if
                  item.url and 'wms' in item.url or 'gwc' in item.url]
    links_download = [item for idx, item in enumerate(links) if
                      item.url and 'wms' not in item.url and 'gwc' not in item.url]
    for item in links_view:
        if item.url and access_token:
            item.url = "%s&access_token=%s" % (item.url, access_token)
    for item in links_download:
        if item.url and access_token:
            item.url = "%s&access_token=%s" % (item.url, access_token)

    if request.user.has_perm('view_resourcebase', layer.get_self_resource()):
        context_dict["links"] = links_view
    if request.user.has_perm('download_resourcebase', layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links_download"] = links_download

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))
Exemple #37
0
def add_layers_to_map_config(request, map_obj, layer_names, add_base_layers=True):
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request)
    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        access_token = None

    bbox = None

    layers = []
    for layer_name in layer_names:
        try:
            layer = _resolve_layer(request, layer_name)
        except ObjectDoesNotExist:
            # bad layer, skip
            continue

        if not layer.is_published:
            # invisible layer, skip inclusion
            continue

        if not request.user.has_perm(
                'view_resourcebase',
                obj=layer.get_self_resource()):
            # invisible layer, skip inclusion
            continue

        layer_bbox = layer.bbox
        # assert False, str(layer_bbox)
        if bbox is None:
            bbox = list(layer_bbox[0:4])
        else:
            bbox[0] = min(bbox[0], layer_bbox[0])
            bbox[1] = max(bbox[1], layer_bbox[1])
            bbox[2] = min(bbox[2], layer_bbox[2])
            bbox[3] = max(bbox[3], layer_bbox[3])

        config = layer.attribute_config()

        # Add required parameters for GXP lazy-loading
        config["title"] = layer.title
        config["queryable"] = True
        config["wrapDateLine"] = True

        config["srs"] = getattr(
            settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
        config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
            else llbbox_to_mercator([float(coord) for coord in bbox])

        if layer.storeType == "remoteStore":
            service = layer.service
            # Probably not a good idea to send the access token to every remote service.
            # This should never match, so no access token should be
            # sent to remote services.
            ogc_server_url = urlparse.urlsplit(
                ogc_server_settings.PUBLIC_LOCATION).netloc
            service_url = urlparse.urlsplit(service.base_url).netloc

            if access_token and ogc_server_url == service_url and 'access_token' not in service.base_url:
                url = service.base_url + '?access_token=' + access_token
            else:
                url = service.base_url
            maplayer = MapLayer(map=map_obj,
                                name=layer.alternate,
                                ows_url=layer.ows_url,
                                layer_params=json.dumps(config),
                                visibility=True,
                                source_params=json.dumps({
                                    "ptype": service.ptype,
                                    "remote": True,
                                    "url": url,
                                    "name": service.name}))
        else:
            ogc_server_url = urlparse.urlsplit(
                ogc_server_settings.PUBLIC_LOCATION).netloc
            layer_url = urlparse.urlsplit(layer.ows_url).netloc

            if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url:
                url = layer.ows_url + '?access_token=' + access_token
            else:
                url = layer.ows_url
            maplayer = MapLayer(
                map=map_obj,
                name=layer.alternate,
                ows_url=url,
                # use DjangoJSONEncoder to handle Decimal values
                layer_params=json.dumps(config, cls=DjangoJSONEncoder),
                visibility=True
            )

        layers.append(maplayer)

    if bbox is not None:
        minx, maxx, miny, maxy = [float(coord) for coord in bbox]
        x = (minx + maxx) / 2
        y = (miny + maxy) / 2

        if getattr(
            settings,
            'DEFAULT_MAP_CRS',
                'EPSG:900913') == "EPSG:4326":
            center = list((x, y))
        else:
            center = list(forward_mercator((x, y)))

        if center[1] == float('-inf'):
            center[1] = 0

        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        # Check if the bbox is invalid
        valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
        valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD

        if valid_x:
            width_zoom = math.log(360 / abs(maxx - minx), 2)
        else:
            width_zoom = 15

        if valid_y:
            height_zoom = math.log(360 / abs(maxy - miny), 2)
        else:
            height_zoom = 15

        map_obj.center_x = center[0]
        map_obj.center_y = center[1]
        map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

    map_obj.handle_moderated_uploads()

    if add_base_layers:
        layers_to_add = DEFAULT_BASE_LAYERS + layers
    else:
        layers_to_add = layers
    config = map_obj.viewer_json(
        request.user, access_token, *layers_to_add)

    config['fromLayer'] = True

    return config
Exemple #38
0
def new_map_config(request):
    '''
    View that creates a new map.

    If the query argument 'copy' is given, the initial map is
    a copy of the map with the id specified, otherwise the
    default map configuration is used.  If copy is specified
    and the map specified does not exist a 404 is returned.
    '''
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request)

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        access_token = None

    if request.method == 'GET' and 'copy' in request.GET:
        mapid = request.GET['copy']
        map_obj = _resolve_map(request, mapid, 'base.view_resourcebase')

        map_obj.abstract = DEFAULT_ABSTRACT
        map_obj.title = DEFAULT_TITLE
        if request.user.is_authenticated():
            map_obj.owner = request.user

        config = map_obj.viewer_json(request.user, access_token)
        del config['id']
    else:
        if request.method == 'GET':
            params = request.GET
        elif request.method == 'POST':
            params = request.POST
        else:
            return HttpResponse(status=405)

        if 'layer' in params:
            bbox = None
            map_obj = Map(projection=getattr(settings, 'DEFAULT_MAP_CRS',
                          'EPSG:900913'))
            layers = []
            for layer_name in params.getlist('layer'):
                try:
                    layer = _resolve_layer(request, layer_name)
                except ObjectDoesNotExist:
                    # bad layer, skip
                    continue

                if not request.user.has_perm(
                        'view_resourcebase',
                        obj=layer.get_self_resource()):
                    # invisible layer, skip inclusion
                    continue

                layer_bbox = layer.bbox
                # assert False, str(layer_bbox)
                if bbox is None:
                    bbox = list(layer_bbox[0:4])
                else:
                    bbox[0] = min(bbox[0], layer_bbox[0])
                    bbox[1] = max(bbox[1], layer_bbox[1])
                    bbox[2] = min(bbox[2], layer_bbox[2])
                    bbox[3] = max(bbox[3], layer_bbox[3])

                config = layer.attribute_config()

                # Add required parameters for GXP lazy-loading
                config["title"] = layer.title
                config["queryable"] = True

                config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
                config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
                    else llbbox_to_mercator([float(coord) for coord in bbox])

                if layer.storeType == "remoteStore":
                    service = layer.service
                    # Probably not a good idea to send the access token to every remote service.
                    # This should never match, so no access token should be sent to remote services.
                    ogc_server_url = urlparse.urlsplit(ogc_server_settings.PUBLIC_LOCATION).netloc
                    service_url = urlparse.urlsplit(service.base_url).netloc

                    if access_token and ogc_server_url == service_url and 'access_token' not in service.base_url:
                        url = service.base_url+'?access_token='+access_token
                    else:
                        url = service.base_url
                    maplayer = MapLayer(map=map_obj,
                                        name=layer.typename,
                                        ows_url=layer.ows_url,
                                        layer_params=json.dumps(config),
                                        visibility=True,
                                        source_params=json.dumps({
                                            "ptype": service.ptype,
                                            "remote": True,
                                            "url": url,
                                            "name": service.name}))
                else:
                    ogc_server_url = urlparse.urlsplit(ogc_server_settings.PUBLIC_LOCATION).netloc
                    layer_url = urlparse.urlsplit(layer.ows_url).netloc

                    if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url:
                        url = layer.ows_url+'?access_token='+access_token
                    else:
                        url = layer.ows_url
                    maplayer = MapLayer(
                        map=map_obj,
                        name=layer.typename,
                        ows_url=url,
                        # use DjangoJSONEncoder to handle Decimal values
                        layer_params=json.dumps(config, cls=DjangoJSONEncoder),
                        visibility=True
                    )

                layers.append(maplayer)

            if bbox is not None:
                minx, miny, maxx, maxy = [float(c) for c in bbox]
                x = (minx + maxx) / 2
                y = (miny + maxy) / 2

                if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') == "EPSG:4326":
                    center = list((x, y))
                else:
                    center = list(forward_mercator((x, y)))

                if center[1] == float('-inf'):
                    center[1] = 0

                BBOX_DIFFERENCE_THRESHOLD = 1e-5

                # Check if the bbox is invalid
                valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
                valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD

                if valid_x:
                    width_zoom = math.log(360 / abs(maxx - minx), 2)
                else:
                    width_zoom = 15

                if valid_y:
                    height_zoom = math.log(360 / abs(maxy - miny), 2)
                else:
                    height_zoom = 15

                map_obj.center_x = center[0]
                map_obj.center_y = center[1]
                map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

            config = map_obj.viewer_json(
                request.user, access_token, *(DEFAULT_BASE_LAYERS + layers))
            config['fromLayer'] = True
        else:
            config = DEFAULT_MAP_CONFIG
    return json.dumps(config)
Exemple #39
0
def add_layers_to_map_config(request,
                             map_obj,
                             layer_names,
                             add_base_layers=True):
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request)
    bbox = None
    layers = []
    for layer_name in layer_names:
        try:
            layer = _resolve_layer(request, layer_name)
        except ObjectDoesNotExist:
            # bad layer, skip
            continue

        if not layer.is_published:
            # invisible layer, skip inclusion
            continue

        if not request.user.has_perm('view_resourcebase',
                                     obj=layer.get_self_resource()):
            # invisible layer, skip inclusion
            continue

        layer_bbox = layer.bbox
        # assert False, str(layer_bbox)
        if bbox is None:
            bbox = list(layer_bbox[0:4])
        else:
            bbox[0] = min(bbox[0], layer_bbox[0])
            bbox[1] = max(bbox[1], layer_bbox[1])
            bbox[2] = min(bbox[2], layer_bbox[2])
            bbox[3] = max(bbox[3], layer_bbox[3])

        config = layer.attribute_config()

        # Add required parameters for a WM layer
        title = 'No title'
        if layer.title:
            title = layer.title
        config["title"] = title
        config["queryable"] = True

        config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')

        config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
            else llbbox_to_mercator([float(coord) for coord in bbox])

        access_token = request.session[
            'access_token'] if request and 'access_token' in request.session else None
        if layer.storeType == "remoteStore":
            service = layer.service
            # Probably not a good idea to send the access token to every remote service.
            # This should never match, so no access token should be
            # sent to remote services.
            ogc_server_url = urlparse.urlsplit(
                ogc_server_settings.PUBLIC_LOCATION).netloc
            service_url = urlparse.urlsplit(service.base_url).netloc

            if access_token and ogc_server_url == service_url and 'access_token' not in service.base_url:
                url = service.base_url + '?access_token=' + access_token
            else:
                url = service.base_url
            maplayer = MapLayer(map=map_obj,
                                name=layer.alternate,
                                ows_url=layer.ows_url,
                                layer_params=json.dumps(config),
                                visibility=True,
                                source_params=json.dumps({
                                    "ptype": service.ptype,
                                    "remote": True,
                                    "url": url,
                                    "name": service.name
                                }))
        else:
            ogc_server_url = urlparse.urlsplit(
                ogc_server_settings.PUBLIC_LOCATION).netloc
            layer_url = urlparse.urlsplit(layer.ows_url).netloc

            if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url:
                url = layer.ows_url + '?access_token=' + access_token
            else:
                url = layer.ows_url
            maplayer = MapLayer(
                map=map_obj,
                name=layer.alternate,
                ows_url=url,
                # use DjangoJSONEncoder to handle Decimal values
                layer_params=json.dumps(config, cls=DjangoJSONEncoder),
                visibility=True)
        layers.append(maplayer)

    if bbox is not None:
        minx, maxx, miny, maxy = [float(coord) for coord in bbox]
        x = (minx + maxx) / 2
        y = (miny + maxy) / 2

        if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') == "EPSG:4326":
            center = list((x, y))
        else:
            center = list(forward_mercator((x, y)))

        if center[1] == float('-inf'):
            center[1] = 0

        BBOX_DIFFERENCE_THRESHOLD = 1e-5

        # Check if the bbox is invalid
        valid_x = (maxx - minx)**2 > BBOX_DIFFERENCE_THRESHOLD
        valid_y = (maxy - miny)**2 > BBOX_DIFFERENCE_THRESHOLD

        if valid_x:
            width_zoom = math.log(360 / abs(maxx - minx), 2)
        else:
            width_zoom = 15

        if valid_y:
            height_zoom = math.log(360 / abs(maxy - miny), 2)
        else:
            height_zoom = 15

        map_obj.center_x = center[0]
        map_obj.center_y = center[1]
        map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

    map_obj.handle_moderated_uploads()

    if add_base_layers:
        layers_to_add = DEFAULT_BASE_LAYERS + layers
    else:
        layers_to_add = layers
    config = map_obj.viewer_json(request, *layers_to_add)

    config['fromLayer'] = True

    return config
Exemple #40
0
def new_map_config(request):
    '''
    View that creates a new map.

    If the query argument 'copy' is given, the initial map is
    a copy of the map with the id specified, otherwise the
    default map configuration is used.  If copy is specified
    and the map specified does not exist a 404 is returned.
    '''
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config(request)

    if 'access_token' in request.session:
        access_token = request.session['access_token']
    else:
        access_token = None

    if request.method == 'GET' and 'copy' in request.GET:
        mapid = request.GET['copy']
        map_obj = _resolve_map(request, mapid, 'base.view_resourcebase')

        map_obj.abstract = DEFAULT_ABSTRACT
        map_obj.title = DEFAULT_TITLE
        if request.user.is_authenticated():
            map_obj.owner = request.user

        config = map_obj.viewer_json(request.user, access_token)
        del config['id']
    else:
        if request.method == 'GET':
            params = request.GET
        elif request.method == 'POST':
            params = request.POST
        else:
            return HttpResponse(status=405)

        if 'layer' in params:
            bbox = None
            map_obj = Map(projection=getattr(settings, 'DEFAULT_MAP_CRS',
                          'EPSG:900913'))
            layers = []
            for layer_name in params.getlist('layer'):
                try:
                    layer = _resolve_layer(request, layer_name)
                except ObjectDoesNotExist:
                    # bad layer, skip
                    continue

                if not request.user.has_perm(
                        'view_resourcebase',
                        obj=layer.get_self_resource()):
                    # invisible layer, skip inclusion
                    continue

                layer_bbox = layer.bbox
                # assert False, str(layer_bbox)
                if bbox is None:
                    bbox = list(layer_bbox[0:4])
                else:
                    bbox[0] = min(bbox[0], layer_bbox[0])
                    bbox[1] = max(bbox[1], layer_bbox[1])
                    bbox[2] = min(bbox[2], layer_bbox[2])
                    bbox[3] = max(bbox[3], layer_bbox[3])

                config = layer.attribute_config()

                # Add required parameters for GXP lazy-loading
                config["title"] = layer.title
                config["queryable"] = True

                config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
                config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
                    else llbbox_to_mercator([float(coord) for coord in bbox])

                if layer.storeType == "remoteStore":
                    service = layer.service
                    # Probably not a good idea to send the access token to every remote service.
                    # This should never match, so no access token should be sent to remote services.
                    ogc_server_url = urlparse.urlsplit(ogc_server_settings.PUBLIC_LOCATION).netloc
                    service_url = urlparse.urlsplit(service.base_url).netloc

                    if access_token and ogc_server_url == service_url and 'access_token' not in service.base_url:
                        url = service.base_url+'?access_token='+access_token
                    else:
                        url = service.base_url
                    maplayer = MapLayer(map=map_obj,
                                        name=layer.typename,
                                        ows_url=layer.ows_url,
                                        layer_params=json.dumps(config),
                                        visibility=True,
                                        source_params=json.dumps({
                                            "ptype": service.ptype,
                                            "remote": True,
                                            "url": url,
                                            "name": service.name}))
                else:
                    ogc_server_url = urlparse.urlsplit(ogc_server_settings.PUBLIC_LOCATION).netloc
                    layer_url = urlparse.urlsplit(layer.ows_url).netloc

                    if access_token and ogc_server_url == layer_url and 'access_token' not in layer.ows_url:
                        url = layer.ows_url+'?access_token='+access_token
                    else:
                        url = layer.ows_url
                    maplayer = MapLayer(
                        map=map_obj,
                        name=layer.typename,
                        ows_url=url,
                        # use DjangoJSONEncoder to handle Decimal values
                        layer_params=json.dumps(config, cls=DjangoJSONEncoder),
                        visibility=True
                    )

                layers.append(maplayer)

            if bbox is not None:
                minx, miny, maxx, maxy = [float(coord) for coord in bbox]
                x = (minx + maxx) / 2
                y = (miny + maxy) / 2

                if getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913') == "EPSG:4326":
                    center = list((x, y))
                else:
                    center = list(forward_mercator((x, y)))

                if center[1] == float('-inf'):
                    center[1] = 0

                BBOX_DIFFERENCE_THRESHOLD = 1e-5

                # Check if the bbox is invalid
                valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
                valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD

                if valid_x:
                    width_zoom = math.log(360 / abs(maxx - minx), 2)
                else:
                    width_zoom = 15

                if valid_y:
                    height_zoom = math.log(360 / abs(maxy - miny), 2)
                else:
                    height_zoom = 15

                map_obj.center_x = center[0]
                map_obj.center_y = center[1]
                map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

            config = map_obj.viewer_json(
                request.user, access_token, *(DEFAULT_BASE_LAYERS + layers))
            config['fromLayer'] = True
        else:
            config = DEFAULT_MAP_CONFIG
    return json.dumps(config)
Exemple #41
0
def gxp2wm(config, map_obj=None):
    """
    Convert a GeoNode map json or string config to the WorldMap client format.
    """
    config_is_string = False
    # let's first see if it is a string, in which case must be converted to json
    if isinstance(config, basestring):
        config = json.loads(config)
        config_is_string = True

    topics = TopicCategory.objects.all()
    topicArray = []
    for topic in topics:
        topicArray.append([topic.identifier, topic.gn_description])
    topicArray.append(['General', 'General'])
    groups = set()

    config['topic_categories'] = topicArray

    config['proxy'] = '/proxy/?url='

    # TODO check permissions here
    config['edit_map'] = True

    # 3 different layer types
    #
    # 1. background layer: group: background, ows_url: None
    #
    # 2. WM local layer:
    #    ows_url: http://localhost:8080/geoserver/wms,
    #    layer_params = {"selected": true, "title": "camer_hyd_basins_vm0_2007",
    #       "url": "http://localhost:8080/geoserver/wms",
    #       "tiled": true, "detail_url": "http://worldmap.harvard.edu/data/geonode:camer_hyd_basins_vm0_2007",
    #       "local": true,
    #       "llbbox": [-94.549682617, 9.553222656, -82.972412109, 18.762207031]}
    #
    # 3. WM remote layer (HH):
    #    ows_url:
    #    http://192.168.33.15:8002/registry/hypermap/layer/13ff2fea-d479-4fc7-87a6-3eab7d349def/map/wmts/market/default_grid/$%7Bz%7D/$%7Bx%7D/$%7By%7D.png
    #    layer_params = {"title": "market", "selected": true,
    #       "detail_url": "http://192.168.33.15:8002/registry/hypermap/layer/13ff2fea-d479-4fc7-87a6-3eab7d349def/",
    #       "local": false}

    # let's detect WM or HH layers and alter configuration as needed
    bbox = [-180, -90, 180, 90]
    valid_layers = []
    for layer_config in config['map']['layers']:
        is_valid = True
        is_wm = False
        is_hh = False
        if 'source' not in layer_config:
            is_valid = False
            print 'Skipping this layer as it is missing source... %s' % layer_config
        else:
            source_id = layer_config['source']
            source = config['sources'][source_id]
            if 'url' in source:
                source_url = source['url']
                # hack
                source_url = source_url.replace('https', 'http')
                if settings.GEOSERVER_PUBLIC_LOCATION in source_url:
                    config['sources'][source_id]['url'] = source_url
                    if 'name' in layer_config:
                        is_wm = True
                if 'registry/hypermap' in source_url:
                    is_hh = True
            group = 'General'
            layer_config['tiled'] = True
            if is_wm:
                source = layer_config['source']
                config['sources'][source]['ptype'] = 'gxp_gnsource'
                config['sources'][source]['url'] = config['sources'][source][
                    'url'].replace('ows', 'wms')
                layer_config['local'] = True
                layer_config['queryable'] = True
                alternate = layer_config['name']
                layer = None
                try:
                    layer = Layer.objects.get(alternate=alternate)
                except Layer.DoesNotExist:
                    is_valid = False
                    print 'Skipping this layer as it is not existing in GeoNode... %s' % layer_config
                if layer:
                    layer_config['attributes'] = (get_layer_attributes(layer))
                    layer_config['url'] = layer.ows_url.replace('ows', 'wms')
                    if 'styles' not in layer_config:
                        if layer.default_style:
                            layer_config['styles'] = [
                                layer.default_style.name,
                            ]
                        else:
                            if layer.styles.all().count() > 0:
                                layer_config['styles'] = [
                                    layer.styles.all()[0].name,
                                ]
                    else:
                        if type(layer_config['styles']) == unicode:
                            try:
                                layer_config['styles'] = ast.literal_eval(
                                    layer_config['styles'])
                            except:  # noqa
                                layer_config['styles'] = [
                                    layer_config['styles'],
                                ]
                    if 'styles' not in layer_config:
                        is_valid = False
                        print 'Skipping this layer as it has not a style... %s' % layer_config
                    if layer.category:
                        group = layer.category.gn_description
                    layer_config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS',
                                                  'EPSG:900913')
                    bbox = layer.bbox[:-1]
                    # WorldMap GXP use a different bbox representation than GeoNode
                    bbox = [bbox[0], bbox[2], bbox[1], bbox[3]]
                    layer_config["bbox"] = [float(coord) for coord in bbox] if layer_config["srs"] != 'EPSG:900913' \
                        else llbbox_to_mercator([float(coord) for coord in bbox])
            if is_hh:
                layer_config['local'] = False
                layer_config['styles'] = ''
                hh_url = ('%smap/wmts/%s/default_grid/${z}/${x}/${y}.png' %
                          (layer_config['detail_url'], layer_config['name']))
                layer_config['url'] = hh_url
            if is_wm or is_hh:
                # bbox
                layer_config['llbbox'] = [float(coord) for coord in bbox]
                # group
                if 'group' not in layer_config:
                    layer_config['group'] = group
                else:
                    group = layer_config['group']
                if group not in groups:
                    groups.add(group)
                # let's make sure the group exists in topicArray (it could be a custom group create from user in GXP)
                is_in_topicarray = False
                for cat in topicArray:
                    if group == cat[1]:
                        is_in_topicarray = True
                if not is_in_topicarray:
                    topicArray.append([group, group])
        if is_valid:
            valid_layers.append(layer_config)

    config['map']['layers'] = valid_layers
    config['map']['groups'] = []

    # about and groups from existing map
    if map_obj:
        config['about']['introtext'] = map_obj.extmap.content_map
        config['about']['urlsuffix'] = map_obj.urlsuffix
        if map_obj.extmap.group_params:
            config["map"]["groups"] = uniqifydict(
                json.loads(map_obj.extmap.group_params), 'group')
    else:
        # TODO check if this works with different languages
        config['about']['introtext'] = unicode(settings.DEFAULT_MAP_ABSTRACT)

    for group in groups:
        if group not in json.dumps(config['map']['groups']):
            config['map']['groups'].append({
                "expanded": "true",
                "group": group
            })

    # make sure if gnsource is in sources
    add_gnsource = True
    for source in config['sources']:
        if 'ptype' in config['sources'][source]:
            if config['sources'][source]['ptype'] == 'gxp_gnsource':
                add_gnsource = False
    if add_gnsource:
        config['sources']['wm'] = {
            'url': settings.OGC_SERVER['default']['PUBLIC_LOCATION'] + "wms",
            'restUrl': '/gs/rest',
            'ptype': 'gxp_gnsource'
        }

    if config_is_string:
        config = json.dumps(config)

    return config
Exemple #42
0
def new_map_config(request):
    '''
    View that creates a new map.

    If the query argument 'copy' is given, the initial map is
    a copy of the map with the id specified, otherwise the
    default map configuration is used.  If copy is specified
    and the map specified does not exist a 404 is returned.
    '''
    DEFAULT_MAP_CONFIG, DEFAULT_BASE_LAYERS = default_map_config()

    if request.method == 'GET' and 'copy' in request.GET:
        mapid = request.GET['copy']
        map_obj = _resolve_map(request, mapid, 'base.view_resourcebase')

        map_obj.abstract = DEFAULT_ABSTRACT
        map_obj.title = DEFAULT_TITLE
        if request.user.is_authenticated():
            map_obj.owner = request.user
        config = map_obj.viewer_json(request.user)
        del config['id']
    else:
        if request.method == 'GET':
            params = request.GET
        elif request.method == 'POST':
            params = request.POST
        else:
            return HttpResponse(status=405)

        if 'layer' in params:
            bbox = None
            map_obj = Map(projection="EPSG:900913")
            layers = []
            for layer_name in params.getlist('layer'):
                try:
                    layer = _resolve_layer(request, layer_name)
                except ObjectDoesNotExist:
                    # bad layer, skip
                    continue

                if not request.user.has_perm(
                        'view_resourcebase',
                        obj=layer.get_self_resource()):
                    # invisible layer, skip inclusion
                    continue

                layer_bbox = layer.bbox
                # assert False, str(layer_bbox)
                if bbox is None:
                    bbox = list(layer_bbox[0:4])
                else:
                    bbox[0] = min(bbox[0], layer_bbox[0])
                    bbox[1] = max(bbox[1], layer_bbox[1])
                    bbox[2] = min(bbox[2], layer_bbox[2])
                    bbox[3] = max(bbox[3], layer_bbox[3])

                config = layer.attribute_config()

                # Add required parameters for GXP lazy-loading
                config["srs"] = layer.srid
                config["title"] = layer.title
                config["bbox"] = [
                    float(coord) for coord in bbox] if layer.srid == "EPSG:4326" else llbbox_to_mercator(
                    [
                        float(coord) for coord in bbox])
                config["queryable"] = True

                if layer.storeType == "remoteStore":
                    service = layer.service
                    maplayer = MapLayer(map=map_obj,
                                        name=layer.typename,
                                        ows_url=layer.ows_url,
                                        layer_params=json.dumps(config),
                                        visibility=True,
                                        source_params=json.dumps({
                                            "ptype": service.ptype,
                                            "remote": True,
                                            "url": service.base_url,
                                            "name": service.name}))
                else:
                    maplayer = MapLayer(
                        map=map_obj,
                        name=layer.typename,
                        ows_url=layer.ows_url,
                        layer_params=json.dumps(config),
                        visibility=True
                    )

                layers.append(maplayer)

            if bbox is not None:
                minx, miny, maxx, maxy = [float(c) for c in bbox]
                x = (minx + maxx) / 2
                y = (miny + maxy) / 2

                center = list(forward_mercator((x, y)))
                if center[1] == float('-inf'):
                    center[1] = 0

                BBOX_DIFFERENCE_THRESHOLD = 1e-5

                # Check if the bbox is invalid
                valid_x = (maxx - minx) ** 2 > BBOX_DIFFERENCE_THRESHOLD
                valid_y = (maxy - miny) ** 2 > BBOX_DIFFERENCE_THRESHOLD

                if valid_x:
                    width_zoom = math.log(360 / abs(maxx - minx), 2)
                else:
                    width_zoom = 15

                if valid_y:
                    height_zoom = math.log(360 / abs(maxy - miny), 2)
                else:
                    height_zoom = 15

                map_obj.center_x = center[0]
                map_obj.center_y = center[1]
                map_obj.zoom = math.ceil(min(width_zoom, height_zoom))

            config = map_obj.viewer_json(
                request.user, *(DEFAULT_BASE_LAYERS + layers))
            config['fromLayer'] = True
        else:
            config = DEFAULT_MAP_CONFIG
    return json.dumps(config)
Exemple #43
0
def layer_detail(request, layername, template='layers/layer_detail.html'):
    try:
        user_role = request.GET['user_role']
    except:
        user_role = None

    layer = _resolve_layer(request, layername, 'base.view_resourcebase',
                           _PERMISSION_MSG_VIEW)

    user = request.user
    edit_permit = False
    if layer.owner == user and layer.status in ['DRAFT', 'ACTIVE', 'DENIED']:
        edit_permit = True
    elif user in layer.group.get_managers() and layer.status in [
            'PENDING', 'ACTIVE', 'DENIED'
    ]:
        edit_permit = True

    if not edit_permit and layer.status == 'ACTIVE':
        edit_permit = True

    # if the edit request is not valid then just return from here
    if not edit_permit:
        return HttpResponse(loader.render_to_string(
            '401.html',
            RequestContext(request, {
                'error_message':
                _("You dont have permission to edit this layer.")
            })),
                            status=401)
        # return  HttpResponse('You dont have permission to edit this layer')

    # assert False, str(layer_bbox)
    config = layer.attribute_config()

    # Add required parameters for GXP lazy-loading
    layer_bbox = layer.bbox
    bbox = [float(coord) for coord in list(layer_bbox[0:4])]
    config["srs"] = getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913')
    config["bbox"] = bbox if config["srs"] != 'EPSG:900913' \
        else llbbox_to_mercator([float(coord) for coord in bbox])
    config["title"] = layer.title
    config["queryable"] = True

    if layer.storeType == "remoteStore":
        service = layer.service
        source_params = {
            "ptype": service.ptype,
            "remote": True,
            "url": service.base_url,
            "name": service.name
        }
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config),
                            source_params=json.dumps(source_params))
    else:
        maplayer = GXPLayer(name=layer.typename,
                            ows_url=layer.ows_url,
                            layer_params=json.dumps(config))

    # Update count for popularity ranking,
    # but do not includes admins or resource owners
    if request.user != layer.owner and not request.user.is_superuser:
        Layer.objects.filter(id=layer.id).update(
            popular_count=F('popular_count') + 1)

    # center/zoom don't matter; the viewer will center on the layer bounds
    map_obj = GXPMap(
        projection=getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'))

    NON_WMS_BASE_LAYERS = [
        la for la in default_map_config()[1] if la.ows_url is None
    ]

    metadata = layer.link_set.metadata().filter(
        name__in=settings.DOWNLOAD_FORMATS_METADATA)

    granules = None
    all_granules = None
    filter = None
    if layer.is_mosaic:
        try:
            cat = gs_catalog
            cat._cache.clear()
            store = cat.get_store(layer.name)
            coverages = cat.mosaic_coverages(store)

            filter = None
            try:
                if request.GET["filter"]:
                    filter = request.GET["filter"]
            except:
                pass

            offset = 10 * (request.page - 1)
            granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                limit=10,
                offset=offset,
                filter=filter)
            all_granules = cat.mosaic_granules(
                coverages['coverages']['coverage'][0]['name'],
                store,
                filter=filter)
        except:
            granules = {"features": []}
            all_granules = {"features": []}
    approve_form = ResourceApproveForm()
    deny_form = ResourceDenyForm()
    metadata_field_list = [
        'owner', 'title', 'date', 'date_type', 'edition', 'abstract',
        'purpose', 'maintenance_frequency', 'regions', 'restriction_code_type',
        'constraints_other', 'license', 'language',
        'spatial_representation_type', 'resource_type',
        'temporal_extent_start', 'temporal_extent_end',
        'supplemental_information', 'data_quality_statement', 'thumbnail_url',
        'elevation_regex', 'time_regex', 'keywords', 'category'
    ]
    if request.user == layer.owner or request.user in layer.group.get_managers(
    ):
        if not layer.attributes:
            messages.info(
                request,
                'Please update layer metadata, missing some informations')
        elif not layer.metadata_author:
            messages.info(
                request,
                'Please update layer metadata, missing some informations')
        else:
            for field in metadata_field_list:
                if not getattr(layer, layer._meta.get_field(field).name):
                    messages.info(
                        request,
                        'Please update layer metadata, missing some informations'
                    )
                    break

    # layer_name = layer.service_typename
    # geoserver_user = OGC_SERVER['default']['USER']
    # geoserver_password = OGC_SERVER['default']['PASSWORD']
    # style_url = OGC_SERVER['default']['PUBLIC_LOCATION'] + "rest/layers/" + layer_name + ".json"
    # response1 = requests.get(style_url, auth=HTTPBasicAuth(geoserver_user, geoserver_password))
    # sld_file_name_url = response1.json()['layer']['defaultStyle']['href']
    # response2 = requests.get(sld_file_name_url, auth=HTTPBasicAuth(geoserver_user, geoserver_password))
    # file_name = response2.json()['style']['filename']
    # sld_file_url = OGC_SERVER['default']['PUBLIC_LOCATION'] + "rest/styles/" + file_name
    # sld_content = requests.get(sld_file_url, auth=HTTPBasicAuth(geoserver_user, geoserver_password)).content
    #
    # xlink = ''
    # try:
    #     dict1 = xmltodict.parse(sld_content)
    #     dict2 = dict1['sld:StyledLayerDescriptor']['sld:NamedLayer']['sld:UserStyle']['sld:FeatureTypeStyle']\
    #     ['sld:Rule']['sld:PointSymbolizer']
    #     xlink = dict2['sld:Graphic']['sld:ExternalGraphic']['sld:OnlineResource']['@xlink:href']
    # except:
    #     pass
    xlink = style_chart_legend_color(layer)

    context_dict = {
        "resource":
        layer,
        'perms_list':
        get_perms(request.user, layer.get_self_resource()),
        "permissions_json":
        _perms_info_json(layer),
        "documents":
        get_related_documents(layer),
        "metadata":
        metadata,
        "is_layer":
        True,
        "wps_enabled":
        settings.OGC_SERVER['default']['WPS_ENABLED'],
        "granules":
        granules,
        "all_granules":
        all_granules,
        "filter":
        filter,
        "user_role":
        user_role,
        "approve_form":
        approve_form,
        "deny_form":
        deny_form,
        "denied_comments":
        LayerAuditActivity.objects.filter(
            layer_submission_activity__layer=layer),
        "status":
        layer.status,
        "chart_link":
        xlink
    }

    context_dict["viewer"] = json.dumps(
        map_obj.viewer_json(request.user, *(NON_WMS_BASE_LAYERS + [maplayer])))
    context_dict["preview"] = getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                      'leaflet')

    if request.user.has_perm('download_resourcebase',
                             layer.get_self_resource()):
        if layer.storeType == 'dataStore':
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_VECTOR)
        else:
            links = layer.link_set.download().filter(
                name__in=settings.DOWNLOAD_FORMATS_RASTER)
        context_dict["links"] = links

    if settings.SOCIAL_ORIGINS:
        context_dict["social_links"] = build_social_links(request, layer)

    return render_to_response(template, RequestContext(request, context_dict))