Ejemplo n.º 1
0
    def get_redirect_url(self, **kwargs):
        pagename = self.request.GET.get('pagename', '')
        if not pagename.strip():
            # No page name provided, so let's return a useful error message.
            messages.add_message(
                self.request, messages.SUCCESS,
                _('You must provide a page name when creating a page.'))
            return reverse('haystack_search')

        slug = slugify(pagename)
        region = self.get_region()
        if Page.objects.filter(slug=slug, region=region).exists():
            return Page.objects.get(slug=slug,
                                    region=region).get_absolute_url()
        else:
            if int(self.request.GET.get('show_templates', 0)):
                # Show them the 'empty page' page, which displays the list of
                # templates to create a page with.
                return reverse('pages:show',
                               kwargs={
                                   'region': region.slug,
                                   'slug': pagename
                               })
            else:
                return reverse('pages:edit',
                               kwargs={
                                   'region': region.slug,
                                   'slug': pagename
                               })
Ejemplo n.º 2
0
def varnish_invalidate_tag_view(slug, region):
    from pages.cache import varnish_invalidate_url

    current_urlconf = get_urlconf() or settings.ROOT_URLCONF

    if region.regionsettings.domain:
        # Has a domain, ugh. Need to clear two URLs on two hosts, in this case
        set_urlconf('main.urls_no_region')
        url = reverse('tags:tagged',
                      kwargs={
                          'slug': slug,
                          'region': region.slug
                      })
        varnish_invalidate_url(url, hostname=region.regionsettings.domain)

        # Now invalidate main path on LocalWiki hub
        set_urlconf('main.urls')
        url = reverse('tags:tagged',
                      kwargs={
                          'slug': slug,
                          'region': region.slug
                      })
        varnish_invalidate_url(url)
    else:
        url = reverse('tags:tagged',
                      kwargs={
                          'slug': slug,
                          'region': region.slug
                      })
        varnish_invalidate_url(url)

    set_urlconf(current_urlconf)
Ejemplo n.º 3
0
 def get_redirect_url(self, **kwargs):
     username = kwargs.get('username', None)
     rest = kwargs.get('rest', '')
     if rest:
         slug = "%s%s" % (username, rest)
         return reverse('user-page-content-view', kwargs={'slug': slug})
     else:
         return reverse('user-page', kwargs={'username': username})
     return
Ejemplo n.º 4
0
 def get_redirect_url(self, **kwargs):
     username = kwargs.get('username', None)
     rest = kwargs.get('rest', '')
     if rest:
         slug = "%s%s" % (username , rest)
         return reverse('user-page-content-view', kwargs={'slug': slug})
     else:
         return reverse('user-page', kwargs={'username': username})
     return 
Ejemplo n.º 5
0
    def render(self, context):
        region = context['region']
        nofollow = context.get('_render_nofollow', False)
        try:
            cls = ''
            url = self.href
            if isinstance(url, Variable):
                url = url.resolve(context)
            page = context['page']
            if self.is_relative_link(url):
                if url.startswith('_files/'):
                    filename = file_url_to_name(url)
                    url = reverse('pages:file-info',
                            kwargs={
                                'region': region.slug,
                                'slug': page.pretty_slug,
                                'file': filename}
                    )
                    try:
                        file = PageFile.objects.get(
                            slug__exact=page.slug, region=region, name__exact=filename)
                        cls = ' class="file_%s"' % file.rough_type
                    except PageFile.DoesNotExist:
                        cls = ' class="missing_link"'
                elif unquote_plus(url).startswith('tags/'):
                    cls = ' class="tag_link"'
                    url = unquote_plus(url)
                else:
                    # Convert to proper URL: My%20page -> My_page
                    url = name_to_url(url_to_name(url))

                    # Handle relative page links with anchors
                    url_parts = urlparse(url)
                    path = url_parts.path
                    fragment = '#%s' % url_parts.fragment if url_parts.fragment else ''

                    if fragment and not path.strip():
                        url = fragment
                    else:
                        try:
                            page = Page.objects.get(slug__exact=slugify(path), region=region)
                            url = reverse('pages:show', kwargs={'region': region.slug, 'slug': page.pretty_slug}) + fragment
                        except Page.DoesNotExist:
                            # Check if Redirect exists.
                            if not Redirect.objects.filter(source=slugify(path), region=region):
                                cls = ' class="missing_link"'
                            url = reverse('pages:show', kwargs={'region': region.slug, 'slug': path}) + fragment
            # External links + nofollow flag (e.g. on User pages) => render as nofollow:
            elif nofollow:
                return '<a rel="nofollow" href="%s"%s>%s</a>' % (url, cls, self.nodelist.render(context))

            return '<a href="%s"%s>%s</a>' % (url, cls,
                                              self.nodelist.render(context))
        except:
            return ''
Ejemplo n.º 6
0
 def get_success_url(self):
     region = self.get_region()
     return reverse('pages:show',
                    kwargs={
                        'region': region.slug,
                        'slug': self.object.pretty_slug
                    })
Ejemplo n.º 7
0
    def get_success_url(self):
        front_path = reverse('frontpage', kwargs={'region': self.object.slug})

        # Send them to the subdomain appropriate for the language,
        # in order to avoid the redirect. If we wait for the language
        # redirect here, then the messages cookie could get set on the
        # base domain, and then never cleared when viewed on the
        # language subdomain.
        region_lang = self._default_language
        request_lang = getattr(self.request, 'LANGUAGE_CODE',
                               settings.LANGUAGE_CODE)
        translation.activate(region_lang)
        self.request.LANGUAGE_CODE = region_lang

        if request_lang != region_lang:
            host = self.request.get_host().split('.')

            # We keep the language code in the subdomain, unless we're on the default language.
            if request_lang == settings.LANGUAGE_CODE:
                base_hostname = '.'.join(host)
            else:
                base_hostname = '.'.join(host[1:])

            if region_lang != settings.LANGUAGE_CODE:
                domain = '%s.%s' % (region_lang, base_hostname)
            else:
                domain = base_hostname

            return '%s://%s%s' % (self.request.is_secure() and 'https'
                                  or 'http', domain, front_path)

        return front_path
Ejemplo n.º 8
0
 def get_absolute_url(self):
     return reverse('pages:file',
                    kwargs={
                        'slug': self.slug,
                        'file': self.name,
                        'region': self.region
                    })
Ejemplo n.º 9
0
 def as_of_url(self, obj):
     return reverse('pages:file-as_of_date', kwargs={
         'slug': self.page(obj).pretty_slug,
         'region': obj.region.slug,
         'date': obj.version_info.date,
         'file': obj.name,
     })
Ejemplo n.º 10
0
 def diff_url(self, obj):
     return reverse('pages:file-compare-dates', kwargs={
         'slug': self.page(obj).pretty_slug,
         'region': obj.region.slug,
         'date1': obj.version_info.date,
         'file': obj.name,
     })
Ejemplo n.º 11
0
    def get_success_url(self):
        front_path = reverse('frontpage', kwargs={'region': self.object.slug})

        # Send them to the subdomain appropriate for the language,
        # in order to avoid the redirect. If we wait for the language
        # redirect here, then the messages cookie could get set on the
        # base domain, and then never cleared when viewed on the
        # language subdomain.
        region_lang = self._default_language
        request_lang = getattr(self.request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
        translation.activate(region_lang)
        self.request.LANGUAGE_CODE = region_lang

        if request_lang != region_lang:
            host = self.request.get_host().split('.')

            # We keep the language code in the subdomain, unless we're on the default language.
            if request_lang == settings.LANGUAGE_CODE:
                base_hostname = '.'.join(host)
            else:
                base_hostname = '.'.join(host[1:])

            if region_lang != settings.LANGUAGE_CODE:
                domain = '%s.%s' % (region_lang, base_hostname)
            else:
                domain = base_hostname

            return '%s://%s%s' % (
                self.request.is_secure() and 'https' or 'http',
                domain,
                front_path
            )

        return front_path
Ejemplo n.º 12
0
 def get_success_url(self):
     region = self.get_region()
     messages.add_message(self.request, messages.SUCCESS,
         self.success_msg())
     # Redirect back to the page.
     return reverse('pages:show',
         kwargs={'region': region.slug, 'slug': self.new_pagename})
Ejemplo n.º 13
0
 def get_success_url(self):
     region = self.get_region()
     messages.add_message(self.request, messages.SUCCESS,
         self.success_msg())
     # Redirect back to the (now empty) page on the old region.
     return reverse('pages:show',
         kwargs={'region': region.slug, 'slug': self.page.pretty_slug})
Ejemplo n.º 14
0
 def get_success_url(self):
     region = self.get_region()
     # Redirect back to the file info page.
     return reverse('pages:file-info', kwargs={
         'region': region.slug,
          'slug': self.kwargs['slug'],
          'file': self.kwargs['file']
     })
Ejemplo n.º 15
0
def page_base_path(region):
    # Django caches repeated resolver lookups, so this should be
    # pretty fast.
    return reverse('pages:show',
                   kwargs={
                       'region': region.slug,
                       'slug': 'foobar'
                   })[:-6]
Ejemplo n.º 16
0
def region_404_response(request, slug):
    region_add = reverse('regions:add')
    msg = (_(
        '<p>Region "%s" not found. Would you like to <a href="%s" rel="nofollow">create it</a>?</p>'
    ) % (slug, region_add))
    html = render_to_string('404.html', {'message': msg},
                            RequestContext(request))
    return HttpResponseNotFound(html)
Ejemplo n.º 17
0
 def get_success_url(self):
     region = self.get_region()
     # Redirect back to the page.
     return reverse('pages:show',
                    kwargs={
                        'region': region.slug,
                        'slug': self.kwargs.get('original_slug')
                    })
Ejemplo n.º 18
0
 def diff_url(self, obj):
     return reverse('pages:file-compare-dates',
                    kwargs={
                        'slug': self.page(obj).pretty_slug,
                        'region': obj.region.slug,
                        'date1': obj.version_info.date,
                        'file': obj.name,
                    })
Ejemplo n.º 19
0
 def as_of_url(self, obj):
     return reverse('pages:file-as_of_date',
                    kwargs={
                        'slug': self.page(obj).pretty_slug,
                        'region': obj.region.slug,
                        'date': obj.version_info.date,
                        'file': obj.name,
                    })
Ejemplo n.º 20
0
 def get_success_url(self):
     region = self.get_region()
     # Redirect back to the file info page.
     return reverse('pages:file-info',
                    kwargs={
                        'region': region.slug,
                        'slug': self.kwargs['slug'],
                        'file': self.kwargs['file']
                    })
Ejemplo n.º 21
0
 def get_success_url(self):
     region = self.get_region()
     messages.add_message(self.request, messages.SUCCESS,
                          self.success_msg())
     # Redirect back to the page.
     return reverse('pages:show',
                    kwargs={
                        'region': region.slug,
                        'slug': self.new_pagename
                    })
Ejemplo n.º 22
0
 def get_success_url(self):
     region = self.get_region()
     messages.add_message(self.request, messages.SUCCESS,
                          self.success_msg())
     # Redirect back to the (now empty) page on the old region.
     return reverse('pages:show',
                    kwargs={
                        'region': region.slug,
                        'slug': self.page.pretty_slug
                    })
 def get_page_url(self):
     if self.page:
         slug = self.page.pretty_slug
     else:
         slug = name_to_url(self.name)
     return reverse('pages:show',
                    kwargs={
                        'region': self.region.slug,
                        'slug': slug
                    })
Ejemplo n.º 24
0
    def get_redirect_url(self, **kwargs):
        pagename = self.request.GET.get('pagename', '')
        if not pagename.strip():
            # No page name provided, so let's return a useful error message.
            messages.add_message(self.request, messages.SUCCESS,
                _('You must provide a page name when creating a page.'))
            return reverse('haystack_search')

        slug = slugify(pagename)
        region = self.get_region()
        if Page.objects.filter(slug=slug, region=region).exists():
            return Page.objects.get(slug=slug, region=region).get_absolute_url()
        else:
            if int(self.request.GET.get('show_templates', 0)):
                # Show them the 'empty page' page, which displays the list of
                # templates to create a page with.
                return reverse('pages:show', kwargs={'region': region.slug, 'slug': pagename})
            else:
                return reverse('pages:edit', kwargs={'region': region.slug, 'slug': pagename})
Ejemplo n.º 25
0
 def get_context_data(self, *args, **kwargs):
     c = super(RegionActivity, self).get_context_data(*args, **kwargs)
     c.update({
         'rc_url': reverse('region-activity',
             kwargs={'region': self.get_region().slug}),
         'ignore_types': IGNORE_TYPES,
         'added_types': ADDED_TYPES,
         'deleted_types': DELETED_TYPES,
         'reverted_types': REVERTED_TYPES,
     })
     return c
Ejemplo n.º 26
0
def varnish_invalidate_tag_view(slug, region):
    from pages.cache import varnish_invalidate_url

    current_urlconf = get_urlconf() or settings.ROOT_URLCONF

    if region.regionsettings.domain:
        # Has a domain, ugh. Need to clear two URLs on two hosts, in this case
        set_urlconf('main.urls_no_region')
        url = reverse('tags:tagged', kwargs={'slug': slug, 'region': region.slug})
        varnish_invalidate_url(url, hostname=region.regionsettings.domain)

        # Now invalidate main path on LocalWiki hub
        set_urlconf('main.urls')
        url = reverse('tags:tagged', kwargs={'slug': slug, 'region': region.slug})
        varnish_invalidate_url(url)
    else:
        url = reverse('tags:tagged', kwargs={'slug': slug, 'region': region.slug})
        varnish_invalidate_url(url)

    set_urlconf(current_urlconf)
Ejemplo n.º 27
0
    def form_valid(self, form):
        if not self.request.user.is_authenticated():
            # If they're not logged in, let's save the form data,
            # pass it along to the log-in-or-create-account page.
            # Later, we'll re-process it here.
            url = '%s?%s' % (reverse('regions:post-save-log-in'), self.form_to_qs(form))
            return HttpResponseRedirect(url)

        self._default_language = form.cleaned_data['default_language']
        response = super(RegionCreateView, self).form_valid(form)
        create_region(self.request, region=self.object, form=form)
        return response
Ejemplo n.º 28
0
def handle_image(elem, context=None):
    # only handle resized images
    do_thumbnail = True
    style = parse_style(elem.attrib.get('style', ''))
    if 'width' not in style or 'height' not in style:
        do_thumbnail = False

    src = desanitize(elem.attrib.get('src', ''))
    if not src.startswith(_files_url):
        return

    if not context or 'page' not in context:
        return

    page = context['page']
    try:
        file = PageFile.objects.get(slug__exact=page.slug,
                                    name__exact=file_url_to_name(src),
                                    region=page.region)
    except PageFile.DoesNotExist:
        return

    if do_thumbnail:
        width = int(style['width'].replace('px', ''))
        height = int(style['height'].replace('px', ''))
        escaped_filename = escape_quotes(file.file.name)
        before = '{%% thumbnail "%s" "%dx%d" as im %%}' % (escaped_filename,
                                                           width, height)
        after = '{% endthumbnail %}'
        # HTML will want to encode {{ }} inside a src / srcset, and we don't
        # want that, so we will just rename it to src_thumb until just before
        # it's output.
        del elem.attrib['src']
        elem.attrib['src_thumb'] = '{{ im.url }}'
        elem.attrib['srcset_thumb'] = ('{{ im.url|resolution:"2x" }} 2x, '
                                       '{{ im.url|resolution:"1.5x" }} 1.5x')
        insert_text_before(before, elem)
        elem.tail = after + (elem.tail or '')
    else:
        elem.attrib['src'] = file.file.url
    info_url = reverse('pages:file-info',
                       kwargs={
                           'region': page.region.slug,
                           'slug': page.pretty_slug,
                           'file': file.name
                       })
    link = etree.Element('a')
    link.attrib['href'] = info_url
    elem.addprevious(link)
    elem.getparent().remove(elem)
    link.append(elem)
    return False
Ejemplo n.º 29
0
    def form_valid(self, form):
        if not self.request.user.is_authenticated():
            # If they're not logged in, let's save the form data,
            # pass it along to the log-in-or-create-account page.
            # Later, we'll re-process it here.
            url = '%s?%s' % (reverse('regions:post-save-log-in'),
                             self.form_to_qs(form))
            return HttpResponseRedirect(url)

        self._default_language = form.cleaned_data['default_language']
        response = super(RegionCreateView, self).form_valid(form)
        create_region(self.request, region=self.object, form=form)
        return response
Ejemplo n.º 30
0
 def form_valid(self, form):
     region = self.get_region()
     try:
         p = Page.objects.get(
             slug=slugify(self.kwargs['slug']),
             region=region
         )
         self.new_pagename = form.cleaned_data['pagename']
         p.rename_to(self.new_pagename)
     except PageExistsError, s:
         messages.add_message(self.request, messages.SUCCESS, s)
         return HttpResponseRedirect(
             reverse('pages:show', kwargs={'region': region.slug, 'slug': p.slug}))
Ejemplo n.º 31
0
def handle_image(elem, context=None):
    # only handle resized images
    do_thumbnail = True
    style = parse_style(elem.attrib.get('style', ''))
    if 'width' not in style or 'height' not in style:
        do_thumbnail = False

    src = desanitize(elem.attrib.get('src', ''))
    if not src.startswith(_files_url):
        return

    if not context or 'page' not in context:
        return

    page = context['page']
    try:
        file = PageFile.objects.get(
            slug__exact=page.slug,
            name__exact=file_url_to_name(src),
            region=page.region
            )
    except PageFile.DoesNotExist:
        return

    if do_thumbnail:
        width = int(style['width'].replace('px', ''))
        height = int(style['height'].replace('px', ''))
        escaped_filename = escape_quotes(file.file.name)
        before = '{%% thumbnail "%s" "%dx%d" as im %%}' % (escaped_filename,
                                                           width, height)
        after = '{% endthumbnail %}'
        # HTML will want to encode {{ }} inside a src / srcset, and we don't
        # want that, so we will just rename it to src_thumb until just before
        # it's output.
        del elem.attrib['src']
        elem.attrib['src_thumb'] = '{{ im.url }}'
        elem.attrib['srcset_thumb'] = (
            '{{ im.url|resolution:"2x" }} 2x, '
            '{{ im.url|resolution:"1.5x" }} 1.5x')
        insert_text_before(before, elem)
        elem.tail = after + (elem.tail or '')
    else:
        elem.attrib['src'] = file.file.url
    info_url = reverse('pages:file-info',
        kwargs={'region': page.region.slug, 'slug': page.pretty_slug, 'file': file.name})
    link = etree.Element('a')
    link.attrib['href'] = info_url
    elem.addprevious(link)
    elem.getparent().remove(elem)
    link.append(elem)
    return False
Ejemplo n.º 32
0
    def diff_url(self, obj):
        """
        args:
            obj: the historical instance, taken from your queryset(),
                 that we are displaying on the Activity page.

        returns:
            the diff url associated with obj.
        """
        return reverse('%s:compare-dates' % obj._meta.app_label, kwargs={
            'slug': self.page(obj).pretty_slug,
            'region': self.page(obj).region.slug,
            'date1': obj.version_info.date,
        })
Ejemplo n.º 33
0
    def as_of_url(self, obj):
        """
        args:
            obj: the historical instance, taken from your queryset(),
                 that we are displaying on the Activity page.

        returns:
            the url to display the version of the obj specified.
        """
        return reverse('%s:as_of_date' % obj._meta.app_label, kwargs={
            'slug': self.page(obj).pretty_slug,
            'region': self.page(obj).region.slug,
            'date': obj.version_info.date,
        })
Ejemplo n.º 34
0
    def post(self, request, *args, **kwargs):
        slug = kwargs['slug']
        region = self.get_region()

        error = None
        file_form = PageFileForm(request.POST, request.FILES)

        uploaded = request.FILES['file']
        if 'file' in kwargs:
            # Replace existing file if exists
            try:
                file = PageFile.objects.get(slug__exact=slug,
                                            name__exact=kwargs['file'],
                                            region=region)
                file.file = uploaded
            except PageFile.DoesNotExist:
                file = PageFile(file=uploaded,
                                name=uploaded.name,
                                slug=slug,
                                region=region)
            file_form.instance = file
            if not file_form.is_valid():
                error = file_form.errors.values()[0]
            else:
                file_form.save()

            if error is not None:
                return HttpResponseBadRequest(error)
            return HttpResponseRedirect(
                reverse('pages:file-info',
                        kwargs={
                            'region': region.slug,
                            'slug': slug,
                            'file': kwargs['file']
                        }))

        # uploaded from ckeditor
        filename = _find_available_filename(uploaded.name, slug, region)
        relative_url = '_files/' + urlquote(filename)
        try:
            file = PageFile(file=uploaded,
                            name=filename,
                            slug=slug,
                            region=region)
            file.save()
            return ck_upload_result(request, url=relative_url)
        except IntegrityError:
            error = _('A file with this name already exists')
        return ck_upload_result(request, url=relative_url, message=error)
Ejemplo n.º 35
0
    def as_of_url(self, obj):
        """
        args:
            obj: the historical instance, taken from your queryset(),
                 that we are displaying on the Activity page.

        returns:
            the url to display the version of the obj specified.
        """
        return reverse('%s:as_of_date' % obj._meta.app_label,
                       kwargs={
                           'slug': self.page(obj).pretty_slug,
                           'region': self.page(obj).region.slug,
                           'date': obj.version_info.date,
                       })
Ejemplo n.º 36
0
    def diff_url(self, obj):
        """
        args:
            obj: the historical instance, taken from your queryset(),
                 that we are displaying on the Activity page.

        returns:
            the diff url associated with obj.
        """
        return reverse('%s:compare-dates' % obj._meta.app_label,
                       kwargs={
                           'slug': self.page(obj).pretty_slug,
                           'region': self.page(obj).region.slug,
                           'date1': obj.version_info.date,
                       })
Ejemplo n.º 37
0
 def form_valid(self, form):
     region = self.get_region()
     try:
         p = Page.objects.get(slug=slugify(self.kwargs['slug']),
                              region=region)
         self.new_pagename = form.cleaned_data['pagename']
         p.rename_to(self.new_pagename)
     except PageExistsError, s:
         messages.add_message(self.request, messages.SUCCESS, s)
         return HttpResponseRedirect(
             reverse('pages:show',
                     kwargs={
                         'region': region.slug,
                         'slug': p.slug
                     }))
Ejemplo n.º 38
0
 def get_context_data(self, *args, **kwargs):
     c = super(RegionActivity, self).get_context_data(*args, **kwargs)
     c.update({
         'rc_url':
         reverse('region-activity',
                 kwargs={'region': self.get_region().slug}),
         'ignore_types':
         IGNORE_TYPES,
         'added_types':
         ADDED_TYPES,
         'deleted_types':
         DELETED_TYPES,
         'reverted_types':
         REVERTED_TYPES,
     })
     return c
Ejemplo n.º 39
0
    def post(self, request, *args, **kwargs):
        slug = kwargs['slug']
        region = self.get_region()

        error = None
        file_form = PageFileForm(request.POST, request.FILES)

        uploaded = request.FILES['file']
        if 'file' in kwargs:
            # Replace existing file if exists
            try:
                file = PageFile.objects.get(
                    slug__exact=slug,
                    name__exact=kwargs['file'],
                    region=region
                )
                file.file = uploaded
            except PageFile.DoesNotExist:
                file = PageFile(
                    file=uploaded,
                    name=uploaded.name,
                    slug=slug,
                    region=region
                )
            file_form.instance = file
            if not file_form.is_valid():
                error = file_form.errors.values()[0]
            else:
                file_form.save()

            if error is not None:
                return HttpResponseBadRequest(error)
            return HttpResponseRedirect(
                reverse('pages:file-info',
                        kwargs={'region': region.slug, 'slug': slug, 'file': kwargs['file']}))

        # uploaded from ckeditor
        filename = _find_available_filename(uploaded.name, slug, region)
        relative_url = '_files/' + urlquote(filename)
        try:
            file = PageFile(file=uploaded, name=filename, slug=slug, region=region)
            file.save()
            return ck_upload_result(request, url=relative_url)
        except IntegrityError:
            error = _('A file with this name already exists')
        return ck_upload_result(request, url=relative_url, message=error)
Ejemplo n.º 40
0
    def form_valid(self, form):
        tag_slug = form.cleaned_data['tag_slug']

        if not self.object:
            # Page doesn't exist yet, so let's redirect to page creation screen
            page_name = form.cleaned_data['page_name']
            p = Page(name=page_name, region=self.get_region())
            url = reverse('pages:edit', kwargs={'slug': page_name, 'region': self.get_region()})
            return HttpResponseRedirect('%s?tag=%s' % (url, tag_slug))

        t = Tag.objects.get(slug=tag_slug, region=self.get_region())
        pts = PageTagSet.objects.filter(page=self.object, region=self.get_region())
        if pts.exists():
            pts = pts[0]
        else:
            pts = PageTagSet(page=self.object, region=self.get_region()) 

        tag_name = Tag._meta.verbose_name.lower()
        pts.save(comment=_("added %(name)s %(added)s.") % {'name': tag_name, 'added': tag_slug})

        if pts.tags and t not in pts.tags.all():
            pts.tags.add(t)

        return super(AddSingleTagView, self).form_valid(form)
Ejemplo n.º 41
0
 def get_context_data(self, *args, **kwargs):
     context = super(RegionPostSaveLogInView, self).get_context_data(*args, **kwargs)
     region_slug = self.request.GET.get('slug')
     context['next'] = reverse('frontpage', kwargs={'region': region_slug})
     return context
Ejemplo n.º 42
0
def region_404_response(request, slug):
    region_add = reverse('regions:add')
    msg = (_('<p>Region "%s" not found. Would you like to <a href="%s" rel="nofollow">create it</a>?</p>') %
        (slug, region_add))
    html = render_to_string('404.html', {'message': msg}, RequestContext(request))
    return HttpResponseNotFound(html)
Ejemplo n.º 43
0
 def get_absolute_url(self):
     return reverse('tags:tagged', kwargs={'region': self.region.slug, 'slug':self.slug})
Ejemplo n.º 44
0
 def popup_html(obj):
     url = reverse('frontpage', kwargs={'region': obj.slug}) 
     return '<a href="%s">%s</a>' % (url, obj.full_name)
Ejemplo n.º 45
0
    def render(self, context):
        region = context['region']
        nofollow = context.get('_render_nofollow', False)
        try:
            cls = ''
            url = self.href
            if isinstance(url, Variable):
                url = url.resolve(context)
            page = context['page']
            if self.is_relative_link(url):
                if url.startswith('_files/'):
                    filename = file_url_to_name(url)
                    url = reverse('pages:file-info',
                                  kwargs={
                                      'region': region.slug,
                                      'slug': page.pretty_slug,
                                      'file': filename
                                  })
                    try:
                        file = PageFile.objects.get(slug__exact=page.slug,
                                                    region=region,
                                                    name__exact=filename)
                        cls = ' class="file_%s"' % file.rough_type
                    except PageFile.DoesNotExist:
                        cls = ' class="missing_link"'
                elif unquote_plus(url).startswith('tags/'):
                    cls = ' class="tag_link"'
                    url = unquote_plus(url)
                else:
                    # Convert to proper URL: My%20page -> My_page
                    url = name_to_url(url_to_name(url))

                    # Handle relative page links with anchors
                    url_parts = urlparse(url)
                    path = url_parts.path
                    fragment = '#%s' % url_parts.fragment if url_parts.fragment else ''

                    if fragment and not path.strip():
                        url = fragment
                    else:
                        try:
                            page = Page.objects.get(slug__exact=slugify(path),
                                                    region=region)
                            url = reverse('pages:show',
                                          kwargs={
                                              'region': region.slug,
                                              'slug': page.pretty_slug
                                          }) + fragment
                        except Page.DoesNotExist:
                            # Check if Redirect exists.
                            if not Redirect.objects.filter(
                                    source=slugify(path), region=region):
                                cls = ' class="missing_link"'
                            url = reverse('pages:show',
                                          kwargs={
                                              'region': region.slug,
                                              'slug': path
                                          }) + fragment
            # External links + nofollow flag (e.g. on User pages) => render as nofollow:
            elif nofollow:
                return '<a rel="nofollow" href="%s"%s>%s</a>' % (
                    url, cls, self.nodelist.render(context))

            return '<a href="%s"%s>%s</a>' % (url, cls,
                                              self.nodelist.render(context))
        except:
            return ''
Ejemplo n.º 46
0
def varnish_invalidate_global_tag_view(slug):
    from pages.cache import varnish_invalidate_url

    url = reverse('tags:global-tagged', kwargs={'slug': slug})
    varnish_invalidate_url(url)
Ejemplo n.º 47
0
def get_absolute_url(self):
    return reverse('user-page', kwargs={'username': smart_str(self.username)})
Ejemplo n.º 48
0
 def get_success_url(self):
     return reverse('regions:settings', kwargs={'region': self.get_region().slug})
Ejemplo n.º 49
0
 def handler404(self, request, *args, **kwargs):
     return HttpResponseRedirect(
         reverse('pages:show', kwargs={
             'slug': kwargs['slug'], 'region': kwargs['region']}))
Ejemplo n.º 50
0
def get_registration_success_url(request):
    if request.GET.get('post_save', None):
        if request.GET.get('post_save') == 'create_region':
            return reverse('frontpage', kwargs={'region': request.GET.get('slug')})
    return None
Ejemplo n.º 51
0
 def get_success_url(self):
     # Redirect back to the file info page.
     return reverse('pages:tags-history',
         args=[self.kwargs['region'], self.kwargs['slug']])
Ejemplo n.º 52
0
 def get_success_url(self):
     return reverse('pages:show',
                    kwargs={
                        'slug': self.get_object().slug,
                        'region': self.get_region().slug
                    })
Ejemplo n.º 53
0
    def success_msg(self):
        # NOTE: This is eventually marked as safe when rendered in our
        # template.  So do *not* allow unescaped user input!
        #
        # XXX TODO: Refactor this into something more general + show this
        # message on other content types (maps, tags)
        default_message = '<div>%s</div>' % _(
            'Thank you for your changes. '
            'Your attention to detail is appreciated.')
        log_in_message = ''
        map_create_link = ''
        follow_message = ''
        share_message = ''

        if not self.request.user.is_authenticated():
            default_message = '<div>%s</div>' % (_(
                'Changes saved! To use your name when editing, please '
                '<a href="%(login_url)s?next=%(current_path)s"><strong>log in</strong></a> or '
                '<a href="%(register_url)s?next=%(current_path)s"><strong>create an account</strong></a>.'
            ) % {
                'login_url':
                reverse('auth_login'),
                'current_path':
                self.request.path,
                'register_url':
                reverse('registration_register')
            })
        if not hasattr(self.object, 'mapdata') and not is_user_page(
                self.object):
            slug = self.object.pretty_slug
            map_create_link = (_(
                '<p class="create_map"><a href="%s" class="button little map">'
                '<span class="text">Create a map</span></a> '
                'for this page?</p>') %
                               reverse('maps:edit',
                                       kwargs={
                                           'region': self.object.region.slug,
                                           'slug': slug
                                       }))

        if self.request.user.is_authenticated() and not map_create_link:
            if is_user_page(self.object):
                obj = User.objects.get(
                    username__iexact=self.kwargs['original_slug'][6:])
                following = Follow.objects.filter(user=self.request.user,
                                                  target_user=obj).exists()
            else:
                following = Follow.objects.filter(
                    user=self.request.user, target_page=self.object).exists()
                obj = self.object

            # They're already auto-following their own user page
            own_user_page = slugify(self.object.name) == slugify(
                'users/%s' % self.request.user.username)
            if not following and not own_user_page:
                t = Template("""
{% load follow_tags %}
{% load i18n %}
{% trans "page" as object_type %}
{% follow_form page %}
                """)
                c = RequestContext(self.request, {
                    'page': obj,
                    'follow_text': _("Follow this page"),
                })
                follow_message = '<div>%s</div>' % (
                    _("%(follow_page_notice)s for updates!") % {
                        'follow_page_notice': t.render(c)
                    })

        if not map_create_link:
            # Translators: Keep under < 100 characters
            twitter_status = _(
                "I just edited %(page)s on @localwiki! %(page_url)s") % {
                    'page':
                    self.object.name,
                    'page_url': ('https://localwiki.org%s' %
                                 self.object.get_url_for_share(self.request)),
                }
            twitter_status = urllib.quote(twitter_status.encode('utf-8'))
            share_message = _("Tell the world about this page:")
            share_message = "%(share_message)s<div>%(fb_link)s %(twitter_link)s</div>" % {
                'share_message':
                share_message,
                'fb_link':
                ('<a target="_blank" class="button tiny" href="https://www.facebook.com/sharer/sharer.php?u=https://localwiki.org%s"></a>'
                 % self.object.get_url_for_share(self.request)),
                'twitter_link':
                ('<a target="_blank" class="button tiny" href="https://twitter.com/home?status=%s"></a>'
                 % twitter_status)
            }
            share_message = '<div class="share_message">%s</div>' % share_message

        return '%s%s%s%s' % (default_message, map_create_link, follow_message,
                             share_message)
Ejemplo n.º 54
0
 def get_success_url(self):
     messages.add_message(self.request, messages.SUCCESS, _("Banned users updated."))
     return reverse('regions:settings', kwargs={'region': self.get_region().slug})
Ejemplo n.º 55
0
 def get_success_url(self):
     next = self.request.POST.get('next', None)
     if next:
         return next
     return reverse('pages:tags',
         args=[self.kwargs.get('region'), self.kwargs.get('slug')])