Example #1
0
def import_mail(f):
    message = email.message_from_file(f)
    if message and message['to'].find(settings.MAILLIST_NAME) != -1:
        subject, encoding = email.header.decode_header(message['subject'])[0]
        if encoding:
            subject = subject.decode(encoding)
        match = settings.MAILLIST_HEADER.search(subject)
        if match:
            message_hash = hashlib.sha1(message.as_string())
            if settings.MAILLIST_DIR:
                tfn = "%s/%s.msg" % (settings.MAILLIST_DIR,
                                     message_hash.hexdigest())
                if not os.path.exists(tfn):
                    tf = open(tfn, 'w')
                    tf.write(message.as_string())
                    tf.close()
            comics = match.group(1)
            name, address = email.utils.getaddresses([message['from']])[0]
            name, encoding  = email.header.decode_header(name)[0]
            if not encoding is None:
                name = name.decode(encoding)
            date = datetime.datetime.fromtimestamp(
                email.utils.mktime_tz(
                    email.utils.parsedate_tz(message['date'])))
            logging.debug('Comics: %s(%s).' % (comics, 
                                                message_hash.hexdigest()))
            if message.is_multipart():
                for part in message.walk():
                    if part.get_content_type() == 'text/plain':
                        text = part.get_payload(decode=True).\
                            decode(part.get_content_charset('utf-8'))
                        break
                else:
                    logging.debug('No text/plain in multipart message.')
                    for part in message.walk():
                        if part.get_content_type() == 'text/html':
                            text = part.get_payload(decode=True).\
                                decode(part.get_content_charset('utf-8'))
                            text = strip_entities(strip_tags(text))
                            break
                    else:
                        logging.warning('No text/html in message %s.' %
                                            message_hash.hexdigest())
            else:
                text = message.get_payload(decode=True).\
                    decode(message.get_content_charset('utf-8'))
                if message.get_content_type() == 'text/html':
                    logging.debug('No text/plain in message.')
                    text = strip_entities(strip_tags(text))
            for footer in settings.MAILLIST_FOOTER:
                try:
                    text = text.split(footer)[0]
                except:
                    pass
            try:
                m = Mail(sender="%s <%s>" % (name, address), message=text,
                         date=date, comics=Comics.objects.get(cid=comics))
                m.save()
            except Comics.DoesNotExist:
                pass
Example #2
0
    def form_valid(self, form):
        """
        Is called when the POSTed data is valid and creates the category.

        Parameters
        ----------
        form : geokey.categories.forms.CategoryCreateForm
            Represents the user input
        """
        data = form.cleaned_data

        project_id = self.kwargs['project_id']
        project = Project.objects.as_admin(self.request.user, project_id)

        category = Category.objects.create(
            project=project,
            creator=self.request.user,
            name=strip_tags(data.get('name')),
            description=strip_tags(data.get('description')),
            default_status=data.get('default_status')
        )

        messages.success(self.request, "The category has been created.")
        return redirect(
            'admin:category_overview',
            project_id=project.id,
            category_id=category.id
        )
Example #3
0
    def clean(self, json_body):
        """
        Cleans the note object or raises a ValidationError.
        """
        if json_body is None:
            raise ValidationError("Note must have a body.")

        body = json.loads(json_body)
        if not type(body) is dict:
            raise ValidationError("Note body must be a dictionary.")

        # NOTE: all three of these fields should be considered user input
        # and may be output back to the user, so we need to sanitize them.
        # These fields should only contain _plain text_.
        self.uri = strip_tags(body.get("uri", ""))
        self.text = strip_tags(body.get("text", ""))
        self.quote = strip_tags(body.get("quote", ""))

        ranges = body.get("ranges")
        if ranges is None or len(ranges) != 1:
            raise ValidationError("Note must contain exactly one range.")

        self.range_start = ranges[0]["start"]
        self.range_start_offset = ranges[0]["startOffset"]
        self.range_end = ranges[0]["end"]
        self.range_end_offset = ranges[0]["endOffset"]

        self.tags = ""
        tags = [strip_tags(tag) for tag in body.get("tags", [])]
        if len(tags) > 0:
            self.tags = ",".join(tags)
Example #4
0
    def post(self, request, project_id, subset_id):
        """
        Updates the subset based on the data entered by the user

        Parameter
        ---------
        request : django.http.HttpRequest
            Object representing the request.
        project_id : int
            identifies the project in the data base
        subset_id : int
            identifies the subset in the data base

        Returns
        -------
        django.http.HttpResponse
            Rendered template
        """
        context = self.get_context_data(project_id, subset_id)
        subset = context.get('subset')

        if subset:
            data = request.POST
            subset.name = strip_tags(data.get('name'))
            subset.description = strip_tags(data.get('description'))
            subset.save()

            messages.success(self.request, "The subset has been updated.")

        return self.render_to_response(context)
Example #5
0
    def form_valid(self, form):
        """
        Is called when the POSTed data is valid and creates the observation
        type.
        """
        data = form.cleaned_data

        project_id = self.kwargs['project_id']
        project = Project.objects.as_admin(self.request.user, project_id)

        category = Category.objects.create(
            project=project,
            creator=self.request.user,
            name=strip_tags(data.get('name')),
            description=strip_tags(data.get('description')),
            default_status=data.get('default_status'),
            create_grouping=(data.get('create_grouping') == 'True')
        )

        messages.success(self.request, "The category has been created.")
        return redirect(
            'admin:category_overview',
            project_id=project.id,
            category_id=category.id
        )
Example #6
0
    def clean_body(self):
        body = self.cleaned_data["body"]

        for tag in CUT_TAG_SYNONYMS:
            body = body.replace(tag, CUT_TAG)

        editor_cut = body.find(CUT_TAG)
        if editor_cut >= 0:
            tease = strip_tags(body[:editor_cut])
        else:
            tease = ""

        body = strip_tags(body)

        if len(body) > SHORT_POST_MAX_LENGTH and editor_cut < 0:
            raise forms.ValidationError(
                _(
                    u"Your post is too long and without a cut. Please add cut somewhere to leave only introduction part before it."
                )
            )

        if editor_cut > CUT_MAX_LENGTH:
            raise forms.ValidationError(
                _(
                    u"Your cut is too long. Please put the cut somewhere to leave only introduction part no longer, than %s characters before it."
                )
                % CUT_MAX_LENGTH
            )

        self.cleaned_data["tease"] = tease

        return body
Example #7
0
def crypto(request):
    if not request.user.is_authenticated():
        messages.error(request, "You must first login to access this page.")
        return render(request, "pbl/invalid_access.html", {})
    if request.method != "POST":
        return render(request, "pbl/crypto/index.html", {})
    if request.POST.get("plainText") is not None:
        inputtext = escape((strip_tags(request.POST.get("plainText"))))
        if inputtext:
            encryptedtext = doEncrypt(inputtext)
            # messages.info(request,encryptedtext)
            return render(request, "pbl/crypto/index.html", {"encryptedtext": encryptedtext})
    if request.POST.get("inputPassword") is not None:
        passwd = escape(strip_tags(request.POST.get("inputPassword")))
        if passwd == doDecrypt("ADGJMPSV"):
            challenge_id = 1
            level_id = 5
            completed = is_already_completed_level(request.user, challenge_id, level_id)
            if not completed:
                compute_score(request, challenge_id, level_id)
                messages.success(request, "Congratulations, You have completed web login challenge - Level 4")
            else:
                messages.success(
                    request,
                    "Congratulations beating up again- web login challenge - Level 4. But you will not get the score",
                )
            return render(request, "pbl/crypto/answers.html", {})
            # return HttpResponse("<html><body>You got it.</body></html>")
        messages.error(request, "Incorrect Password")
    return render(request, "pbl/crypto/index.html", {})
Example #8
0
    def clean(self, json_body):
        """
        Cleans the note object or raises a ValidationError.
        """
        if json_body is None:
            raise ValidationError('Note must have a body.')

        body = json.loads(json_body)
        if not isinstance(body, dict):
            raise ValidationError('Note body must be a dictionary.')

        # NOTE: all three of these fields should be considered user input
        # and may be output back to the user, so we need to sanitize them.
        # These fields should only contain _plain text_.
        self.uri = strip_tags(body.get('uri', ''))
        self.text = strip_tags(body.get('text', ''))
        self.quote = strip_tags(body.get('quote', ''))

        ranges = body.get('ranges')
        if ranges is None or len(ranges) != 1:
            raise ValidationError('Note must contain exactly one range.')

        self.range_start = ranges[0]['start']
        self.range_start_offset = ranges[0]['startOffset']
        self.range_end = ranges[0]['end']
        self.range_end_offset = ranges[0]['endOffset']

        self.tags = ""
        tags = [strip_tags(tag) for tag in body.get('tags', [])]
        if len(tags) > 0:
            self.tags = ",".join(tags)
Example #9
0
    def _update_rssatom(self):
        d = feedparser.parse(self.url)
        try:
            most_recent_saved = self.entries.order_by('-posted_on')[0]

            for post in d.entries:
                post_time = datetime(*post.updated_parsed[:6])
                if post_time <= most_recent_saved.posted_on:
                    break
                else:
                    e = Entry(
                            feed=self,
                            title=post.title,
                            url=post.link,
                            content=strip_tags(post.summary),
                            posted_on=datetime(*post.updated_parsed[:6])
                        )
                    e.save()

        except IndexError: # no Entry saved
            for post in d.entries:
                e = Entry(
                        feed=self,
                        title=post.title,
                        url=post.link,
                        content=strip_tags(post.summary),
                        posted_on=datetime(*post.updated_parsed[:6])
                    )
                e.save()
    def test_date_options(self):
        form = SearchForm(request=None, data={
            'date_filter': 'created',
            'date__gte': '10/1/18',
            'date__lt': '11/01/2018',
        })
        self.assertTrue(form.is_valid())
        query_params = form.get_api_request_params()
        query_params.pop('resolution', None)
        self.assertDictEqual(query_params, {
            'ordering': '-created',
            'log__action': 'created',
            'logged_at__gte': datetime.date(2018, 1, 10),
            'logged_at__lt': datetime.date(2018, 1, 12),
        })
        description = form.search_description
        self.assertTrue(description['has_filters'])
        self.assertIn('date entered between 10 Jan 2018 and 11 Jan 2018', strip_tags(description['description']))

        form = SearchForm(request=None, data={
            'ordering': '-amount',
            'date_filter': 'confirmed',
            'date__lt': '2018-01-10',
        })
        self.assertTrue(form.is_valid())
        query_params = form.get_api_request_params()
        query_params.pop('resolution', None)
        self.assertDictEqual(query_params, {
            'ordering': '-amount',
            'log__action': 'confirmed',
            'logged_at__lt': datetime.date(2018, 1, 11),
        })
        description = form.search_description
        self.assertTrue(description['has_filters'])
        self.assertIn('date confirmed before 10 Jan 2018', strip_tags(description['description']))
Example #11
0
    def _render_change_replace_lines(self, differ, i1, i2, j1, j2,
                                     old_lines, new_lines):
        replace_new_lines = []

        for i, j in zip(range(i1, i2), range(j1, j2)):
            old_line = old_lines[i]
            new_line = new_lines[j]

            parser = HTMLParser()

            old_regions, new_regions = \
                get_line_changed_regions(parser.unescape(strip_tags(old_line)),
                                         parser.unescape(strip_tags(new_line)))

            old_line = highlightregion(old_line, old_regions)
            new_line = highlightregion(new_line, new_regions)

            yield (
                '<tr class="replace-old">'
                ' <td class="marker">~</td>'
                ' <td class="marker">&nbsp;</td>'
                ' <td class="line rich-text">%s</td>'
                '</tr>'
                % old_line)

            replace_new_lines.append(new_line)

        for line in replace_new_lines:
            yield (
                '<tr class="replace-new">'
                ' <td class="marker">&nbsp;</td>'
                ' <td class="marker">~</td>'
                ' <td class="line rich-text">%s</td>'
                '</tr>'
                % line)
Example #12
0
    def post(self, request, project_id, group_id):
        """
        Updates the user group settings

        Parameter
        ---------
        request : django.http.HttpRequest
            Object representing the request.
        project_id : int
            identifies the project in the data base
        group_id : int
            identifies the group in the data base

        Returns
        -------
        django.http.HttpResponse
            Rendered template
        """
        context = self.get_context_data(project_id, group_id)
        group = context.pop('group', None)

        if group is not None:
            data = request.POST

            group.name = strip_tags(data.get('name'))
            group.description = strip_tags(data.get('description'))
            group.save()

            messages.success(self.request, "The user group has been updated.")
            context['group'] = group

        return self.render_to_response(context)
Example #13
0
def umail(request, template, subject, sender, to, context = {}, bcc = [], attachments=[]):
    """
    It sends mail with template. It supports html and txt template. In the first case it searches a txt template with the
    same name in the same position. If it will be found it sends both.
    'template', 'subject' and 'sender' are strings.
    'to' and 'bcc' are lists of addresses.
    'context' is a dictionary.
    'attachments' is a list of paths.
    """
    if request:
        c = RequestContext(request, context)
    else:
        c = Context(context)

    if template.endswith('.html'):
        t = loader.get_template(template)
        try:
            t_html = t
            txt_name = '%s.txt' % (template.rsplit('.', 1)[0])
            t = loader.get_template(txt_name)
        except:
            print "Missing .txt template for: %s" % (template)
            email = EmailMessage(subject, t_html.render(c), sender, to, bcc)
            email.content_subtype = "html"
        else:
            email = EmailMultiAlternatives(subject, strip_tags(t.render(c)), sender, to, bcc)
            email.attach_alternative(t_html.render(c).encode('utf-8'), "text/html")
    else:
        t = loader.get_template(template)
        email = EmailMessage(subject, strip_tags(t.render(c)), sender, to, bcc)

        for filepath in attachments:
            mimetype = mimetypes.guess_type(filepath)[0]
            email.attach_file(filepath, mimetype)
    email.send()
Example #14
0
def locations(request):
    if request.method == 'POST':
        import pdb;
        pdb.set_trace()

        # need to reference account first
        # CODE HERE

        # sanitize and localize the JSON
        latitude = strip_tags(request.POST['latitude'])
        longitude = strip_tags(request.POST['longitude'])

        # insert geocoder here


        # return JSON response
        #{"address":"Observatory Road, Dartmouth College, Hanover, NH 03755, USA","created_at":"2013-02-13T00:30:08Z","id":1,"latitude":"43.70359","longitude":"-72.286756","updated_at":"2013-02-13T00:30:08Z"}
        payload = {'latitude':latitude, 'longitude':longitude}

        return HttpResponse(json.dumps(payload), mimetype="application/json")

        


    else:
        # not POST, send home
        return render_to_response("main.html", RequestContext(request))
Example #15
0
    def post(self, request, project_id):
        """
        Updates the project settings

        Parameter
        ---------
        request : django.http.HttpRequest
            Object representing the request.
        project_id : int
            identifies the project in the database

        Returns
        -------
        django.http.HttpResponse
            Rendered template
        """
        context = self.get_context_data(project_id)
        project = context.pop('project')

        if project is not None:
            data = request.POST

            project.name = strip_tags(data.get('name'))
            project.description = strip_tags(data.get('description'))
            project.everyone_contributes = data.get('everyone_contributes')
            project.save()

            messages.success(self.request, "The project has been updated.")
            context['project'] = project
        return self.render_to_response(context)
Example #16
0
 def get_mark(self):
     marks = Mark.objects.filter(code_id=self.code.id, displayorder__gte=0).order_by("line_num")
     mark_dict = {}
     for mark in marks:
         if not mark.line_num in mark_dict.keys():
             mark_dict[mark.line_num] = [mark]
         else:
             mark_dict[mark.line_num].append(mark)
     
     mark_html = ''
     for k,v in mark_dict.items():
         if len(v) == 1 and len(strip_tags(v[0].content)) < 20:
             #mark_html += '<div code_id="%d" line_num="%d" class="mark_wrapper"><a code_id="%d" line_num="%d" href="javascript:;" class="single_mark mark_view" data-toggle="tooltip" data-placement="right" data-trigger="manual" data-title="%s">&nbsp;</a></div>' \
             mark_html += '<div code_id="%d" line_num="%d" class="mark_wrapper">\
                             <div class="tooltip fade right in" style="top: 0px; left: -2px; display: block;">\
                                 <div class="tooltip-arrow"></div>\
                                 <div class="tooltip-inner"><a code_id="%d" line_num="%d" href="javascript:;" class="single_mark mark_view" title="">%s</a></div>\
                             </div>\
                         </div>'\
             % (self.code.id, k, self.code.id, k, strip_tags(v[0].content))
         else:
             #mark_html += '<div code_id="%d" line_num="%d" class="mark_wrapper"><a code_id="%d" line_num="%d" href="javascript:;" class="multi_mark mark_view" data-toggle="tooltip" data-placement="right" data-trigger="manual" data-title="%d">&nbsp;</a></div>' \
             mark_html += '<div code_id="%d" line_num="%d" class="mark_wrapper">\
                             <div class="tooltip fade right in" style="top: 0px; left: -2px; display: block;">\
                                 <div class="tooltip-arrow"></div>\
                                 <div class="tooltip-inner"><a code_id="%d" line_num="%d" href="javascript:;" class="multi_mark mark_view" title=""><span class="xw1 text-danger">%d</span> marks</a></div>\
                             </div>\
                         </div>'\
             % (self.code.id, k, self.code.id, k, len(v))
     
     
     return mark_html
Example #17
0
def import_blog_category (table):

    oldarticles = table.objects.all()

    Z.Entry.objects.filter(categories=detect_news_category(table)).delete()

    disconnect_zinnia_signals()

    for oldarticle in oldarticles:
        #oldarticle = L.MusicNews()
        if oldarticle.titulo:
            title = oldarticle.titulo
        else:
            title = truncate( strip_tags( oldarticle.contenido ), 255 )[:255]
        if title:

            article = Z.Entry(
                title = title,
                #Ignore titcone

                slug = slugify(title),
                status = Z.PUBLISHED,

                short = truncate( strip_tags( oldarticle.contenido ), 100 ),
                source = oldarticle.info,
                #author
            )

            

            last_update = compile_date(oldarticle.du, oldarticle.mu, oldarticle.au)
            creation_date = compile_date(oldarticle.da, oldarticle.ma, oldarticle.aa)
            start_publication = compile_date(oldarticle.dia, oldarticle.mes, oldarticle.ano)

            if last_update:
                article.last_update = last_update

            if creation_date:
                article.creation_date = creation_date

            if start_publication:
                article.start_publication = start_publication

            #import one photo as main, insert other in bottom
            additional_image = False
            image_name = oldarticle.imagen1
            if oldarticle.imagen2:
                image_name = oldarticle.imagen2

            if image_name:
                #bi_content = ContentFile( open( settings.FAKE_IMPORT_IMAGE, 'r' ).read() )
                bi_content = ContentFile( open( settings.OLDDATABOGOTA_PHOTO_PATH + 'contenido/' + image_name, 'r' ).read() )
                article.image.save( image_name, bi_content, save = False )

            #Import subtitle as part of content!!!!!!
            article.content = compile_news_content(oldarticle.contenido,oldarticle.subtitulo, additional_image)
            article.save()
            article.categories.add(detect_news_category(table))
            #TODO carefully import sites
            article.sites.add(1)
Example #18
0
def helloworld_create(request):

    # Tutorial: user just entered friends name
    if request.method == 'POST':

        friend_name = strip_tags(request.POST['friend_name'])
        friend_id = request.POST['hash']

        #friend_form = TutorialNameForm(request.POST)
        #if friend_form.is_valid():

        friend_name = strip_tags(request.POST['friend_name'].title())
        # create first album with friend name: "My Experiences with <friend>"
        first_friend_experience = Experiences(title='Stories with '+friend_name)
        first_friend_experience.save()
        first_friend_experience.creator.add(request.user) # added to user's album

        # pass to next page (dragging memes into album)
        request.session['first_friend_experience'] = first_friend_experience

        # pass to invitation process
        request.session['friend_id'] = strip_tags(friend_id)
        request.session['friend_inv_exist'] = True
        request.session['friend_name'] = friend_name.split()[0] # Take only first name

        # create album and return for user
        response = {
            "title": first_friend_experience.title,
            "id": first_friend_experience.id
        }
        return HttpResponse(json.dumps(response), mimetype="application/json")
Example #19
0
def add_meme_to_node(request):
    if request.is_ajax():
        if request.method == 'POST':
            dragged_meme_id = strip_tags(request.POST['meme'])
            add_type = strip_tags(request.POST['type'])
            meme_node = strip_tags(request.POST['meme_node'])
            
            # discover obj for drag and drop
            selected_meme = Meme.objects.get(pk=meme_node) # meme that was opened in fancybox
            dragged_meme_obj = Meme.objects.get(pk=dragged_meme_id) # meme that was dragged from uncat

            if add_type == 'horizontal':

                # first add connections to every permutation of DRAGGED MEME PERSPECTIVE
                for node in dragged_meme_obj.meme_horizontal.all():
                    node.meme_horizontal.add(selected_meme)

                # ADD CONNECTIONS TO OPENED MEMES PERSPECTIVE
                for node in selected_meme.meme_horizontal.all():
                    node.meme_horizontal.add(dragged_meme_obj)

                # add connection to original
                selected_meme.meme_horizontal.add(dragged_meme_obj) 

                return HttpResponse('success')

            if add_type == 'vertical':
                # just add 1 node
                selected_meme.meme_vertical = dragged_meme_obj
                selected_meme.save()

                return HttpResponse('success')
Example #20
0
    def post(self, request, app_id):
        """
        Handles the POST request and updates the application

        Parameters
        ----------
        request : django.http.HttpRequest
            Object representing the request.
        app_id : int
            ID identifying the the app in the database.

        Returns
        -------
        django.http.HttpResponse
            Rendered template
        """
        context = self.get_context_data(app_id)
        app = context.pop('application', None)

        if (app is not None):
            data = request.POST
            app.name = strip_tags(data.get('name'))
            app.description = strip_tags(data.get('description'))
            app.download_url = data.get('download_url')
            app.redirect_uris = data.get('redirect_uris')
            app.authorization_grant_type = data.get('authorization_grant_type')
            app.save()

            messages.success(self.request, "The application has been updated.")
            context['application'] = app

        return self.render_to_response(context)
Example #21
0
    def get_search_data(self, language=None, request=None):
        """
        Returns search text data for current object
        """
        if not self.pk:
            return ""

        bits = [self.name]
        description = self.safe_translation_getter("description")
        if description:
            bits.append(force_unicode(strip_tags(description)))

        if self.category:
            bits.append(self.category.safe_translation_getter("name"))
            description = self.category.safe_translation_getter("description")
            if description:
                bits.append(force_unicode(strip_tags(description)))

        for tag in self.tags.all():
            bits.append(tag.safe_translation_getter("name"))
            description = tag.safe_translation_getter("description", "")
            if description:
                bits.append(force_unicode(strip_tags(description)))

        bits.append(get_text_from_placeholder(self.body, language, request))
        return " ".join(bits)
Example #22
0
def ical_all_event(request, response_format='ical'):
    "Export upcoming events "
    query = Q()
    events = Object.filter_by_request(request, Event.objects.filter(query))
    icalstream = """BEGIN:VCALENDAR
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:PUBLISH
PRODID:-//PYVOBJECT//NONSGML Version 1//EN
"""
    vevent = ""
    for event in events:
        vevent += "BEGIN:VEVENT\n"
        if event.start:
            vevent += "DTSTART;VALUE=DATE:%s\n" % str((datetime.strptime(str(event.start)[0:10], '%Y-%m-%d')))[0:10].replace("-", "")
        vevent += "DTEND;VALUE=DATE:%s\n" % str((datetime.strptime(str(event.end)[0:10], '%Y-%m-%d')))[0:10].replace("-", "")
        if not event.details:
            vevent += "SUMMARY:%s\n" % strip_tags(event.name)
        else:
            vevent += "SUMMARY:%s\n" % strip_tags(event.details)
        vevent += "UID:%s\n" % (event.name)
        vevent += "END:VEVENT\n"
        
    icalstream += vevent
    icalstream += """X-WR-CALDESC:Tree.io Calendar
X-WR-CALNAME:Tree.io
X-WR-TIMEZONE:London/UK
END:VCALENDAR
"""
    
    response = HttpResponse(icalstream, mimetype='text/calendar')
    response['Filename'] = 'events.ics'  # IE needs this
    response['Content-Disposition'] = 'attachment; filename=events.ics'
    return response
Example #23
0
def page_not_found(request, **kwargs):
    error = sys.exc_value

    if len(error.args):
        error = error.args[0]
    if hasattr(error, 'get'):
        error = "<code>%s</code> could not be found." % (error.get('path', request.path))
    if not isinstance(error, unicode):
        error = error.__unicode__()
    if not bool(error):
        error = "<code>%s</code> could not be found." % (request.path)

    if request.is_json():
        msg = {"error": strip_tags(error)}
        response = HttpResponseNotFound(json.dumps(msg))
        response['Content-type'] = 'application/json'
        return response

    if request.is_txt():
        msg = "404 Not Found:\n%s" % strip_tags(error)
        response = HttpResponseNotFound(msg)
        response['Content-type'] = 'text/plain; charset=utf-8'
        return response

    # must clear query string
    request.GET = {}
    html = home(request, points=True, error=error)
    return HttpResponseNotFound(html)
Example #24
0
    def post(self, request, project_id, usergroup_id):
        """
        Updates the user group based on the data entered by the user.

        Parameter
        ---------
        request : django.http.HttpRequest
            Object representing the request
        project_id : int
            Identifies the project in the database
        usergroup_id : int
            Identifies the user group in the database

        Returns
        -------
        django.http.HttpResponse
            Rendered template when user group updated
        django.http.HttpResponse
            Rendered template, if project or user group does not exist
        """

        data = request.POST
        context = self.get_context_data(project_id, usergroup_id)
        usergroup = context.get('usergroup')

        if usergroup:
            usergroup.name = strip_tags(data.get('name'))
            usergroup.description = strip_tags(data.get('description'))
            usergroup.save()

            messages.success(self.request, 'The user group has been updated.')

        return self.render_to_response(context)
Example #25
0
def add_users(request):
    """
        Provides a view for adding a user
    """
    context = {
        'message': []
    }

    if request.method == 'POST':
        add_type = request.POST['type']

        if add_type == "SINGLE":
            to_add = strip_tags(request.POST['username'])
            first_name = strip_tags(request.POST['firstname'])
            last_name = strip_tags(request.POST['lastname'])
            major = strip_tags(request.POST['major'])
            year = strip_tags(request.POST['class'])

            exists = User.objects.filter(username=to_add).count()
            if exists:
                context['message'].append("Username " + to_add + " is taken.")
            else:
                try:
                    utils.create_user(to_add, first_name, last_name, major, year)
                    context['message'].append("User " + to_add + " successfully added.")
                except:
                    context['message'].append("Error adding " + to_add + ".")
    return render(request, 'secure/add_users.html', context)
Example #26
0
def message(request, socket, context, message):
    """
    Event handler for a room receiving a message. First validates a
    joining user's name and sends them the list of users.
    """
    room = get_object_or_404(ChatRoom, id=message["room"])
    if message["action"] == "start":
        name = strip_tags(message["name"])
        user, created = room.users.get_or_create(name=name)
        if not created:
            socket.send({"action": "in-use"})
        else:
            context["user"] = user
            users = [u.name for u in room.users.exclude(id=user.id)]
            socket.send({"action": "started", "users": users})
            user.session = socket.session.session_id
            user.save()
            joined = {"action": "join", "name": user.name, "id": user.id}
            socket.send_and_broadcast_channel(joined)
    else:
        try:
            user = context["user"]
        except KeyError:
            return
        if message["action"] == "message":
            message["message"] = strip_tags(message["message"])
            message["name"] = user.name
            socket.send_and_broadcast_channel(message)
Example #27
0
    def clean(self, value):
        super(TitleField, self).clean(value)

        if len(strip_tags(value).strip()) < settings.FORM_MIN_QUESTION_TITLE:
            raise forms.ValidationError(_('title must be at least %s characters without HTML tags and spaces') % settings.FORM_MIN_QUESTION_TITLE)

        return strip_tags(value)
Example #28
0
def ido0(request):
	if not request.user.is_authenticated():
		html = "<html><body>You must first login to access this page. <span> <a href="'../'">Go Home page</a></span></body></html>"
		return HttpResponse(html)
	if request.method != "POST":
		return render(request,'pbl/ido/0/index.html',{})	
	if request.POST.get("itemList") is not None:
		inputItem = escape((strip_tags(request.POST.get("itemList"))))
		if inputItem:
			return render(request,'pbl/ido/0/index.html',{'inputItem':inputItem})	
		else:
			messages.error(request,"Please select an item!!!")
			return render(request,'pbl/ido/0/index.html',{})
	selItem = escape((strip_tags(request.POST.get("itemChoosen"))))
	if not(selItem):
		messages.error(request,"Please select an item!!!")
	if selItem and selItem != 'banana':
		messages.error(request,"Congratulations, You have Successfully added the item but can you add item that is in stock but not in the list? ")
	if selItem == 'banana':
		challenge_id = 4 
		level_id = 1
		completed = is_already_completed_level(request.user,challenge_id,level_id)
		if not completed:
			compute_score(request,challenge_id,level_id)
			messages.success(request,"Congratulations, You have completed Insecure Direct object Reference challenge - Level 0")
		else: messages.success(request,"Congratulations beating up again- Insecure Direct object Reference challenge - Level 0. But you will not get the score")
		return render(request,'pbl/ido/0/answers.html',{})		
	return render(request,'pbl/ido/0/index.html',{})
Example #29
0
def print_pdf(request,slug):
	from reportlab.lib.units import inch
	from django.utils.html import strip_tags
	from reportlab.pdfbase.pdfmetrics import stringWidth
	from reportlab.rl_config import defaultPageSize

	PAGE_WIDTH  = defaultPageSize[0]
	PAGE_HEIGHT = defaultPageSize[1]

	
	funder = get_object_or_404(Funder, slug=slug)
	response=HttpResponse(mimetype='application/pdf')
	response['Content-Disposition']='attachment;filename=%s'%(slug)
	c=canvas.Canvas(response)
	sample_text=strip_tags(funder.eligibility)
	text_width = stringWidth(sample_text,"Helvetica",14)
	y = 1050
	text=c.beginText((PAGE_WIDTH - text_width) / 2.0, y)
	text.setTextOrigin(inch,2.5*inch)
	text.setFont("Helvetica",14)
	text.textLine("Organisation name")
	text.textLine(funder.organisation_name)
	text.textLines(strip_tags(funder.eligibility))
	c.drawText(text)
	c.showPage()
	c.save()
	return response
Example #30
0
def fetch_data_from_url(url, content):
    data = {"url": url}
    try:
        readable = Readability(url, content)
        data["title"] = reduce_whitespace(unescape_entities(readable.get_article_title()))
        # Try to get abstract from meta description:
        abstract = reduce_whitespace(unescape_entities(strip_tags(readable.get_meta_description()).strip()))
        if not abstract:
            abstract = reduce_whitespace(unescape_entities(strip_tags(readable.get_article_text()).strip()))
        abstract = truncate_words(abstract, 200)
        data["abstract"] = abstract
    except ReadabilityException:
        pass

    if VIDEO_URL_RE.search(url):
        data["media_formats"] = MediaFormat.objects.filter(name="Video")

    urls = URL_RE.findall(content)
    OLD_CC_LICENCES = [l[0] for l in CC_OLD_LICENSES[1:]]

    for url in urls:
        if CC_LICENSE_URL_RE.match(url):
            url = url.lower()
            if url in OLD_CC_LICENCES:
                data["license_type"] = "cc-old"
                data["license_cc_old"] = url
            else:
                data["license_type"] = "cc"
                data["license_cc"] = url

    return data
Example #31
0
def striptags(value):
    """Strip all [X]HTML tags."""
    return strip_tags(value)
Example #32
0
def count_words(html_string):
    word_string = strip_tags(html_string)
    matching_words = re.findall(r'\w+',word_string)
    count = len(re.findall(r'\w+',word_string))
    return count 
Example #33
0
    def __init__(self, filename, test):
        tree = filename.read()
        try:
            data = json.loads(str(tree, 'utf-8'))
        except:
            data = json.loads(tree)
        find_date = datetime.now()
        dupes = {}
        test_description = ""
        if "name" in data:
            test_description = "**Info:**\n"
            if "packagename" in data:
                test_description = "%s  **Package Name:** %s\n" % (test_description, data["packagename"])

            if "mainactivity" in data:
                test_description = "%s  **Main Activity:** %s\n" % (test_description, data["mainactivity"])

            if "pltfm" in data:
                test_description = "%s  **Platform:** %s\n" % (test_description, data["pltfm"])

            if "sdk" in data:
                test_description = "%s  **SDK:** %s\n" % (test_description, data["sdk"])

            if "min" in data:
                test_description = "%s  **Min SDK:** %s\n" % (test_description, data["min"])

            if "targetsdk" in data:
                test_description = "%s  **Target SDK:** %s\n" % (test_description, data["targetsdk"])

            if "minsdk" in data:
                test_description = "%s  **Min SDK:** %s\n" % (test_description, data["minsdk"])

            if "maxsdk" in data:
                test_description = "%s  **Max SDK:** %s\n" % (test_description, data["maxsdk"])

            test_description = "%s\n**File Information:**\n" % (test_description)

            if "name" in data:
                test_description = "%s  **Name:** %s\n" % (test_description, data["name"])

            if "md5" in data:
                test_description = "%s  **MD5:** %s\n" % (test_description, data["md5"])

            if "sha1" in data:
                test_description = "%s  **SHA-1:** %s\n" % (test_description, data["sha1"])

            if "sha256" in data:
                test_description = "%s  **SHA-256:** %s\n" % (test_description, data["sha256"])

            if "size" in data:
                test_description = "%s  **Size:** %s\n" % (test_description, data["size"])

            if "urls" in data:
                curl = ""
                for url in data["urls"]:
                    for curl in url["urls"]:
                        curl = "%s\n" % (curl)

                if curl:
                    test_description = "%s\n**URL's:**\n %s\n" % (test_description, curl)

            if "bin_anal" in data:
                test_description = "%s  \n**Binary Analysis:** %s\n" % (test_description, data["bin_anal"])

        test.description = strip_tags(test_description)

        mobsf_findings = []
        # Mobile Permissions
        if "permissions" in data:
            # for permission, details in data["permissions"].items():
            if type(data["permissions"]) is list:
                for details in data["permissions"]:
                    mobsf_item = {
                        "category": "Mobile Permissions",
                        "title": details[1],
                        "severity": "info",
                        "description": "**Permission Type:** " + details[1] + " (" + details[0] + ")\n\n**Description:** " + details[2],
                        "file_path": None
                    }
                    mobsf_findings.append(mobsf_item)
            else:
                for permission, details in list(data["permissions"].items()):
                    mobsf_item = {
                        "category": "**Mobile Permissions**",
                        "title": permission,
                        "severity": "info",
                        "description": "**Permission Type:** " + details["status"] + "\n\n**Description:** " + details["description"],
                        "file_path": None
                    }
                    mobsf_findings.append(mobsf_item)

        # Insecure Connections
        if "insecure_connections" in data:
            for details in data["insecure_connections"]:
                insecure_urls = ""
                for url in details.split(','):
                    insecure_urls = insecure_urls + url + "\n"

                mobsf_item = {
                    "category": None,
                    "title": "Insecure Connections",
                    "severity": "Low",
                    "description": insecure_urls,
                    "file_path": None
                }
                mobsf_findings.append(mobsf_item)

        # Binary Analysis
        if "binary_analysis" in data:
            for details in data["binary_analysis"]:
                for binary_analysis_type in details:
                    if "name" != binary_analysis_type:
                        mobsf_item = {
                            "category": "Binary Analysis",
                            "title": details[binary_analysis_type]["description"].split(".")[0],
                            "severity": details[binary_analysis_type]["severity"].replace("warning", "low").title(),
                            "description": details[binary_analysis_type]["description"],
                            "file_path": details["name"]
                        }
                        mobsf_findings.append(mobsf_item)

        # Manifest
        if "manifest" in data:
            for details in data["manifest"]:
                mobsf_item = {
                    "category": "Manifest",
                    "title": details["title"],
                    "severity": details["stat"],
                    "description": details["desc"],
                    "file_path": None
                }
                mobsf_findings.append(mobsf_item)

        # MobSF Findings
        if "findings" in data:
            for title, finding in list(data["findings"].items()):
                description = title
                file_path = None

                if "path" in finding:
                    description = description + "\n\n**Files:**\n"
                    for path in finding["path"]:
                        if file_path is None:
                            file_path = path
                        description = description + " * " + path + "\n"

                mobsf_item = {
                    "category": "Findings",
                    "title": title,
                    "severity": finding["level"],
                    "description": description,
                    "file_path": file_path
                }

                mobsf_findings.append(mobsf_item)

        for mobsf_finding in mobsf_findings:
            title = strip_tags(mobsf_finding["title"])
            sev = self.getCriticalityRating(mobsf_finding["severity"])
            description = ""
            file_path = None
            if mobsf_finding["category"]:
                description = "**Category:** " + mobsf_finding["category"] + "\n\n"
            description = description + strip_tags(mobsf_finding["description"])
            if mobsf_finding["file_path"]:
                file_path = mobsf_finding["file_path"]
            dupe_key = sev + title
            if dupe_key in dupes:
                find = dupes[dupe_key]
                if description is not None:
                    find.description += description
            else:
                find = Finding(title=Truncator(title).words(5),
                               cwe=919,  # Weaknesses in Mobile Applications
                               test=test,
                               active=False,
                               verified=False,
                               description=description,
                               severity=sev,
                               numerical_severity=Finding.get_numerical_severity(sev),
                               references=None,
                               date=find_date,
                               file_path=file_path,
                               static_finding=True)
                dupes[dupe_key] = find
        self.items = list(dupes.values())
Example #34
0
 def prepare_content(self, obj):
     content = obj.content
     content = strip_tags(content)
     content = strip_entities(content)
     return content
Example #35
0
 def get_object_display(self, attachment):
     instance_name = get_attachment_name(self._meta.request, attachment)
     vals = {"dev": attachment['device'],
             "instance_name": strip_tags(instance_name)}
     return _("%(dev)s on instance %(instance_name)s") % vals
Example #36
0
 def __unicode__(self):
     return u"%s" % (truncate_words(strip_tags(self.title), 3)[:30] + "...")
Example #37
0
def news_image_handler(instance, filename):
    _instance = instance
    headline = strip_tags(instance.headline)
    return "news/{year}/{headline}/{filename}".format(year=timezone.now().year,
                                                      headline=headline,
                                                      filename=filename)
Example #38
0
def explotation(request, block_code=None):
    data, data2 = {}, {}
    data1 = {0: 0, 12: 0, 18: 0, 25: 0, 32: 0, 40: 0, 50: 0, 65: 0, '>65': 0}
    exclude = []
    marks = {}
    form = FiltersForm()
    filters = {}
    block = None
    variables = Variable.objects.all()
    dimensions = Dimension.objects.exclude(name='')
    status = []
    if block_code:
        if Block.objects.filter(code=block_code, is_scored=True).exists():
            block = Block.objects.filter(code=block_code, is_scored=True)[0]
            filters = {'blocks': {'$in': [int(block_code)]}}
        else:
            return HttpResponseRedirect(reverse('explotation_statistic'))

        variables = Variable.objects.filter(
            variables_categories__categories_blocks=block
        ).distinct().order_by('id')

    form = FiltersForm(block=block)

    if block_code == str(settings.ANXIETY_DEPRESSION_BLOCK):
        status = [u'Ansiedad', u'Depresión']
        data2 = {
            u'Ansiedad': [0 for i in range(len(settings.HAMILTON.keys()) + 2)],
            u'Depresión': [0 for i in range(len(settings.BECK.keys()) + 1)]
        }
        exclude = ('suicide', 'unhope', 'ybocs')
    elif block_code == str(settings.UNHOPE_BLOCK):
        status = [u'Desesperanza', u'Suicidio']
        data2 = {
            u'Suicidio': [0 for i in range(len(settings.SUICIDE.keys()) + 2)],
            u'Desesperanza': [
                0 for i in range(len(settings.UNHOPE.keys()) + 4)
            ],
        }
        exclude = ('anxiety', 'depression', 'aves', 'ybocs')
        dimensions = Dimension.objects.none()
        delattr(form, 'dimensions')
    elif block_code == str(settings.YBOCS_BLOCK):
        status = [u'Obsesión/Compulsión']
        data2 = {
            u'Obsesión/Compulsión': [
                0 for i in range(len(settings.Y_BOCS.keys()) + 2)
            ]
        }
        exclude = ('anxiety', 'depression', 'aves', 'suicide', 'unhope')
        dimensions = Dimension.objects.none()
        delattr(form, 'dimensions')
    else:
        exclude = ('anxiety', 'depression', 'aves',
                   'suicide', 'unhope', 'ybocs')
        status = []
        dimensions = Dimension.objects.none()
        delattr(form, 'dimensions')

    for exc in exclude:
        del form.fields[exc]

    reports = []

    group = True
    template_name = 'statistic/explotation.html'
    if request.method == 'POST':
        template_name = 'statistic/explotation-ajax.html'
        form = FiltersForm(request.POST)
        for k, v in request.POST.items():
            if v:
                if k.startswith('date'):
                    day, month, year = v.split('/')
                    filters = update_filter(
                        filters, k, datetime(int(year), int(month), int(day))
                    )
                if k.startswith('age'):
                    filters = update_filter(filters, k, int(v))
                if k.startswith('profession'):
                    filters = update_filter(
                        filters, k, request.POST.getlist(k)
                    )
                if k.startswith('sex'):
                    filters = update_filter(
                        filters, k, [int(v) for v in request.POST.getlist(k)]
                    )
                if k.startswith('marital'):
                    filters = update_filter(
                        filters, k, [int(v) for v in request.POST.getlist(k)]
                    )
                if k.startswith('education'):
                    filters = update_filter(
                        filters, k, [int(v) for v in request.POST.getlist(k)]
                    )
                if k.startswith('anxiety'):
                    filters = update_filter(
                        filters,
                        'status.Ansiedad',
                        [int(v) for v in request.POST.getlist('anxiety')]
                    )
                if k.startswith('depression'):
                    filters = update_filter(
                        filters,
                        'status.Depresión',
                        [int(v) for v in request.POST.getlist('depression')]
                    )
                if k.startswith('unhope'):
                    filters = update_filter(
                        filters,
                        'status.Desesperanza',
                        [int(v) for v in request.POST.getlist('unhope')]
                    )
                if k.startswith('suicide'):
                    filters = update_filter(
                        filters,
                        'status.Suicidio',
                        [int(v) for v in request.POST.getlist('suicide')]
                    )
                if k.startswith('ybocs'):
                    filters = update_filter(
                        filters,
                        'status.Obsesión/Compulsión',
                        [int(v) for v in request.POST.getlist('ybocs')]
                    )
                if k.startswith('treatment'):
                    filters = update_filter(
                        filters,
                        k,
                        [v for v in request.POST.getlist(k)]
                    )
                if k.startswith('illnesses'):
                    filters = update_filter(
                        filters,
                        k,
                        [v for v in request.POST.getlist(k)]
                    )
                if k.startswith('ave'):
                    filters = update_filter(
                        filters,
                        k,
                        [int(v) for v in request.POST.getlist(k)]
                    )
                if k.startswith('variables') or k.startswith('dimensions'):
                    filters = update_filter(filters, k, int(v))
                if k.startswith('options'):
                    for o in request.POST.getlist(k):
                        if o == 'filter':
                            lp = [i['id'] for i in Profile.objects.filter(doctor=request.user).values('id')]
                            filters = update_filter(filters, '\patient_id', lp)
                        if o == 'ungroup':
                            group = False
    reports = Report.objects.raw_query(filters)

    if group:
        for r in reports:
            try:
                #Check for deleted patients
                p = Profile.objects.get(id=r.patient)
            except:
                # Regenerate ALL the database
                return regenerate_data(request, True)
            if r.patient in data:
                if (not data[r.patient].date
                    or (r.date and
                        data[r.patient].date and
                        r.date > data[r.patient].date)):
                    data[r.patient].date = r.date
                for var, mark in r.variables.items():
                    if isinstance(mark, (int, long, float)):
                        if var in data[r.patient].variables:
                            data[r.patient].variables[var].append(mark)
                        else:
                            data[r.patient].variables[var] = [mark, ]
                for dim, mark in r.dimensions.items():
                    if isinstance(mark, (int, long, float)):
                        if dim in data[r.patient].dimensions:
                            data[r.patient].dimensions[dim].append(mark)
                        else:
                            data[r.patient].dimensions[dim] = [mark, ]
            else:
                data[r.patient] = r
                for var, mark in r.variables.items():
                    if isinstance(mark, (int, long, float)):
                        data[r.patient].variables[var] = [mark, ]
                    else:
                        data[r.patient].variables[var] = []
                for dim, mark in r.dimensions.items():
                    if isinstance(mark, (int, long, float)):
                        data[r.patient].dimensions[dim] = [mark, ]
                    else:
                        data[r.patient].dimensions[dim] = []
                if block_code == str(settings.ANXIETY_DEPRESSION_BLOCK):
                    data[r.patient].status[u'Ansiedad'] = p.get_anxiety_status(index=True)
                    data[r.patient].status[u'Depresión'] = p.get_depression_status(index=True)

        for p in data.keys():
            for key, l in data[p].variables.items():
                if l:
                    data[p].variables[key] = reduce(lambda x, y: x + y, l) / len(l)
                else:
                    data[p].variables[key] = ''
            for key, l in data[p].dimensions.items():
                if l:
                    data[p].dimensions[key] = reduce(lambda x, y: x + y, l) / len(l)
                else:
                    data[p].dimensions[key] = ''
        reports = data.values()
        data = {}


    if status:
        reports = sorted(reports, key=lambda report: -((report.status[u'Ansiedad'] and int(report.status[u'Ansiedad']) or -1) + (report.status[u'Depresión'] and int(report.status[u'Depresión']) or -1)))
    else:
        reports = sorted(reports, key=lambda report: report.date)

    if request.GET.get('as', '') == 'xls':
        style_head = xlwt.easyxf('font: name Times New Roman, \
                                 color-index black, bold on')
        style_value = xlwt.easyxf('font: name Times New Roman, \
                                  color-index blue', num_format_str='#,##0.00')
        style_int = xlwt.easyxf('font: name Times New Roman, \
                                color-index green', num_format_str='#0')
        style_date = xlwt.easyxf(num_format_str='DD-MM-YYYY')

        wb = xlwt.Workbook(encoding='utf-8')
        ws = wb.add_sheet('Data')
        headers = [('age', _(u'Edad'), style_int),
                   ('sex', _(u'Sexo'), style_int),
                   ('education', _(u'Estudios'), style_int),
                   ('profession', _(u'Profesión'), style_int),
                   ('dimensions', [d.name for d in dimensions], style_value),
                   ('variables', [v.name for v in variables], style_value),
                   ('status', status, style_int),
                   ('date', (group
                             and _(u'Episodio más reciente')
                             or _(u'Fecha')), style_date)]
        ws.write_merge(0, 0, 0, 3, _(u'Datos demográficos'), style_head)
        offset = 4
        if dimensions.count():
            offset += dimensions.count()
            ws.write_merge(0, 0, 4, offset - 1, _(u'Dimensiones'), style_head)
        ws.write_merge(0, 0, offset, offset + variables.count() - 1,
                       _(u'Variables'), style_head)
        offset += variables.count()
        if len(status):
            ws.write_merge(0, 0, offset, offset + len(status),
                           _(u'Estratificación'), style_head)
        r, c = 2, 0
        for report in reports:
            for key, name, style in headers:
                if isinstance(name, list):
                    values = []
                    for n in name:
                        try:
                            if key == 'status':
                                st = ''
                                nst = getattr(report, key)[n]
                                if n == u'Ansiedad':
                                    st = [settings.HAMILTON[k][0] for k in sorted(settings.HAMILTON.keys())][nst]
                                elif n == u'Depresión':
                                    st = [settings.BECK[k][0] for k in sorted(settings.BECK.keys())][nst]
                                elif n == u'Desesperanza':
                                    st = [settings.UNHOPE[k][0] for k in sorted(settings.UNHOPE.keys())][nst]
                                elif n == u'Obsesión/Compulsión':
                                    st = [settings.Y_BOCS[k][0] for k in sorted(settings.Y_BOCS.keys())][nst]
                                elif n == u'Suicidio':
                                    st = [settings.SUICIDE[k][0] for k in sorted(settings.SUICIDE.keys())][nst]
                                values.append((n, strip_tags(st)))
                            else:
                                values.append((n, getattr(report, key)[n]))
                        except:
                            values.append((n, ''))
                else:
                    if key == 'sex':
                        values = [(name, report.patient.get_sex()), ]
                    elif key == 'education':
                        values = [(name, report.patient.get_education()), ]
                    else:
                        values = [(name, getattr(report, key)), ]
                for n, v in values:
                    if r == 2:
                        ws.write(1, c, n, style_head)
                    ws.write(r, c, v, style)
                    c += 1
            r += 1
            c = 0
        tmp_io = cStringIO.StringIO()
        wb.save(tmp_io)
        response = HttpResponse(tmp_io.getvalue(),
                                content_type='application/vnd.ms-excel')
        tmp_io.close()
        response['Content-Disposition'] = 'attachment; \
                filename="consulting30_data.xls"'
        return response

    else:
        #### Pyramids ####
        for r in reports:
            p = Profile.objects.get(id=r.patient)
            for var, mark in r.variables.items():
                if mark >= 0 and mark:
                    if var in data.keys() and p.sex in data[var].keys():
                        data[var][p.sex].append(mark)
                    elif var in data.keys():
                        data[var][p.sex] = [mark, ]
                    else:
                        data[var] = {p.sex: [mark, ]}
            found = False
            for age in sorted(data1.keys())[:-1]:
                if r.age <= age:
                    data1[age] += 1
                    found = True
                    break
            if not found:
                data1['>65'] += 1
            if data2:
                for k in status:
                    v = r.status[k]
                    if not isinstance(v, int):
                        v = 0
                    else:
                        if v > 0:
                            #Fix Offsets for scales shorter than Beck
                            if k == u"Desesperanza":
                                v += 3
                            elif k in [u"Ansiedad",
                                       u"Suicidio",
                                       u"Obsesión/Compulsión"]:
                                v += 1
                        v += 1
                    data2[k][v] += 1

        for varname, marks in data.items():
            for key, l in marks.items():
                if l:
                    data[varname][key] = reduce(lambda x, y: x + y, l) / len(l)
                else:
                    data[varname][key] = 0
        prev = None
        for age in sorted(data1.keys()):
            if prev and isinstance(age, int):
                label = "%d-%d" % (prev, age)
                data1[label] = data1[age]
                data1.pop(age)
            prev = age

        return render_to_response(template_name,
                                  {'data': data,
                                   'data1': data1,
                                   'data2': data2,
                                   'labels_for_data1': sorted(data1.keys()),
                                   'survey_block': block,
                                   'group': group,
                                   'form': form,
                                   'reports': list(reports),
                                   'variables': variables,
                                   'dimensions': dimensions,
                                   'status': status},
                                  context_instance=RequestContext(request))
Example #39
0
def map_metadata(request, mapid, template='maps/map_metadata.html'):

    map_obj = _resolve_map(request, mapid, 'base.view_resourcebase',
                           _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()
            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,
            }))
Example #40
0
def text(value):
    """
    Remove tags e retorna texto seguro
    """
    return mark_safe(strip_tags(value))
 def get_body(self):
     return strip_tags(super(HTMLEmail, self).get_body())
Example #42
0
 def summary(self):
     return strip_tags(self.html)[:300]
Example #43
0
 def __str__(self):
     return Truncator(strip_tags(self.body)).words(6, truncate="...")
Example #44
0
    def form_valid(self, form):
        message = form.cleaned_data.get("comment")
        image = form.cleaned_data.get("image", "")
        users = (self.request.POST.get("users[]", "")).split(",")
        user = self.request.user
        subject = self.ytvideo.topic.subject

        if users[0] != "":
            for u in users:
                to_user = User.objects.get(email=u)
                talk, create = Conversation.objects.get_or_create(
                    user_one=user, user_two=to_user)
                created = TalkMessages.objects.create(text=message,
                                                      talk=talk,
                                                      user=user,
                                                      subject=subject,
                                                      image=image)

                simple_notify = textwrap.shorten(strip_tags(message),
                                                 width=30,
                                                 placeholder="...")

                if image != "":
                    simple_notify += " ".join(_("[Photo]"))

                notification = {
                    "type":
                    "chat",
                    "subtype":
                    "subject",
                    "space":
                    subject.slug,
                    "user_icon":
                    created.user.image_url,
                    "notify_title":
                    str(created.user),
                    "simple_notify":
                    simple_notify,
                    "view_url":
                    reverse("chat:view_message",
                            args=(created.id, ),
                            kwargs={}),
                    "complete":
                    render_to_string("chat/_message.html",
                                     {"talk_msg": created}, self.request),
                    "container":
                    "chat-" + str(created.user.id),
                    "last_date":
                    _("Last message in %s") % (formats.date_format(
                        created.create_date, "SHORT_DATETIME_FORMAT")),
                }

                notification = json.dumps(notification)

                Group("user-%s" % to_user.id).send({"text": notification})

                ChatVisualizations.objects.create(viewed=False,
                                                  message=created,
                                                  user=to_user)
            success = str(_("The message was successfull sent!"))
            return JsonResponse({"message": success})
        erro = HttpResponse(str(_("No user selected!")))
        erro.status_code = 404
        return erro
Example #45
0
def xml_kangoo(request):
    today = datetime.date.today().strftime("%Y-%m-%d")
    doc = Document()
    products = doc.createElement("products")
    products.setAttribute("xmlns", "http://www.sklepy24.pl")
    products.setAttribute("xmlns:xsi",
                          "http://www.w3.org/2001/XMLSchema-instance")
    products.setAttribute("xsi:schemaLocation",
                          "http://www.w3.org/2001/XMLSchema-instance")
    products.setAttribute("date", today)
    doc.appendChild(products)

    shop_products = Product.published.all()

    for pr in shop_products:
        product = doc.createElement("product")
        product.setAttribute("id", pr.slug)
        products.appendChild(product)
        # elementy produktu
        name_elem = doc.createElement("name")
        product.appendChild(name_elem)
        name = doc.createTextNode(escape(pr.name))
        name_elem.appendChild(name)

        url_elem = doc.createElement("url")
        product.appendChild(url_elem)
        url = doc.createTextNode(
            DOMAIN + reverse("product_page", kwargs={"slug": pr.slug}))
        url_elem.appendChild(url)

        brand_elem = doc.createElement("brand")
        product.appendChild(brand_elem)
        brand = doc.createTextNode(escape(pr.manufacturer.name))
        brand_elem.appendChild(brand)

        categories_elem = doc.createElement("categories")
        product.appendChild(categories_elem)
        for cat in pr.categories.all():
            category_elem = doc.createElement("category")
            categories_elem.appendChild(category_elem)
            category = doc.createTextNode(escape(cat.name))
            category_elem.appendChild(category)

        pr_photos = pr.photos_set.all()
        if len(pr_photos):
            photo_elem = doc.createElement("photo")
            product.appendChild(photo_elem)
            photo = doc.createTextNode(
                escape(DOMAIN + pr.photos_set.all()[0].image.url).encode(
                    'ascii', 'xmlcharrefreplace'))
            photo_elem.appendChild(photo)

        description_elem = doc.createElement("description")
        product.appendChild(description_elem)
        description = doc.createTextNode(escape(strip_tags(pr.description)))
        description_elem.appendChild(description)

        price_elem = doc.createElement("price")
        product.appendChild(price_elem)
        price = doc.createTextNode(
            str(pr.price).replace(".", ",").rstrip("0").rstrip(",").strip())
        price_elem.appendChild(price)

    return HttpResponse(doc.toxml(), mimetype="text/xml")
Example #46
0
def comment_body_intro(obj):
    # Truncate comment body for display in the admin
    return strip_tags(obj.body[:20])
Example #47
0
 def prepare_caption(self, obj):
     caption = obj.caption
     caption = strip_tags(caption)
     caption = strip_entities(caption)
     return caption
Example #48
0
def xml_okazje(request):
    today = datetime.date.today().strftime("%Y-%m-%d")
    doc = Document()
    okazje = doc.createElement("okazje")
    doc.appendChild(okazje)
    offers = doc.createElement("offers")
    okazje.appendChild(offers)

    shop_products = Product.published.all()

    for pr in shop_products:
        offer = doc.createElement("offer")
        offers.appendChild(offer)
        # elementy produktu
        id_elem = doc.createElement("id")
        offer.appendChild(id_elem)
        id = doc.createTextNode(pr.slug)
        id_elem.appendChild(id)

        name_elem = doc.createElement("name")
        offer.appendChild(name_elem)
        name = doc.createTextNode(escape(pr.name))
        name_elem.appendChild(name)

        url_elem = doc.createElement("url")
        offer.appendChild(url_elem)
        url = doc.createTextNode(
            DOMAIN + reverse("product_page", kwargs={"slug": pr.slug}))
        url_elem.appendChild(url)

        brand_elem = doc.createElement("producer")
        offer.appendChild(brand_elem)
        brand = doc.createTextNode(escape(pr.manufacturer.name))
        brand_elem.appendChild(brand)

        category_elem = doc.createElement("category")
        offer.appendChild(category_elem)
        path = pr.categories.all()[0].get_ancestors()[1:]
        path_txt = "/".join([p.name for p in path])
        path_txt += "/" + pr.categories.all()[0].name
        category = doc.createTextNode(escape(path_txt))
        category_elem.appendChild(category)

        photo_elem = doc.createElement("image")
        offer.appendChild(photo_elem)
        pr_photos = pr.photos_set.all()
        if len(pr_photos):
            photo = doc.createTextNode(
                escape(DOMAIN + pr_photos[0].image.url).encode(
                    'ascii', 'xmlcharrefreplace'))
            photo_elem.appendChild(photo)

        description_elem = doc.createElement("description")
        offer.appendChild(description_elem)
        description = doc.createTextNode(escape(strip_tags(pr.description)))
        description_elem.appendChild(description)

        price_elem = doc.createElement("price")
        offer.appendChild(price_elem)
        price = doc.createTextNode(
            str(pr.price).replace(".", ",").rstrip("0").rstrip(",").strip())
        price_elem.appendChild(price)

    return HttpResponse(doc.toxml(), mimetype="text/xml")
Example #49
0
 def item_title(self, item):
     return strip_tags(item.content_parsed)[:100]
Example #50
0
 def __str__(self):
     return Truncator(strip_tags(self.text)).words(20)
Example #51
0
 def embedded_content_for_search(self):
     contents = strip_tags('/n'.join([
         '/n'.join(value)
         for value in self.subpages.all().values_list('title', 'body')
     ]))
     return contents
Example #52
0
 def prepare_description(self, obj):
     description = obj.description
     description = strip_tags(description)
     description = strip_entities(description)
     return description
Example #53
0
 def get_meta_description(self):
     return truncatewords(
         strip_tags(self.body.render_as_block()),
         20
     )
Example #54
0
 def plain_text_description(self):
     if settings.USE_JSON_CONTENT:
         return json_content_to_raw_text(self.description_json)
     return strip_tags(self.description)
Example #55
0
 def add_help_attrs(self, widget=None):
     if widget is None:
         widget = self.widget
     if not isinstance(widget, CheckboxInput):
         widget.attrs["title"] = widget.attrs.get(
             "title", escape(strip_tags(self.field_help)))
Example #56
0
def clean_html(text):
    value = strip_tags(text).replace('\n', '')
    return re.sub(r'&(?:\w+|#\d+);', '', value)
 def __unicode__(self):
     return Truncator(strip_tags(self.body)).words(3, truncate="...")
Example #58
0
 def add_error_attrs(self):
     field_title = self.widget.attrs.get("title", "")
     field_title += " " + " ".join(
         [strip_tags(e) for e in self.field_errors])
     self.widget.attrs["title"] = field_title.strip()
Example #59
0
def striptags(value):
    "Strips all [X]HTML tags"
    from django.utils.html import strip_tags
    return strip_tags(value)
Example #60
0
    def handle(self, *args, **options):
        filename = options['file'][0]
        blog_index = BlogIndex.objects.all().first()

        if not os.path.isfile(filename):
            raise CommandError('Could not find file at path "%s"' % filename)

        if options['dryrun']:
            self.stdout.write('Dry run, no database inserts. Parsed CSV data:')

        with open(filename) as f:
            # csv reader apparently too stupid to handle commas in fields so use "|"
            csvreader = csv.DictReader(f, delimiter='|')
            for row in csvreader:
                if options['dryrun']:
                    print(row)

                else:
                    # create a BlogPage from CSV data
                    try:
                        # date_created is a UNIX timestamp stored as a string
                        post_date = datetime.datetime.fromtimestamp(
                            int(row['date_created']))
                        # strip HTML tags & truncate the body to create search description
                        search_desc = truncate(strip_tags(row['body']))
                        post = BlogPage(
                            title=row['title'],
                            slug=row['slug'],
                            search_description=search_desc,
                            date=post_date,
                            imported_body=row['body'],
                        )
                        # have to add this way to get page's depth & path fields right
                        blog_index.add_child(instance=post)
                        self.stdout.write(
                            self.style.SUCCESS(
                                'Successfully created blog post %s' % post))
                    except:
                        self.stdout.write(
                            self.style.ERROR('Unable to create blog post %s' %
                                             row['title']))
                        self.stdout.write(sys.exc_info()[0])

                    # if there is one, create an image in Wagtail & attach it to the blog post
                    img_field = row.get('main_image', None)

                    if not options[
                            'noimages'] and img_field and img_field != 'NULL':
                        try:
                            wagtail_image = add_img_to_wagtail(img_field)
                            post.main_image = wagtail_image
                            post.save()
                            self.stdout.write(
                                self.style.SUCCESS(
                                    'Successfully added main image %s' %
                                    img_field))
                        except:
                            self.stdout.write(
                                self.style.ERROR(
                                    'Unable to add main image %s' % img_field))
                            self.stdout.write(sys.exc_info()[0])