Пример #1
0
def map_remove(request, mapid, template='maps/map_remove.html'):
    ''' Delete a map, and its constituent layers. '''
    map_obj = _resolve_map(request, mapid, 'base.delete_resourcebase', _PERMISSION_MSG_VIEW)

    if request.method == 'GET':
        return render_to_response(template, RequestContext(request, {
            "map": map_obj
        }))

    elif request.method == 'POST':

        if getattr(settings, 'SLACK_ENABLED', False):

            slack_message = None
            try:
                from geonode.contrib.slack.utils import build_slack_message_map
                slack_message = build_slack_message_map("map_delete", map_obj)
            except:
                print "Could not build slack message for delete map."

            delete_map.delay(object_id=map_obj.id)

            try:
                from geonode.contrib.slack.utils import send_slack_messages
                send_slack_messages(slack_message)
            except:
                print "Could not send slack message for delete map."

        else:
            delete_map.delay(object_id=map_obj.id)

        return HttpResponseRedirect(reverse("maps_browse"))
Пример #2
0
def map_remove(request, mapid, template='maps/map_remove.html'):
    ''' Delete a map, and its constituent layers. '''
    map_obj = _resolve_map(request, mapid, 'base.delete_resourcebase',
                           _PERMISSION_MSG_VIEW)

    if request.method == 'GET':
        return render(request, template, context={"map": map_obj})

    elif request.method == 'POST':

        if getattr(settings, 'SLACK_ENABLED', False):

            slack_message = None
            try:
                from geonode.contrib.slack.utils import build_slack_message_map
                slack_message = build_slack_message_map("map_delete", map_obj)
            except BaseException:
                logger.error("Could not build slack message for delete map.")

            delete_map.delay(object_id=map_obj.id)

            try:
                from geonode.contrib.slack.utils import send_slack_messages
                send_slack_messages(slack_message)
            except BaseException:
                logger.error("Could not send slack message for delete map.")

        else:
            delete_map.delay(object_id=map_obj.id)

        return HttpResponseRedirect(reverse("maps_browse"))
Пример #3
0
def map_remove(request, mapid, template='maps/map_remove.html'):
    ''' Delete a map, and its constituent layers. '''
    map_obj = _resolve_map(request, mapid, 'base.delete_resourcebase',
                           _PERMISSION_MSG_VIEW)

    if request.method == 'GET':
        return render_to_response(template,
                                  RequestContext(request, {"map": map_obj}))

    elif request.method == 'POST':

        if getattr(settings, 'SLACK_ENABLED', False):

            slack_message = None
            try:
                from geonode.contrib.slack.utils import build_slack_message_map
                slack_message = build_slack_message_map("map_delete", map_obj)
            except:
                print "Could not build slack message for delete map."

            delete_map.delay(object_id=map_obj.id)
            # notify map owner that someone have deleted the map
            if request.user != map_obj.owner:
                recipient = map_obj.owner
                notify.send(request.user,
                            recipient=recipient,
                            actor=request.user,
                            target=map_obj,
                            verb='deleted your map')

            try:
                from geonode.contrib.slack.utils import send_slack_messages
                send_slack_messages(slack_message)
            except:
                print "Could not send slack message for delete map."

        else:
            delete_map.delay(object_id=map_obj.id)
            # notify map owner that someone have deleted the map
            if request.user != map_obj.owner:
                recipient = map_obj.owner
                notify.send(request.user,
                            recipient=recipient,
                            actor=request.user,
                            target=map_obj,
                            verb='deleted your map')

        return HttpResponseRedirect(reverse("maps_browse"))
Пример #4
0
def map_remove(request, mapid, template='maps/map_remove.html'):
    ''' Delete a map, and its constituent layers. '''
    try:
        map_obj = _resolve_map(
            request,
            mapid,
            'base.delete_resourcebase',
            _PERMISSION_MSG_VIEW)
    except PermissionDenied:
        return HttpResponse(_("Not allowed"), status=403)
    except Exception:
        raise Http404(_("Not found"))
    if not map_obj:
        raise Http404(_("Not found"))

    if request.method == 'GET':
        return render(request, template, context={
            "map": map_obj
        })
    elif request.method == 'POST':
        if getattr(settings, 'SLACK_ENABLED', False):
            slack_message = None
            try:
                from geonode.contrib.slack.utils import build_slack_message_map
                slack_message = build_slack_message_map("map_delete", map_obj)
            except Exception:
                logger.error("Could not build slack message for delete map.")
            delete_map.apply_async((map_obj.id, ))
            try:
                from geonode.contrib.slack.utils import send_slack_messages
                send_slack_messages(slack_message)
            except Exception:
                logger.error("Could not send slack message for delete map.")
        else:
            delete_map.apply_async((map_obj.id, ))

        register_event(request, EventType.EVENT_REMOVE, map_obj)

        return HttpResponseRedirect(reverse("maps_browse"))
Пример #5
0
def map_metadata(request, mapid, template='maps/map_metadata.html'):

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

    poc = map_obj.poc

    metadata_author = map_obj.metadata_author

    topic_category = map_obj.category

    if request.method == "POST":
        map_form = MapForm(request.POST, instance=map_obj, prefix="resource")
        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)
    else:
        map_form = MapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and map_form.is_valid(
    ) and category_form.is_valid():
        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']
        new_title = strip_tags(map_form.cleaned_data['title'])
        new_abstract = strip_tags(map_form.cleaned_data['abstract'])
        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                    send_slack_messages(build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(
                reverse(
                    'map_detail',
                    args=(
                        map_obj.id,
                    )))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(
                instance=metadata_author,
                prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    return render_to_response(template, RequestContext(request, {
        "map": map_obj,
        "map_form": map_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "category_form": category_form,
    }))
Пример #6
0
def map_metadata(request, mapid, template='maps/cread_map_metadata.html'):

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

    cmapqs = CReadResource.objects.filter(resource=map_obj)

    if len(cmapqs) == 0:
        logger.info('cread_resource does not exist for map %r', map_obj)
        cread_resource = None
    else:
        logger.debug('cread_resource found for map %r (%d)', map_obj,
                     len(cmapqs))
        cread_resource = cmapqs[0]

    poc = map_obj.poc
    metadata_author = map_obj.metadata_author
    topic_category = map_obj.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        map_form = CReadMapForm(
            #map_form = MapForm(
            request.POST,
            instance=map_obj,
            prefix="resource")
        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)
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(request.POST["cread_subcategory_choice_field"])
            if "cread_subcategory_choice_field" in request.POST else None)
    else:
        baseinfo_form = CReadBaseInfoForm(prefix="baseinfo",
                                          initial={
                                              'title': map_obj.title,
                                              'abstract': map_obj.abstract
                                          })
        map_form = CReadMapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field",
            initial=cread_subcategory.id if cread_subcategory else None)

    if request.method == "POST" \
            and baseinfo_form.is_valid() \
            and map_form.is_valid() \
            and cread_subcategory_form.is_valid():

        new_title = strip_tags(baseinfo_form.cleaned_data['title'])
        new_abstract = strip_tags(baseinfo_form.cleaned_data['abstract'])

        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if (cread_subcategory_form.is_valid()):
            logger.info("Checking CReadLayer record %r ",
                        cread_subcategory_form.is_valid())
            cread_subcat_id = cread_subcategory_form.cleaned_data[
                'cread_subcategory_choice_field']
            new_creadsubcategory = CReadSubCategory.objects.get(
                id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug("Selected cread cat/subcat: %s : %s / %s",
                         new_creadcategory.identifier, new_creadcategory.name,
                         new_creadsubcategory.identifier)

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = map_obj

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")
        # End cread category

        # Update original topic category according to cread category
        if category_form.is_valid():
            new_category = TopicCategory.objects.get(
                id=category_form.cleaned_data['category_choice_field'])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category from CREAD category")
            new_category = TopicCategory.objects.get(
                id=new_creadsubcategory.relatedtopic.id)

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                    send_slack_messages(
                        build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(
                reverse('map_detail', args=(map_obj.id, )))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author,
                                      prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(
        template,
        RequestContext(
            request, {
                "map": map_obj,
                "map_form": map_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "category_form": category_form,
                "baseinfo_form": baseinfo_form,
                "cread_sub_form": cread_subcategory_form,
                "cread_categories": categories_struct
            }))
Пример #7
0
def map_metadata(request, mapid, template='maps/map_metadata.html', ajax=True):
    map_obj = _resolve_map(request, mapid, 'base.change_resourcebase_metadata',
                           _PERMISSION_MSG_VIEW)

    poc = map_obj.poc

    metadata_author = map_obj.metadata_author

    topic_category = map_obj.category

    if request.method == "POST":
        map_form = MapForm(request.POST, instance=map_obj, prefix="resource")
        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)
    else:
        map_form = MapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and map_form.is_valid(
    ) and category_form.is_valid():
        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']
        new_regions = map_form.cleaned_data['regions']
        new_title = strip_tags(map_form.cleaned_data['title'])
        new_abstract = strip_tags(map_form.cleaned_data['abstract'])
        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        the_map = map_form.instance
        if new_poc is not None and new_author is not None:
            the_map.poc = new_poc
            the_map.metadata_author = new_author
        the_map.title = new_title
        the_map.abstract = new_abstract
        if new_keywords:
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
        if new_regions:
            the_map.regions.clear()
            the_map.regions.add(*new_regions)
        the_map.category = new_category
        the_map.save()

        if getattr(settings, 'SLACK_ENABLED', False):
            try:
                from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                send_slack_messages(
                    build_slack_message_map("map_edit", the_map))
            except BaseException:
                logger.error("Could not send slack message for modified map.")

        if not ajax:
            return HttpResponseRedirect(
                reverse('map_detail', args=(map_obj.id, )))

        message = map_obj.id

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

    # - POST Request Ends here -

    # Request.GET
    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author,
                                      prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

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

    config = map_obj.viewer_json(request.user, access_token)
    layers = MapLayer.objects.filter(map=map_obj.id)

    metadata_author_groups = []
    if request.user.is_superuser or request.user.is_staff:
        metadata_author_groups = GroupProfile.objects.all()
    else:
        try:
            all_metadata_author_groups = chain(
                request.user.group_list_all(),
                GroupProfile.objects.exclude(access="private").exclude(
                    access="public-invite"))
        except BaseException:
            all_metadata_author_groups = 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
        ]

    if settings.ADMIN_MODERATE_UPLOADS:
        if not request.user.is_superuser:
            map_form.fields['is_published'].widget.attrs.update(
                {'disabled': 'true'})

            can_change_metadata = request.user.has_perm(
                'change_resourcebase_metadata', map_obj.get_self_resource())
            try:
                is_manager = request.user.groupmember_set.all().filter(
                    role='manager').exists()
            except BaseException:
                is_manager = False
            if not is_manager or not can_change_metadata:
                map_form.fields['is_approved'].widget.attrs.update(
                    {'disabled': 'true'})

    return render(request,
                  template,
                  context={
                      "config":
                      json.dumps(config),
                      "resource":
                      map_obj,
                      "map":
                      map_obj,
                      "map_form":
                      map_form,
                      "poc_form":
                      poc_form,
                      "author_form":
                      author_form,
                      "category_form":
                      category_form,
                      "layers":
                      layers,
                      "preview":
                      getattr(settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY',
                              'geoext'),
                      "crs":
                      getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857'),
                      "metadata_author_groups":
                      metadata_author_groups,
                      "GROUP_MANDATORY_RESOURCES":
                      getattr(settings, 'GROUP_MANDATORY_RESOURCES', False),
                  })
Пример #8
0
def map_metadata(request, mapid, template='maps/map_metadata.html'):

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

    poc = map_obj.poc

    metadata_author = map_obj.metadata_author

    topic_category = map_obj.category

    if request.method == "POST":
        map_form = MapForm(request.POST, instance=map_obj, prefix="resource")
        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)
    else:
        map_form = MapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and map_form.is_valid(
    ) and category_form.is_valid():
        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']
        new_title = strip_tags(map_form.cleaned_data['title'])
        new_abstract = strip_tags(map_form.cleaned_data['abstract'])
        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                    send_slack_messages(
                        build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(
                reverse('map_detail', args=(map_obj.id, )))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author,
                                      prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    return render_to_response(
        template,
        RequestContext(
            request, {
                "map": map_obj,
                "map_form": map_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "category_form": category_form,
            }))
Пример #9
0
def map_metadata(request, mapid, template='maps/map_metadata.html'):

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

    poc = map_obj.poc

    metadata_author = map_obj.metadata_author

    topic_category = map_obj.category

    if request.method == "POST":
        map_form = MapForm(request.POST, instance=map_obj, prefix="resource")
        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)
    else:
        map_form = MapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and map_form.is_valid(
    ) and category_form.is_valid():
        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']
        new_title = strip_tags(map_form.cleaned_data['title'])
        new_abstract = strip_tags(map_form.cleaned_data['abstract'])
        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                    send_slack_messages(
                        build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(
                reverse('map_detail', args=(map_obj.id, )))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author,
                                      prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

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

    config = map_obj.viewer_json(request.user, access_token)
    layers = MapLayer.objects.filter(map=map_obj.id)

    metadata_author_groups = []
    if request.user.is_superuser:
        metadata_author_groups = GroupProfile.objects.all()
    else:
        metadata_author_groups = metadata_author.group_list_all()
    return render_to_response(
        template,
        RequestContext(
            request, {
                "config": json.dumps(config),
                "map": map_obj,
                "map_form": map_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "category_form": category_form,
                "layers": layers,
                "preview": getattr(settings, 'LAYER_PREVIEW_LIBRARY',
                                   'leaflet'),
                "crs": getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'),
                "metadata_author_groups": metadata_author_groups,
            }))
Пример #10
0
def map_metadata(
        request,
        mapid,
        template='maps/map_metadata.html',
        ajax=True):
    map_obj = _resolve_map(
        request,
        mapid,
        'base.change_resourcebase_metadata',
        _PERMISSION_MSG_VIEW)

    poc = map_obj.poc

    metadata_author = map_obj.metadata_author

    topic_category = map_obj.category

    if request.method == "POST":
        map_form = MapForm(request.POST, instance=map_obj, prefix="resource")
        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)
    else:
        map_form = MapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and map_form.is_valid(
    ) and category_form.is_valid():
        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']
        new_regions = map_form.cleaned_data['regions']
        new_title = strip_tags(map_form.cleaned_data['title'])
        new_abstract = strip_tags(map_form.cleaned_data['abstract'])
        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        the_map = map_form.instance
        if new_poc is not None and new_author is not None:
            the_map.poc = new_poc
            the_map.metadata_author = new_author
        the_map.title = new_title
        the_map.abstract = new_abstract
        if new_keywords:
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
        if new_regions:
            the_map.regions.clear()
            the_map.regions.add(*new_regions)
        the_map.category = new_category
        the_map.save()

        if getattr(settings, 'SLACK_ENABLED', False):
            try:
                from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                send_slack_messages(
                    build_slack_message_map(
                        "map_edit", the_map))
            except BaseException:
                logger.error("Could not send slack message for modified map.")

        if not ajax:
            return HttpResponseRedirect(
                reverse(
                    'map_detail',
                    args=(
                        map_obj.id,
                    )))

        message = map_obj.id

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

    # - POST Request Ends here -

    # Request.GET
    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(
                instance=metadata_author,
                prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    config = map_obj.viewer_json(request)
    layers = MapLayer.objects.filter(map=map_obj.id)

    metadata_author_groups = []
    if request.user.is_superuser or request.user.is_staff:
        metadata_author_groups = GroupProfile.objects.all()
    else:
        try:
            all_metadata_author_groups = chain(
                request.user.group_list_all(),
                GroupProfile.objects.exclude(
                    access="private").exclude(access="public-invite"))
        except BaseException:
            all_metadata_author_groups = 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]

    if settings.ADMIN_MODERATE_UPLOADS:
        if not request.user.is_superuser:
            map_form.fields['is_published'].widget.attrs.update(
                {'disabled': 'true'})

            can_change_metadata = request.user.has_perm(
                'change_resourcebase_metadata',
                map_obj.get_self_resource())
            try:
                is_manager = request.user.groupmember_set.all().filter(role='manager').exists()
            except BaseException:
                is_manager = False
            if not is_manager or not can_change_metadata:
                map_form.fields['is_approved'].widget.attrs.update(
                    {'disabled': 'true'})

    return render(request, template, context={
        "config": json.dumps(config),
        "resource": map_obj,
        "map": map_obj,
        "map_form": map_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "category_form": category_form,
        "layers": layers,
        "preview": getattr(settings, 'GEONODE_CLIENT_LAYER_PREVIEW_LIBRARY', 'geoext'),
        "crs": getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:3857'),
        "metadata_author_groups": metadata_author_groups,
        "GROUP_MANDATORY_RESOURCES": getattr(settings, 'GROUP_MANDATORY_RESOURCES', False),
    })
Пример #11
0
def map_metadata(request, mapid, template="maps/cread_map_metadata.html"):

    map_obj = _resolve_map(request, mapid, "base.change_resourcebase_metadata", _PERMISSION_MSG_VIEW)

    cmapqs = CReadResource.objects.filter(resource=map_obj)

    if len(cmapqs) == 0:
        logger.info("cread_resource does not exist for map %r", map_obj)
        cread_resource = None
    else:
        logger.debug("cread_resource found for map %r (%d)", map_obj, len(cmapqs))
        cread_resource = cmapqs[0]

    poc = map_obj.poc
    metadata_author = map_obj.metadata_author
    topic_category = map_obj.category
    cread_subcategory = cread_resource.subcategory if cread_resource else None

    if request.method == "POST":
        baseinfo_form = CReadBaseInfoForm(request.POST, prefix="baseinfo")
        map_form = CReadMapForm(
            # map_form = MapForm(
            request.POST,
            instance=map_obj,
            prefix="resource",
        )
        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,
        )
        cread_subcategory_form = CReadSubCategoryForm(
            request.POST,
            prefix="cread_subcategory_choice_field",
            initial=int(request.POST["cread_subcategory_choice_field"])
            if "cread_subcategory_choice_field" in request.POST
            else None,
        )
    else:
        baseinfo_form = CReadBaseInfoForm(
            prefix="baseinfo", initial={"title": map_obj.title, "abstract": map_obj.abstract}
        )
        map_form = CReadMapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field", initial=topic_category.id if topic_category else None
        )
        cread_subcategory_form = CReadSubCategoryForm(
            prefix="cread_subcategory_choice_field", initial=cread_subcategory.id if cread_subcategory else None
        )

    if (
        request.method == "POST"
        and baseinfo_form.is_valid()
        and map_form.is_valid()
        and cread_subcategory_form.is_valid()
    ):

        new_title = strip_tags(baseinfo_form.cleaned_data["title"])
        new_abstract = strip_tags(baseinfo_form.cleaned_data["abstract"])

        new_poc = map_form.cleaned_data["poc"]
        new_author = map_form.cleaned_data["metadata_author"]
        new_keywords = map_form.cleaned_data["keywords"]

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        # CRead category
        # note: call to is_valid is needed to compute the cleaned data
        if cread_subcategory_form.is_valid():
            logger.info("Checking CReadLayer record %r ", cread_subcategory_form.is_valid())
            cread_subcat_id = cread_subcategory_form.cleaned_data["cread_subcategory_choice_field"]
            new_creadsubcategory = CReadSubCategory.objects.get(id=cread_subcat_id)
            new_creadcategory = new_creadsubcategory.category
            logger.debug(
                "Selected cread cat/subcat: %s : %s / %s",
                new_creadcategory.identifier,
                new_creadcategory.name,
                new_creadsubcategory.identifier,
            )

            if cread_resource:
                logger.info("Update CReadResource record")
            else:
                logger.info("Create new CReadResource record")
                cread_resource = CReadResource()
                cread_resource.resource = map_obj

            cread_resource.category = new_creadcategory
            cread_resource.subcategory = new_creadsubcategory
            cread_resource.save()
        else:
            new_creadsubcategory = None
            logger.info("CRead subcategory form is not valid")
        # End cread category

        # Update original topic category according to cread category
        if category_form.is_valid():
            new_category = TopicCategory.objects.get(id=category_form.cleaned_data["category_choice_field"])
        elif new_creadsubcategory:
            logger.debug("Assigning default ISO category from CREAD category")
            new_category = TopicCategory.objects.get(id=new_creadsubcategory.relatedtopic.id)

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, "SLACK_ENABLED", False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages

                    send_slack_messages(build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(reverse("map_detail", args=(map_obj.id,)))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields["poc"].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(instance=metadata_author, prefix="author")
        else:
            map_form.fields["metadata_author"].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

    # creates cat - subcat association
    categories_struct = []
    for category in CReadCategory.objects.all():
        subcats = []
        for subcat in CReadSubCategory.objects.filter(category=category):
            subcats.append(subcat.id)
        categories_struct.append((category.id, category.description, subcats))

    return render_to_response(
        template,
        RequestContext(
            request,
            {
                "map": map_obj,
                "map_form": map_form,
                "poc_form": poc_form,
                "author_form": author_form,
                "category_form": category_form,
                "baseinfo_form": baseinfo_form,
                "cread_sub_form": cread_subcategory_form,
                "cread_categories": categories_struct,
            },
        ),
    )
Пример #12
0
def map_metadata(request, mapid, template='maps/map_metadata.html'):

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

    poc = map_obj.poc

    metadata_author = map_obj.metadata_author

    topic_category = map_obj.category

    if request.method == "POST":
        map_form = MapForm(request.POST, instance=map_obj, prefix="resource")
        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)
    else:
        map_form = MapForm(instance=map_obj, prefix="resource")
        category_form = CategoryForm(
            prefix="category_choice_field",
            initial=topic_category.id if topic_category else None)

    if request.method == "POST" and map_form.is_valid(
    ) and category_form.is_valid():
        new_poc = map_form.cleaned_data['poc']
        new_author = map_form.cleaned_data['metadata_author']
        new_keywords = map_form.cleaned_data['keywords']
        new_title = strip_tags(map_form.cleaned_data['title'])
        new_abstract = strip_tags(map_form.cleaned_data['abstract'])
        new_category = TopicCategory.objects.get(
            id=category_form.cleaned_data['category_choice_field'])

        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.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.has_changed and author_form.is_valid():
                new_author = author_form.save()

        if new_poc is not None and new_author is not None:
            the_map = map_form.save()
            the_map.poc = new_poc
            the_map.metadata_author = new_author
            the_map.title = new_title
            the_map.abstract = new_abstract
            the_map.save()
            the_map.keywords.clear()
            the_map.keywords.add(*new_keywords)
            the_map.category = new_category
            the_map.save()

            if getattr(settings, 'SLACK_ENABLED', False):
                try:
                    from geonode.contrib.slack.utils import build_slack_message_map, send_slack_messages
                    send_slack_messages(build_slack_message_map("map_edit", the_map))
                except:
                    print "Could not send slack message for modified map."

            return HttpResponseRedirect(
                reverse(
                    'map_detail',
                    args=(
                        map_obj.id,
                    )))

    if poc is None:
        poc_form = ProfileForm(request.POST, prefix="poc")
    else:
        if poc is None:
            poc_form = ProfileForm(instance=poc, prefix="poc")
        else:
            map_form.fields['poc'].initial = poc.id
            poc_form = ProfileForm(prefix="poc")
            poc_form.hidden = True

    if metadata_author is None:
        author_form = ProfileForm(request.POST, prefix="author")
    else:
        if metadata_author is None:
            author_form = ProfileForm(
                instance=metadata_author,
                prefix="author")
        else:
            map_form.fields['metadata_author'].initial = metadata_author.id
            author_form = ProfileForm(prefix="author")
            author_form.hidden = True

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

    config = map_obj.viewer_json(request.user, access_token)
    layers = MapLayer.objects.filter(map=map_obj.id)

    metadata_author_groups = []
    if request.user.is_superuser:
        metadata_author_groups = GroupProfile.objects.all()
    else:
        metadata_author_groups = metadata_author.group_list_all()
    return render_to_response(template, RequestContext(request, {
        "config": json.dumps(config),
        "map": map_obj,
        "map_form": map_form,
        "poc_form": poc_form,
        "author_form": author_form,
        "category_form": category_form,
        "layers": layers,
        "preview":  getattr(settings, 'LAYER_PREVIEW_LIBRARY', 'leaflet'),
        "crs":  getattr(settings, 'DEFAULT_MAP_CRS', 'EPSG:900913'),
        "metadata_author_groups": metadata_author_groups,
    }))