Exemple #1
0
 def get_absolute_url(self, no_slug=False):
     if self.is_answer():
         return u'%(base)s%(slug)s?answer=%(id)d#answer-container-%(id)d' % \
                 {
                     'base': urlresolvers.reverse('question', args=[self.question.id]),
                     'slug': django_urlquote(slugify(self.question.title)),
                     'id': self.id
                 }
     elif self.is_question():
         url = urlresolvers.reverse('question', args=[self.id])
         if no_slug == True:
             return url
         else:
             return url + django_urlquote(self.slug)
     raise NotImplementedError
Exemple #2
0
 def get_absolute_url(self, no_slug = False):
     if self.is_answer():
         return u'%(base)s%(slug)s?answer=%(id)d#answer-container-%(id)d' % \
                 {
                     'base': urlresolvers.reverse('question', args=[self.question.id]),
                     'slug': django_urlquote(slugify(self.question.title)),
                     'id': self.id
                 }
     elif self.is_question():
         url = urlresolvers.reverse('question', args=[self.id])
         if no_slug == True:
             return url
         else:
             return url + django_urlquote(self.slug)
     raise NotImplementedError
Exemple #3
0
def results(request):
    """Results of a search query.
    """
    # prep query for elasticsearch
    model = request.GET.get('model', None)
    q = django_urlquote(request.GET.get('query', ''))
    filters = {}
    fields = models.all_list_fields()
    sort = {
        'record_created': request.GET.get('record_created', ''),
        'record_lastmod': request.GET.get('record_lastmod', ''),
    }
    # do the query
    results = elasticsearch.query(settings.ELASTICSEARCH_HOST_PORT,
                                  settings.DOCUMENT_INDEX,
                                  query=q,
                                  filters=filters,
                                  fields=fields,
                                  sort=sort)
    hits = models.massage_query_results(results)
    paginator = Paginator(hits, settings.RESULTS_PER_PAGE)
    page = paginator.page(request.GET.get('page', 1))
    return render_to_response('ui/search/results.html', {
        'paginator': paginator,
        'page': page,
        'query': q,
        'filters': filters,
        'sort': sort,
    },
                              context_instance=RequestContext(request,
                                                              processors=[]))
Exemple #4
0
def results( request ):
    """Results of a search query.
    """
    # prep query for elasticsearch
    model = request.GET.get('model', None)
    q = django_urlquote(request.GET.get('query', ''))
    filters = {}
    fields = models.all_list_fields()
    sort = {'record_created': request.GET.get('record_created', ''),
            'record_lastmod': request.GET.get('record_lastmod', ''),}
    # do the query
    results = elasticsearch.query(settings.ELASTICSEARCH_HOST_PORT, settings.DOCUMENT_INDEX,
                                  query=q, filters=filters,
                                  fields=fields, sort=sort)
    hits = models.massage_query_results(results)
    paginator = Paginator(hits, settings.RESULTS_PER_PAGE)
    page = paginator.page(request.GET.get('page', 1))
    return render_to_response(
        'ui/search/results.html',
        {'paginator': paginator,
         'page': page,
         'query': q,
         'filters': filters,
         'sort': sort,},
        context_instance=RequestContext(request, processors=[])
    )
Exemple #5
0
 def get_absolute_url(self):
     return u'%(base)s%(slug)s?answer=%(id)d#answer-container-%(id)d' % \
             {
                 'base': reverse('question', args=[self.question.id]),
                 'slug': django_urlquote(slugify(self.question.title)),
                 'id': self.id
             }
 def get_absolute_url(self):
     return '%(base)s%(slug)s?answer=%(id)d#%(id)d' % \
             {
                 'base': reverse('question', args=[self.question.id]),
                 'slug': django_urlquote(slugify(self.question.title)),
                 'id': self.id
             }
 def wrap(request, *args, **kwargs):
     redirect=False
     user = request.user 
     # Check if the user is authenticated and has a profile that
     # says this user has authenticated using aadhaar. 
     if not user.is_authenticated(): 
         print "aadhaar login decorator: User not found"
         redirect = True 
     else: 
         print "aadhaar login decorator: Found user ", user 
         profile = user.get_profile() 
         if not profile.is_valid_aadhaar(): 
             print "Not an aadhaar login. So redirect"
             redirect = True 
         else:
             print "aadhaar login decorator: valid aadhaar profile", profile
     if (redirect): 
         print "Logging out and redirecting"
         auth.logout(request)
         next=django_urlquote(request.get_full_path())
         nexturl = ("/account/aadhaar/authenticate/?next=%s" % next)
         print "sending the user to ", nexturl 
         return HttpResponseRedirect(nexturl)
     else:
         print "All is well. So process"
         return f(request, *args, **kwargs)
 def wrap(request, *args, **kwargs):
     redirect = False
     user = request.user
     # Check if the user is authenticated and has a profile that
     # says this user has authenticated using aadhaar.
     if not user.is_authenticated():
         print "aadhaar login decorator: User not found"
         redirect = True
     else:
         print "aadhaar login decorator: Found user ", user
         profile = user.get_profile()
         if not profile.is_valid_aadhaar():
             print "Not an aadhaar login. So redirect"
             redirect = True
         else:
             print "aadhaar login decorator: valid aadhaar profile", profile
     if (redirect):
         print "Logging out and redirecting"
         auth.logout(request)
         next = django_urlquote(request.get_full_path())
         nexturl = ("/account/aadhaar/authenticate/?next=%s" % next)
         print "sending the user to ", nexturl
         return HttpResponseRedirect(nexturl)
     else:
         print "All is well. So process"
         return f(request, *args, **kwargs)
    def import_posts(self, post_type, save_redirects=False):
        """imports osqa Nodes to askbot Post objects"""
        if save_redirects:
            redirects_file = self.open_unique_file('question_redirects')

        models_map = {
            'question': 'forum.question',
            'answer': 'forum.answer',
            'comment': 'forum.comment'
        }

        model_name = models_map[post_type]

        for osqa_node in self.get_objects_for_model(model_name):
            if osqa_node.node_type != post_type:
                continue

            post = Post()

            #this line is a bit risky, but should work if we import things in correct order
            if osqa_node.parent:
                post.parent = self.get_imported_object_by_old_id(Post, osqa_node.parent)
                post.thread = post.parent.thread
            else:
                post.thread = self.get_imported_object_by_old_id(Thread, osqa_node.id)

            post.post_type = osqa_node.node_type

            if save_redirects:
                slug = django_urlquote(slugify(osqa_node.title))
                #todo: add i18n to the old url
                old_url = '/questions/%d/%s/' % (osqa_node.id, slug)

            post.author = self.get_imported_object_by_old_id(User, osqa_node.author)
            post.html = HTMLParser().unescape(osqa_node.body)
            post.summary = post.get_snippet()

            #these don't have direct equivalent in the OSQA Node object
            #post.deleted_by
            #post.locked_by
            #post.last_edited_by

            #these are to be set later with the real values
            post.points = 0
            post.vote_up_count = 0
            post.vote_down_count = 0
            post.offensive_flag_count = 0

            post.save()

            if save_redirects:
                new_url = post.get_absolute_url()
                self.write_redirect(old_url, new_url, redirects_file)

            self.log_action_with_old_id(osqa_node.id, post)

        if save_redirects:
            redirects_file.close()
Exemple #10
0
def urlquote(link=None, get=None):
    """
    This method does both: urlquote() and urlencode()

    urlqoute(): Quote special characters in 'link'

    urlencode(): Map dictionary to query string key=value&...

    HTML escaping is not done.

    Example:

    urlquote('/wiki/Python_(programming_language)')
        --> '/wiki/Python_%28programming_language%29'
    urlquote('/mypath/', {'key': 'value'})
        --> '/mypath/?key=value'
    urlquote('/mypath/', {'key': ['value1', 'value2']})
        --> '/mypath/?key=value1&key=value2'
    urlquote({'key': ['value1', 'value2']})
        --> 'key=value1&key=value2'
    """
    if get is None:
        get = []

    assert link or get
    if isinstance(link, dict):
        # urlqoute({'key': 'value', 'key2': 'value2'}) -->
        # key=value&key2=value2
        assert not get, get
        get = link
        link = ''
    assert isinstance(get, dict), 'wrong type "%s", dict required' % type(get)
    # assert not (link.startswith('http://') or link.startswith('https://')),
    #    'This method should only quote the url path.
    #    It should not start with http(s)://  (%s)' % (
    #    link)
    if get:
        # http://code.djangoproject.com/ticket/9089
        if isinstance(get, MultiValueDict):
            get = get.lists()
        if link:
            link = '%s?' % django_urlquote(link)
        return '%s%s' % (link, django_urlencode(get, doseq=True))
    else:
        return django_urlquote(link)
Exemple #11
0
def urlquote(link=None, get=None):
    """
    This method does both: urlquote() and urlencode()

    urlqoute(): Quote special characters in 'link'

    urlencode(): Map dictionary to query string key=value&...

    HTML escaping is not done.

    Example:

    urlquote('/wiki/Python_(programming_language)')
        --> '/wiki/Python_%28programming_language%29'
    urlquote('/mypath/', {'key': 'value'})
        --> '/mypath/?key=value'
    urlquote('/mypath/', {'key': ['value1', 'value2']})
        --> '/mypath/?key=value1&key=value2'
    urlquote({'key': ['value1', 'value2']})
        --> 'key=value1&key=value2'
    """
    if get is None:
        get = []

    assert link or get
    if isinstance(link, dict):
        # urlqoute({'key': 'value', 'key2': 'value2'}) -->
        # key=value&key2=value2
        assert not get, get
        get = link
        link = ''
    assert isinstance(get, dict), 'wrong type "%s", dict required' % type(get)
    # assert not (link.startswith('http://') or link.startswith('https://')),
    #    'This method should only quote the url path.
    #    It should not start with http(s)://  (%s)' % (
    #    link)
    if get:
        # http://code.djangoproject.com/ticket/9089
        if isinstance(get, MultiValueDict):
            get = get.lists()
        if link:
            link = '%s?' % django_urlquote(link)
        return '%s%s' % (link, django_urlencode(get, doseq=True))
    else:
        return django_urlquote(link)
Exemple #12
0
def question_search(request, keywords):
    def question_search(keywords, orderby):
        return Question.objects.filter(Q(title__icontains=keywords) | Q(html__icontains=keywords))

    from forum.modules import get_handler

    question_search = get_handler('question_search', question_search)
    initial = question_search(keywords)

    return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
            base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)))
Exemple #13
0
def question_search(request, keywords):
    def question_search(keywords):
        return Question.objects.filter(Q(title__icontains=keywords) | Q(body__icontains=keywords))

    from forum.modules import get_handler

    question_search = get_handler('question_search', question_search)
    initial = question_search(keywords)

    return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
            base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
Exemple #14
0
def display_facet(fieldname, text, facet):
    # make everything a list
    if isinstance(text, basestring):
        text = text.strip().split(';')
    lines = []
    for txt in text:
        term_id = faceting.extract_term_id(txt)
        url = '/search/%s:%s/' % (fieldname, django_urlquote(term_id))
        termdata = {'url': url, 'term': txt.strip(), 'title': txt.strip()}
        if facet and facet['terms']:
            for term in facet['terms']:
                if term['id'] == term_id:
                    termdata['title'] = term['title']
        lines.append(termdata)
    t = Template(FACET_TEMPLATE)
    c = Context({'facets': lines})
    return t.render(c)
Exemple #15
0
def display_facet(fieldname, text, facet):
    # make everything a list
    if isinstance(text, basestring):
        text = text.strip().split(';')
    lines = []
    for txt in text:
        term_id = faceting.extract_term_id(txt)
        url = '/search/%s:%s/' % (fieldname, django_urlquote(term_id))
        termdata = {'url':url, 'term':txt.strip(), 'title':txt.strip()}
        if facet and facet['terms']:
            for term in facet['terms']:
                if term['id'] == term_id:
                    termdata['title'] = term['title']
        lines.append(termdata)
    t = Template(FACET_TEMPLATE)
    c = Context({'facets': lines})
    return t.render(c)
Exemple #16
0
def shib_login(request):
    """ Redirects to shib-SP-login url.
        Specifies the post-login url as the `shib_login_handler` url. """
    time.sleep(.5)  # in case the IDP logout just-completed needs a breath
    log.debug('\n\nstarting shib_login(); request.__dict__, ```%s```' %
              request.__dict__)
    shortlink = request.GET['shortlink']
    target_url = '%s?shortlink=%s' % (reverse('shib_login_handler_url'),
                                      shortlink)
    log.debug('target_url, ```%s```' % target_url)
    if (request.get_host() == '127.0.0.1' or request.get_host()
            == '127.0.0.1:8000') and project_settings.DEBUG == True:
        redirect_url = target_url
    else:
        redirect_url = '%s?target=%s' % (settings_app.SHIB_SP_LOGIN_URL,
                                         django_urlquote(target_url))
    log.debug('redirect_url, ```%s```' % redirect_url)
    return HttpResponseRedirect(redirect_url)
 def prep_login_url_stepA(self, request):
     """ Preps logout url with appropriate redirect.
         Steps for login:
         - a) execute django-logout and hit idp logout url (this function)
         - b) hit sp login url w/redirect to processor-view """
     django_logout(request)
     log.debug('django-logout executed')
     shortlink = request.GET['shortlink']
     log.debug('shortlink, `%s`' % shortlink)
     if '127.0.0.1' in request.get_host(
     ) and project_settings.DEBUG == True:
         login_a_url = '%s?shortlink=%s' % (reverse('shib_login_url'),
                                            shortlink)
     else:
         return_url = self.prep_return_url(request)
         login_a_url = '%s?&return=%s' % (self.SHIB_IDP_LOGOUT_URL,
                                          django_urlquote(return_url))
     log.debug('login_a_url, ```%s```' % login_a_url)
     return login_a_url
def authorize(request, aadhaar=False):
    
    raise Exception("Client authorize. Should not come here") 

    print "Came here - authorizer aadhaar = ", aadhaar
    authorizer = Authorizer()
    try:
        # Check if the correct user is logged in. Else redirect to login
        # page 
        loggedin_user = request.user 
        print "logged in user = "******"Unknown client") 
        
        # This is necessary if the logged in user is different from
        # the client identified. This is possibly a legacy issue. The 
        # check is useful anyway. 
        resource_owner = client.user 
        print "resource owner = ", resource_owner 
        if (loggedin_user != resource_owner):
            auth.logout(request)
            next=django_urlquote(request.get_full_path())
            if aadhaar: 
                nexturl = ("/account/aadhaar/authenticate/?next=%s" % next)
            else:
                nexturl = ("/account/login/?next=%s" % next)
            print "sending the user to ", nexturl 
            return HttpResponseRedirect(nexturl)
        
        # Now authorize
        authorizer.validate(request)

    except MissingRedirectURI, e:
        return HttpResponseRedirect("/oauth2/missing_redirect_uri")
def authorize(request, aadhaar=False):

    raise Exception("Client authorize. Should not come here")

    print "Came here - authorizer aadhaar = ", aadhaar
    authorizer = Authorizer()
    try:
        # Check if the correct user is logged in. Else redirect to login
        # page
        loggedin_user = request.user
        print "logged in user = "******"Unknown client")

        # This is necessary if the logged in user is different from
        # the client identified. This is possibly a legacy issue. The
        # check is useful anyway.
        resource_owner = client.user
        print "resource owner = ", resource_owner
        if (loggedin_user != resource_owner):
            auth.logout(request)
            next = django_urlquote(request.get_full_path())
            if aadhaar:
                nexturl = ("/account/aadhaar/authenticate/?next=%s" % next)
            else:
                nexturl = ("/account/login/?next=%s" % next)
            print "sending the user to ", nexturl
            return HttpResponseRedirect(nexturl)

        # Now authorize
        authorizer.validate(request)

    except MissingRedirectURI, e:
        return HttpResponseRedirect("/oauth2/missing_redirect_uri")
Exemple #20
0
 def get_absolute_url(self):
     return ('question', (), {'id': self.id, 'slug': django_urlquote(slugify(self.title))})
Exemple #21
0
 def get_absolute_url(self):
     return reverse('book',
                    args=[django_urlquote(slugify(self.short_name))])
Exemple #22
0
 def get_absolute_url(self):
     return '%s%s#%s' % (reverse('question', args=[
         self.question.id
     ]), django_urlquote(slugify(self.question.title)), self.id)
Exemple #23
0
 def get_absolute_url(self, no_slug=False):
     url = reverse('question', args=[self.id])
     if no_slug == True:
         return url
     else:
         return url + django_urlquote(self.slug)
Exemple #24
0
def question_search(request, keywords):
    initial = Question.objects.search(keywords)

    return question_list(request, initial, _("questions matching '%(keywords)s'") % {'keywords': keywords},
            base_path="%s?t=question&q=%s" % (reverse('search'), django_urlquote(keywords)), sort=False)
def urlquote(value):
    """Prepend user defined media root to url"""
    return django_urlquote(value)
Exemple #26
0
 def get_absolute_url(self, no_slug = False):
     url = reverse('question', args=[self.id])
     if no_slug == True:
         return url
     else:
         return url + django_urlquote(self.slug)
    def import_posts(self, post_type, save_redirects=False):
        """imports osqa Nodes to askbot Post objects"""
        if save_redirects:
            redirects_file = self.open_unique_file('question_redirects')

        models_map = {
            'question': 'forum.question',
            'answer': 'forum.answer',
            'comment': 'forum.comment'
        }

        model_name = models_map[post_type]

        for osqa_node in self.get_objects_for_model(model_name):
            #we iterate through all nodes, but pick only the ones we need
            if osqa_node.node_type != post_type:
                continue

            #cheat: do not import deleted content
            if '(deleted)' in osqa_node.state_string:
                continue

            post = Post()

            #this line is a bit risky, but should work if we import things in correct order
            if osqa_node.parent:
                post.parent = self.get_imported_object_by_old_id(Post, osqa_node.parent)
                if post.parent is None:
                    continue #deleted parent
                post.thread = post.parent.thread
            else:
                post.thread = self.get_imported_object_by_old_id(Thread, osqa_node.id)
                if post.thread is None:
                    continue #deleted thread

            post.post_type = osqa_node.node_type
            post.added_at = osqa_node.added_at

            if save_redirects:
                slug = django_urlquote(slugify(osqa_node.title))
                #todo: add i18n to the old url
                old_url = '/questions/%d/%s/' % (osqa_node.id, slug)

            post.author = self.get_imported_object_by_old_id(User, osqa_node.author)
            #html will de added with the revisions
            #post.html = HTMLParser().unescape(osqa_node.body)
            post.summary = post.get_snippet()

            #these don't have direct equivalent in the OSQA Node object
            #post.deleted_by - deleted nodes are not imported
            #post.locked_by
            #post.last_edited_by

            #these are to be set later with the real values
            post.points = 0
            post.vote_up_count = 0
            post.vote_down_count = 0
            post.offensive_flag_count = 0

            post.save()

            #mark accepted answer
            now = timezone.now()
            if osqa_node.node_type == 'answer':
                if '(accepted)' in osqa_node.state_string:
                    post.thread.accepted_answer = post
                    post.endorsed = True
                    post.endorsed_at = now
                    post.thread.save()


            if save_redirects:
                new_url = post.get_absolute_url()
                self.write_redirect(old_url, new_url, redirects_file)

            self.log_action_with_old_id(osqa_node.id, post)

        if save_redirects:
            redirects_file.close()
Exemple #28
0
    def import_posts(self, post_type, save_redirects=False):
        """imports osqa Nodes to askbot Post objects"""
        if save_redirects:
            redirects_file = self.open_unique_file('question_redirects')

        models_map = {
            'question': 'forum.question',
            'answer': 'forum.answer',
            'comment': 'forum.comment'
        }

        model_name = models_map[post_type]

        for osqa_node in self.get_objects_for_model(model_name):
            #we iterate through all nodes, but pick only the ones we need
            if osqa_node.node_type != post_type:
                continue

            #cheat: do not import deleted content
            if '(deleted)' in osqa_node.state_string:
                continue

            post = Post()

            #this line is a bit risky, but should work if we import things in correct order
            if osqa_node.parent:
                post.parent = self.get_imported_object_by_old_id(
                    Post, osqa_node.parent)
                if post.parent is None:
                    continue  #deleted parent
                post.thread = post.parent.thread
            else:
                post.thread = self.get_imported_object_by_old_id(
                    Thread, osqa_node.id)
                if post.thread is None:
                    continue  #deleted thread

            post.post_type = osqa_node.node_type
            post.added_at = osqa_node.added_at

            if save_redirects:
                slug = django_urlquote(slugify(osqa_node.title))
                #todo: add i18n to the old url
                old_url = '/questions/%d/%s/' % (osqa_node.id, slug)

            post.author = self.get_imported_object_by_old_id(
                User, osqa_node.author)
            #html will de added with the revisions
            #post.html = HTMLParser().unescape(osqa_node.body)
            post.summary = post.get_snippet()

            #these don't have direct equivalent in the OSQA Node object
            #post.deleted_by - deleted nodes are not imported
            #post.locked_by
            #post.last_edited_by

            #these are to be set later with the real values
            post.points = 0
            post.vote_up_count = 0
            post.vote_down_count = 0
            post.offensive_flag_count = 0

            post.save()

            #mark accepted answer
            now = timezone.now()
            if osqa_node.node_type == 'answer':
                if '(accepted)' in osqa_node.state_string:
                    post.thread.accepted_answer = post
                    post.endorsed = True
                    post.endorsed_at = now
                    post.thread.save()

            if save_redirects:
                new_url = post.get_absolute_url()
                self.write_redirect(old_url, new_url, redirects_file)

            self.log_action_with_old_id(osqa_node.id, post)

        if save_redirects:
            redirects_file.close()
Exemple #29
0
 def get_absolute_url(self):
     return '%s%s' % (
                 reverse('question', args=[self.id]), 
                 django_urlquote(slugify(self.title))
             )
Exemple #30
0
 def get_absolute_url(self, no_slug=False):
     url = reverse("question", args=[self.id])
     if no_slug == True:
         return url
     else:
         return url + django_urlquote(slugify(self.title))
Exemple #31
0
def urlquote(value):
    """Prepend user defined media root to url"""
    return django_urlquote(value)
Exemple #32
0
 def get_absolute_url(self):
     return reverse('book', args=[django_urlquote(slugify(self.short_name))])
Exemple #33
0
 def get_absolute_url(self):
     return '%s%s' % (reverse('question', args=[self.id]), django_urlquote(self.title.replace(' ', '-')))
Exemple #34
0
 def get_absolute_url(self):
     return '%s' % reverse('book', args=[django_urlquote(self.short_name)])
Exemple #35
0
 def get_absolute_url(self):
     return '%s%s#%s' % (reverse('question', args=[self.question.id]), django_urlquote(self.question.title), self.id)