def render(self, name, value, attrs=None,): substitutions = { 'initial_text': self.initial_text, 'input_text': self.input_text, 'clear_template': '', 'clear_checkbox_label': self.clear_checkbox_label, } template = u'%(input)s' substitutions['input'] = super(ClearableFileInput, self).render(name, value, attrs) if value and hasattr(value, "url"): template = self.template_with_initial if self.preview: substitutions['initial'] = (u'<a href="{0}">{1}</a><br /><br />\ <a href="{0}" target="_blank"><img src="{0}" alt="" width="{2}" /></a><br /><br />'.format (escape(value.url),'...'+escape(force_unicode(value))[-self.url_length:], self.image_width)) else: substitutions['initial'] = (u'<a href="{0}">{1}</a>'.format (escape(value.url),'...'+escape(force_unicode(value))[-self.url_length:])) if not self.is_required: checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) substitutions['clear_checkbox_name'] = conditional_escape(checkbox_name) substitutions['clear_checkbox_id'] = conditional_escape(checkbox_id) substitutions['clear'] = CheckboxInput().render(checkbox_name, False, attrs={'id': checkbox_id}) substitutions['clear_template'] = self.template_with_clear % substitutions return mark_safe(template % substitutions)
def comment_it(request, f_id): user = auth.get_user(request) if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): comment = Comment(text=html.escape(comment_form.cleaned_data['text']), author=user, film=Film.objects.get(pk=f_id)) comment.save() response_data = { "code": 0, "response": "OK", "email": user.email, "text": html.escape(comment_form.cleaned_data['text']), "c_id": comment.id, "f_id": f_id, "is_staff": user.is_staff, } return HttpResponse(json.dumps(response_data), content_type="application/json") else: return HttpResponse(json.dumps({"code": 0, "response": "Not valid"}), content_type="application/json") else: return redirect('/plitka/filmbody/%s' % f_id)
def render(self, name, value, attrs=None, choices=()): dev = None if value: try: dev = Device.objects.get(sn=(value or '').lower()) except Device.DoesNotExist: pass if dev is None: output = [ '<input type="hidden" name="%s" value="">' % (escape(name),), '<div class="input uneditable-input">', '<i class="fugue-icon %s"></i> %s</a>' % ( presentation.get_device_icon(None), 'None'), '</div>', ] else: output = [ '<input type="hidden" name="%s" value="%s">' % (escape(name), escape(value)), '<div class="input uneditable-input">', '<a href="/ui/racks/%s/info/">' '<i class="fugue-icon %s"></i> %s</a>' % (slugify(dev.sn), presentation.get_device_icon(dev), escape(dev.name)), '</div>', ] return mark_safe('\n'.join(output))
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", {})
def generate_media_player(fileurl, image="", autostart=False, width=450, height=350, **kwargs): # Warning - fileurl had better be an ABSOLUTE url, else some media players won't find the file ! md5 = hashlib.md5() md5.update(fileurl.encode('ascii', 'ignore')) myhash = md5.hexdigest()[0:8] options = \ { "title": "Video Viewer", "id": myhash, # risks of collision are ultra weak... "lib_dir": escape(LIB_DIR), "autoplay": "true" if autostart else "false", "allowfullscreen": "true", "transparency": "opaque", # transparent, window "background": "#000000", "backgroundqt": "black", "fileurl": escape(fileurl), # warning, sometimes would need urlencoding actually! "image": escape(image), # warning - gif images aren't supported by all players ! "width": escape(width), "height": escape(height), "additional_flash_vars": "" # must begin with '&' if present, and be escaped/urlencoded properly } options.update(kwargs) extension = os.path.splitext(fileurl)[1][1:].lower() # we remove the dot and lower-case the extension for extensions in _media_player_templates.keys(): if extension in extensions: template = _media_player_templates[extensions] return template % options raise ValueError("Unsupported media type")
def format_file_comment_msg(self): try: d = json.loads(self.detail) except Exception as e: logger.error(e) return _(u"Internal error") repo_id = d['repo_id'] file_path = d['file_path'] author = d['author'] comment = d['comment'] repo = seafile_api.get_repo(repo_id) if repo is None or not seafile_api.get_file_id_by_path(repo.id, file_path): self.delete() return None file_name = os.path.basename(file_path) msg = _("File <a href='%(file_url)s'>%(file_name)s</a> has a new comment from user %(author)s") % { 'file_url': reverse('view_lib_file', args=[repo_id, file_path]), 'file_name': escape(file_name), 'author': escape(email2nickname(author)), } return msg
def tag(self, alt='', use_size=None, **attrs): """ Return a standard XHTML ``<img ... />`` tag for this field. Use ``alt`` to specify alt-text. If ``use_size`` isn't set, it will be default to ``True`` or ``False`` depending on whether the file storage is local or not. All other keyword arguments are added as (properly escaped) extra attributes to the `img` tag. """ if use_size is None: try: self.field.storage.path(self.name) use_size = True except NotImplementedError: use_size = False attrs['alt'] = escape(alt) attrs['src'] = escape(self.url) if use_size: attrs.update(dict(width=self.width, height=self.height)) attrs = ' '.join(['%s="%s"' % (key, escape(value)) for key, value in attrs.items()]) return mark_safe('<img %s />' % attrs)
def format_group_join_request(self): """ Arguments: - `self`: """ try: d = json.loads(self.detail) except Exception as e: logger.error(e) return _(u"Internal error") username = d['username'] group_id = d['group_id'] join_request_msg = d['join_request_msg'] group = ccnet_api.get_group(group_id) if group is None: self.delete() return None msg = _(u"User <a href='%(user_profile)s'>%(username)s</a> has asked to join group <a href='%(href)s'>%(group_name)s</a>, verification message: %(join_request_msg)s") % { 'user_profile': reverse('user_profile', args=[username]), 'username': username, 'href': HASH_URLS['GROUP_MEMBERS'] % {'group_id': group_id}, 'group_name': escape(group.group_name), 'join_request_msg': escape(join_request_msg), } return msg
def format_add_user_to_group(self): """ Arguments: - `self`: """ try: d = json.loads(self.detail) except Exception as e: logger.error(e) return _(u"Internal error") group_staff = d['group_staff'] group_id = d['group_id'] group = ccnet_api.get_group(group_id) if group is None: self.delete() return None msg = _(u"User <a href='%(user_profile)s'>%(group_staff)s</a> has added you to group <a href='%(href)s'>%(group_name)s</a>") % { 'user_profile': reverse('user_profile', args=[group_staff]), 'group_staff': escape(email2nickname(group_staff)), 'href': reverse('group', args=[group_id]), 'group_name': escape(group.group_name)} return msg
def render_data(self, obj): """ Renders the column data to a string. This may contain HTML. """ id_field = '%s_id' % self.field_name # Look for this directly so that we don't end up fetching the # data for the object. if id_field in obj.__dict__: pk = obj.__dict__[id_field] if pk in self.data_cache: return self.data_cache[pk] else: value = getattr(obj, self.field_name) self.data_cache[pk] = escape(value) return value else: # Follow . separators like in the django template library value = obj for field_name in filter(None, self.field_name.split('.')): value = getattr(value, field_name) if callable(value): value = value() return escape(value)
def format_group_message_title(self): """ Arguments: - `self`: """ try: d = self.group_message_detail_to_dict() except self.InvalidDetailError as e: logger.error(e) return _(u"Internal error") group_id = d.get('group_id') group = ccnet_api.get_group(group_id) if group is None: self.delete() return None msg_from = d.get('msg_from') if msg_from is None: msg = _(u"<a href='%(href)s'>%(group_name)s</a> has a new discussion.") % { 'href': HASH_URLS['GROUP_DISCUSS'] % {'group_id': group.id}, 'group_name': group.group_name} else: msg = _(u"%(user)s posted a new discussion in <a href='%(href)s'>%(group_name)s</a>.") % { 'href': HASH_URLS['GROUP_DISCUSS'] % {'group_id': group.id}, 'user': escape(email2nickname(msg_from)), 'group_name': escape(group.group_name) } return msg
def render_activity(item): if not item.group: # not implemented return action_str = ACTIVITY_ACTION_STRINGS[item.type] if item.type == Activity.CREATE_ISSUE: action_str = action_str.format(**item.data) output = '' if item.user: user = item.user name = user.first_name or user.email output += '<span class="avatar"><img src="%s"></span> ' % (get_gravatar_url(user.email, size=20),) output += '<strong>%s</strong> %s' % (escape(name), action_str) else: output += '<span class="avatar sentry"></span> ' output += 'The system %s' % (action_str,) output += ' <span class="sep">—</span> <span class="time">%s</span>' % (timesince(item.datetime),) if item.type == Activity.NOTE: output += linebreaks(urlize(escape(item.data['text']))) return mark_safe(output)
def trans(name, langs=None, include_lang=True, use_delim=True, prefix=False, escape=False): langs = langs or ["default"] if include_lang: if use_delim: tag = lambda lang: ' [%s] ' % lang else: tag = lambda lang: ''' <span class="btn btn-xs btn-info btn-langcode-preprocessed">%(lang)s</span> ''' % {"lang": html.escape(lang)} else: tag = lambda lang: "" for lang in langs: # "name[lang] is not None" added to avoid empty lang tag in case of empty value for a field. # When a value like {'en': ''} is passed to trans it returns [en] which then gets added # as value on the input field and is visible in the text box. # Ref: https://github.com/dimagi/commcare-hq/pull/16871/commits/14453f4482f6580adc9619a8ad3efb39d5cf37a2 if lang in name and name[lang] is not None: n = six.text_type(name[lang]) if escape: n = html.escape(n) affix = ("" if langs and lang == langs[0] else tag(lang)) return affix + n if prefix else n + affix # ok, nothing yet... just return anything in name for lang, n in sorted(name.items()): n = six.text_type(n) if escape: n = html.escape(n) affix = tag(lang) return affix + n if prefix else n + affix return ""
def choice_html(self, choice): """ Format a choice using :py:attr:`choice_html_format`. """ return self.choice_html_format % ( escape(self.choice_value(choice)), escape(self.choice_label(choice)))
def render_edit_link(obj, db_field, popup=True, request=None): """ """ change_permission = '%s.change_%s' % ( obj._meta.app_label, obj._meta.object_name.lower()) if request and not request.user.has_perm(change_permission, obj): return u'<strong>%s</strong>' % escape(smart_unicode(obj)) try: change_url = reverse( "admin:%s_%s_change" % ( obj._meta.app_label, obj._meta.object_name.lower()), args=(obj.pk,)) except NoReverseMatch: change_url = '#error:no-change-form' input_id = 'id_%s' % db_field.name # (TODO: Use actual id prefix if custom -- pass form in via widget init) return render_to_string( _template_list(obj, '_edit_popup_link.html'), { 'change_url': change_url, 'input_id': input_id, 'object_string': escape(smart_unicode(obj)), 'obj': obj, 'popup': popup, })
def render(self, context): from ..utils import autodiscover autodiscover() file = get_cachefile(context, self._generator_id, self._generator_kwargs) attrs = dict((k, v.resolve(context)) for k, v in self._html_attrs.items()) # Only add width and height if neither is specified (to allow for # proportional in-browser scaling). if not 'width' in attrs and not 'height' in attrs: attrs.update(width=file.width, height=file.height) if 'title' in attrs and attrs['title']==u"copy_alt": attrs['title']=attrs['alt'] if 'title' in attrs: attrs['title']=attrs['title'].replace('[company]', Site.objects.get_current().company) attrs['title']=attrs['title'].replace('[country]', Site.objects.get_current().country) if 'alt' in attrs: attrs['alt']=attrs['alt'].replace('[company]', Site.objects.get_current().company) attrs['alt']=attrs['alt'].replace('[country]', Site.objects.get_current().country) attrs['src'] = file.url attr_str = ' '.join('%s="%s"' % (escape(k), escape(v)) for k, v in attrs.items()) if 'no_tag' in attrs: return mark_safe(attrs['src']) return mark_safe(u'<img %s />' % attr_str)
def get_template_exception_info(self): origin, (start, end) = self.exc_value.source template_source = origin.reload() context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(template_source)): if start >= upto and end <= next: line = num before = escape(template_source[upto:start]) during = escape(template_source[start:end]) after = escape(template_source[end:next]) source_lines.append( (num, escape(template_source[upto:next])) ) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) self.template_info = { 'message': self.exc_value.args[0], 'source_lines': source_lines[top:bottom], 'before': before, 'during': during, 'after': after, 'top': top, 'bottom': bottom, 'total': total, 'line': line, 'name': origin.name, }
def render(self, name, value, attrs=None, choices=()): dm = None if value: try: dm = DeviceModel.objects.get(id=value) except DeviceModel.DoesNotExist: pass if dm is None: output = [ '<input type="hidden" name="%s" value="">' % (escape(name),), '<div class="input uneditable-input">', '<i class="fugue-icon %s"></i> %s</a>' % ( presentation.get_device_model_icon(None), 'None'), '</div>', ] else: output = [ '<input type="hidden" name="%s" value="%s">' % (escape(name), escape(value)), '<div class="input uneditable-input">', '<a href="/admin/discovery/devicemodel/%s">' '<i class="fugue-icon %s"></i> %s</a>' % (dm.id, presentation.get_device_model_icon(dm), escape(dm.name)), '</div>', ] return mark_safe('\n'.join(output))
def urlize(url, name=None, target="_blank", nofollow=True): """Make an url clickable. Args: url: the actual url, such as '/user/list' name: the display name, such as 'List Users', defaults to url target: the 'target' attribute of the <a> element nofollow: whether to add the 'rel="nofollow"' attribute """ if not url: return "" from django.utils.safestring import mark_safe from django.utils.html import escape safe_url = escape(url) safe_name = escape(name) link = URL_PATTERN % { "url": safe_url, "name": safe_name if name else safe_url, "target": ' target="%s"' % target if target else "", "nofollow": ' rel="nofollow"' if nofollow else "", } return mark_safe(link)
def format_value(value): if getattr(value, 'is_hyperlink', False): name = six.text_type(value.obj) return mark_safe('<a href=%s>%s</a>' % (value, escape(name))) if value is None or isinstance(value, bool): return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value]) elif isinstance(value, list): if any([isinstance(item, (list, dict)) for item in value]): template = loader.get_template('rest_framework/admin/list_value.html') else: template = loader.get_template('rest_framework/admin/simple_list_value.html') context = {'value': value} return template.render(context) elif isinstance(value, dict): template = loader.get_template('rest_framework/admin/dict_value.html') context = {'value': value} return template.render(context) elif isinstance(value, six.string_types): if ( (value.startswith('http:') or value.startswith('https:')) and not re.search(r'\s', value) ): return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value))) elif '@' in value and not re.search(r'\s', value): return mark_safe('<a href="mailto:{value}">{value}</a>'.format(value=escape(value))) elif '\n' in value: return mark_safe('<pre>%s</pre>' % escape(value)) return six.text_type(value)
def followup_edit(request, ticket_id, followup_id, ): "Edit followup options with an ability to change the ticket." followup = get_object_or_404(FollowUp, id=followup_id) ticket = get_object_or_404(Ticket, id=ticket_id) if request.method == 'GET': form = EditFollowUpForm(initial= {'title': escape(followup.title), 'ticket': followup.ticket, 'comment': escape(followup.comment), 'public': followup.public, 'new_status': followup.new_status, }) return render_to_response('helpdesk/followup_edit.html', RequestContext(request, { 'followup': followup, 'ticket': ticket, 'form': form, })) elif request.method == 'POST': form = EditFollowUpForm(request.POST) if form.is_valid(): title = form.cleaned_data['title'] _ticket = form.cleaned_data['ticket'] comment = form.cleaned_data['comment'] public = form.cleaned_data['public'] new_status = form.cleaned_data['new_status'] #will save previous date old_date = followup.date followup.delete() new_followup = FollowUp(title=title, date=old_date, ticket=_ticket, comment=comment, public=public, new_status=new_status, ) new_followup.save() return HttpResponseRedirect(reverse('helpdesk_view', args=[ticket.id]))
def test_custom_serialization_widget(self): class CustomGeometryWidget(forms.BaseGeometryWidget): template_name = "gis/openlayers.html" deserialize_called = 0 def serialize(self, value): return value.json if value else "" def deserialize(self, value): self.deserialize_called += 1 return GEOSGeometry(value) class PointForm(forms.Form): p = forms.PointField(widget=CustomGeometryWidget) point = GEOSGeometry("SRID=4326;POINT(9.052734375 42.451171875)") form = PointForm(data={"p": point}) self.assertIn(escape(point.json), form.as_p()) CustomGeometryWidget.called = 0 widget = form.fields["p"].widget # Force deserialize use due to a string value self.assertIn(escape(point.json), widget.render("p", point.json)) self.assertEqual(widget.deserialize_called, 1) form = PointForm(data={"p": point.json}) self.assertTrue(form.is_valid()) # Ensure that resulting geometry has srid set self.assertEqual(form.cleaned_data["p"].srid, 4326)
def instance_link(self, operation): try: return admin_link('instance')(self, operation) except: return _("deleted {0} {1}").format( escape(operation.content_type), escape(operation.object_id) )
def format_userinfo(user): parts = user.username.split("@") if len(parts) == 1: username = user.username else: username = parts[0].lower() return mark_safe('<span title="%s">%s</span>' % (escape(user.username), escape(username)))
def render(self, name, value, attrs=None): """Render the custom widget.""" substitutions = { 'input_text': self.input_text, 'clear_template': '', 'clear_checkbox_label': self.clear_checkbox_label, } template = '%(input)s' substitutions['input'] = Input.render(self, name, value, attrs) if value and hasattr(value, "url"): template = ('%(initial)s %(clear_template)s<br />%(input_text)s: ' '%(input)s') substitutions['initial'] = ( '<img class="img-responsive" src="%s" alt="%s"/>' % ( escape(value.url), escape(force_unicode(value)))) if not self.is_required: checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) substitutions['clear_checkbox_name'] = conditional_escape( checkbox_name) substitutions['clear_checkbox_id'] = conditional_escape( checkbox_id) substitutions['clear'] = CheckboxInput().render( checkbox_name, False, attrs={'id': checkbox_id}) substitutions['clear_template'] = \ self.template_with_clear % substitutions return mark_safe(template % substitutions)
def description_as_html(self, description, params): user = self.activity.user if user: name = user.get_display_name() else: name = 'Sentry' fmt = u'<span class="avatar-container">{}</span> <strong>{}</strong>' author = mark_safe(fmt.format( self.avatar_as_html(), escape(name), )) an_issue = u'<a href="{}">an issue</a>'.format( escape(self.get_group_link()), ) context = { 'author': author, 'an issue': an_issue, } context.update(params) return mark_safe(description.format(**context))
def test_article_list_and_feed(self): response = self.client.get(reverse('lbe:article_list')) self.assertEqual(response.status_code, 200) article_pub = Article.objects.create( title=rs(20), content=rt(4), created=tz.now(), slug=rcs(10), is_published=True ) article_not_pub = Article.objects.create( title=rs(20), content=rt(4), created=tz.now(), slug=rcs(10) ) page_pub = Article.objects.create( title=rs(20), content=rt(4), created=tz.now(), slug=rcs(10), is_standalone=True, is_published=True ) page_not_pub = Article.objects.create( title=rs(20), content=rt(4), created=tz.now(), slug=rcs(10), is_standalone=True ) response = self.client.get(reverse('lbe:article_list')) self.assertEqual(response.status_code, 200) self.assertIn(article_pub, response.context['object_list']) for a in (article_not_pub, page_pub, page_not_pub): self.assertNotIn(a, response.context['object_list']) response = self.client.get(reverse('lbe:rss')) self.assertEqual(response.status_code, 200) self.assertIn(escape(article_pub.get_content()), force_text(response)) for a in (article_not_pub, page_pub, page_not_pub): self.assertNotIn(escape(a.get_content()), force_text(response))
def test_article_comments_rss(self): article = Article.objects.create( title=rs(20), content=rt(4), created=tz.now(), slug=rcs(10), is_published=True ) response = self.client.get( reverse('lbe:article_comments_rss', args=[article.slug]) ) self.assertEqual(response.status_code, 200) comment_approved = Comment.objects.create( article=article, user_name=rs(10), content=rt(1), created=tz.now(), is_approved=True ) comment_not_approved = Comment.objects.create( article=article, user_name=rs(10), content=rt(1), created=tz.now(), is_approved=False ) response = self.client.get( reverse('lbe:article_comments_rss', args=[article.slug]) ) self.assertEqual(response.status_code, 200) self.assertIn( escape(comment_approved.get_content()), force_text(response) ) self.assertNotIn( escape(comment_not_approved.get_content()), force_text(response) )
def response_add(self, request, obj, post_url_continue='../%s/'): """ Determines the HttpResponse for the add_view stage. """ opts = obj._meta pk_value = obj._get_pk_val() msg = _('The %(name)s "%(obj)s" was added successfully.') % {'name': force_unicode(opts.verbose_name), 'obj': force_unicode(obj)} # Here, we distinguish between different save types by checking for # the presence of keys in request.POST. if request.POST.has_key("_continue"): self.message_user(request, msg + ' ' + _("You may edit it again below.")) if request.POST.has_key("_popup"): post_url_continue += "?_popup=1" return HttpResponseRedirect(post_url_continue % pk_value) if request.POST.has_key("_popup"): return HttpResponse('<script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script>' % \ # escape() calls force_unicode. (escape(pk_value), escape(obj))) elif request.POST.has_key("_addanother"): self.message_user(request, msg + ' ' + (_("You may add another %s below.") % force_unicode(opts.verbose_name))) return HttpResponseRedirect(request.path) else: self.message_user(request, msg) # Figure out where to redirect. If the user has change permission, # redirect to the change-list page for this object. Otherwise, # redirect to the admin index. if self.has_change_permission(request, None): post_url = '../' else: post_url = '../../../' return HttpResponseRedirect(post_url)
def format_callback(obj): has_admin = obj.__class__ in admin_site._registry opts = obj._meta if has_admin: admin_url = reverse('%s:%s_%s_change' % (admin_site.name, opts.app_label, opts.object_name.lower()), None, (quote(obj._get_pk_val()),)) p = '%s.%s' % (opts.app_label, opts.get_delete_permission()) if not user.has_perm(p): perms_needed.add(opts.verbose_name) # Display a link to the admin page. return mark_safe(u'<span class="label label-info">%s:</span> <a href="%s">%s</a>' % (escape(capfirst(opts.verbose_name)), admin_url, escape(obj))) else: # Don't display link to edit, because it either has no # admin or is edited inline. return mark_safe(u'<span class="label label-info">%s:</span> %s' % (escape(capfirst(opts.verbose_name)), escape(obj)))
def form_valid(self, form): self.object = form.save() return HttpResponse(""" <script type="text/javascript">opener.dismissAddAnotherPopup(window, "%s", "%s");</script> """ % (escape(form.instance._get_pk_val()), escape(form.instance)))
def run(request, api=False): """View iOS Files.""" try: logger.info('View iOS Source File') exp = 'Error Description' file_format = None if api: fil = request.POST['file'] md5_hash = request.POST['hash'] mode = request.POST['type'] viewsource_form = ViewSourceIOSApiForm(request.POST) else: fil = request.GET['file'] md5_hash = request.GET['md5'] mode = request.GET['type'] viewsource_form = ViewSourceIOSForm(request.GET) typ = set_ext_api(fil) if not viewsource_form.is_valid(): err = FormUtil.errors_message(viewsource_form) if api: return err return print_n_send_error_response(request, err, False, exp) base = Path(settings.UPLD_DIR) / md5_hash if mode == 'ipa': src1 = base / 'payload' src2 = base / 'Payload' if src1.exists(): src = src1 elif src2.exists(): src = src2 else: raise Exception('MobSF cannot find Payload directory') elif mode == 'ios': src = base sfile = src / fil sfile = sfile.as_posix() if not is_safe_path(src, sfile): msg = 'Path Traversal Detected!' if api: return {'error': 'Path Traversal Detected!'} return print_n_send_error_response(request, msg, False, exp) dat = '' sql_dump = {} if typ == 'm': file_format = 'cpp' with io.open(sfile, mode='r', encoding='utf8', errors='ignore') as flip: dat = flip.read() elif typ == 'xml': file_format = 'xml' with io.open(sfile, mode='r', encoding='utf8', errors='ignore') as flip: dat = flip.read() elif typ == 'plist': file_format = 'json' dat = biplist.readPlist(sfile) try: dat = json.dumps(dat, indent=4, sort_keys=True) except Exception: pass elif typ == 'db': file_format = 'asciidoc' sql_dump = read_sqlite(sfile) elif typ == 'txt' and fil == 'classdump.txt': file_format = 'cpp' app_dir = os.path.join(settings.UPLD_DIR, md5_hash + '/') cls_dump_file = os.path.join(app_dir, 'classdump.txt') if is_file_exists(cls_dump_file): with io.open( cls_dump_file, # lgtm [py/path-injection] mode='r', encoding='utf8', errors='ignore') as flip: dat = flip.read() else: dat = 'Class Dump result not Found' elif typ == 'txt': file_format = 'text' with io.open(sfile, mode='r', encoding='utf8', errors='ignore') as flip: dat = flip.read() else: if api: return {'error': 'Invalid Parameters'} return HttpResponseRedirect('/error/') context = { 'title': escape(ntpath.basename(fil)), 'file': escape(ntpath.basename(fil)), 'type': file_format, 'data': dat, 'sqlite': sql_dump, 'version': settings.MOBSF_VER, } template = 'general/view.html' if api: return context return render(request, template, context) except Exception as exp: logger.exception('Error Viewing Source') msg = str(exp) exp = exp.__doc__ if api: return print_n_send_error_response(request, msg, True, exp) return print_n_send_error_response(request, msg, False, exp)
def test_validation_errors_are_sent_back_to_home_page_template(self): response = self.client.post('/lists/new', data={'text': ''}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'home.html') expected_error = escape("You can't have an empty list item") self.assertContains(response, expected_error)
def linkfy_post(self): return bleach.linkify(escape(self.post))
def test_validation_errors_are_shown_on_home_page(self): response = self.client.post('/lists/new', data={'text': ''}) self.assertContains(response, escape(EMPTY_LIST_ERROR))
def test_for_invalid_input_shows_error_on_page(self): response = self.post_invalid_input() self.assertContains(response, escape(EMPTY_LIST_ERROR))