Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __init__(self):
self.rule_refs = []
rules = Rule.objects.all()
for r in rules:
rr = RuleRef(r.rule_id, r)
self.rule_refs.append(rr)
rule.scope=scope
rule.category = RuleCategory.objects.get(rule_category_code=r['rule_category'])
rule.group=group
rule.language_dependancy=r['language_dependency']
rule.primary_property=r['primary_property']
rule.resource_properties=resource_properties
rule.validation=r['validate']
rule.wcag_primary = SuccessCriterion.get_by_wcag_number(r['wcag_primary'])
rule.updated_date=r['last_updated']
NodeResultMessage.objects.filter(rule=rule).delete()
except ObjectDoesNotExist:
print(" Creating Rule: " + r['nls_rule_id'])
resource_properties = ",".join(r['resource_properties'])
rule = Rule(rule_id=r['rule_id'],scope=scope,group=group,language_dependancy=r['language_dependency'],primary_property=r['primary_property'],resource_properties=resource_properties,validation=r['validate'],updated_date=r['last_updated'])
rule.wcag_primary = SuccessCriterion.get_by_wcag_number(r['wcag_primary'])
rule.category = RuleCategory.objects.get(rule_category_code=r['rule_category'])
rule.slug = r['rule_id'].lower().replace('_', '')
rule.save()
rule.wcag_related.clear();
for related in r['wcag_related']:
rule.wcag_related.add(SuccessCriterion.get_by_wcag_number(related))
rule.target_resources.clear();
for m in r['target_resources']:
try:
rule.target_resources.add(ElementDefinition.get_by_title(m))
except:
pass
A_BYPASS = Transformation.A_BYPASS
# Lateral
LATERAL = Transformation.LATERAL
L_AUTO = Transformation.L_AUTO
L_YES = Transformation.L_YES
L_NO = Transformation.L_NO
# Target
TARGET = Transformation.TARGET
T_AUTO = Transformation.T_AUTO
T_SOURCE = Transformation.T_SOURCE
T_DST = Transformation.T_DESTINATION
T_NONE = Transformation.T_NONE
rule_str = Rule.__name__.lower()
category_str = Category.__name__.lower()
ruleset_str = Ruleset.__name__.lower()
cls.TRANSFORMATIONS = {
ACTION: {
rule_str: {
A_DROP: None, A_REJECT: None, A_FILESTORE: None, A_NONE: None, A_BYPASS: None,
},
category_str: {
A_DROP: None, A_REJECT: None, A_FILESTORE: None, A_NONE: None, A_BYPASS: None,
},
ruleset_str: {
A_DROP: None, A_REJECT: None, A_FILESTORE: None, A_BYPASS: None,
}
},
LATERAL: {
def rule(request, rule_id, key = 'pk'):
if request.is_ajax():
rule = get_object_or_404(Rule, sid=rule_id)
rule.highlight_content = SuriHTMLFormat(rule.content)
data = { 'msg': rule.msg, 'sid': rule.sid, 'content': rule.content,
'highlight_content': rule.highlight_content}
return HttpResponse(json.dumps(data),
content_type="application/json")
if key == 'pk':
rule = get_object_or_404(Rule, pk=rule_id)
else:
rule = get_object_or_404(Rule, sid=rule_id)
rule_path = [rule.category.source, rule.category]
rule.highlight_content = SuriHTMLFormat(rule.content)
references = extract_rule_references(rule)
# build table of rulesets and display if rule is active
rulesets = Ruleset.objects.all()
def search(request):
context = {}
length = 0
rules_width = 4
search = None
if request.method == 'POST':
if request.POST.has_key('search'):
search = request.POST['search']
request.GET = request.GET.copy()
request.GET.update({'search': search})
elif request.method == 'GET':
if request.GET.has_key('search'):
search = request.GET['search']
if search:
rules = Rule.objects.filter(content__icontains=search)
if len(rules) > 0:
length += len(rules)
rules = RuleTable(rules)
tables.RequestConfig(request).configure(rules)
else:
rules = None
categories = Category.objects.filter(name__icontains=search)
if len(categories) > 0:
length += len(categories)
categories = CategoryTable(categories)
tables.RequestConfig(request).configure(categories)
else:
rules_width += 4
categories = None
rulesets = Ruleset.objects.filter(name__icontains=search)
if len(rulesets) > 0:
def _get_hits_order(self, request, order):
es_top_kwargs = {
'count': Rule.objects.count(),
'order': order
}
es_top_kwargs.update(es_hits_params(request))
try:
result = es_get_top_rules(request, **es_top_kwargs)
except ESError:
queryset = Rule.objects.order_by('sid')
queryset = queryset.annotate(hits=models.Value(0, output_field=models.IntegerField()))
queryset = queryset.annotate(hits=models.ExpressionWrapper(models.Value(0), output_field=models.IntegerField()))
return queryset.values_list('sid', 'hits')
result = map(lambda x: (x['key'], x['doc_count']), result)
return result
def get_id(self):
return 'prsr_' + self.id
# ---------------------------------------------------------------
#
# PageRuleResult
#
# ---------------------------------------------------------------
class PageRuleResult(RuleResult):
id = models.AutoField(primary_key=True)
rule = models.ForeignKey(Rule)
rule_required = models.BooleanField(default=False)
slug = models.SlugField(max_length=32, default="none", blank=True, editable=False)
ws_rule_result = models.ForeignKey(WebsiteRuleResult, related_name="page_rule_results", blank=True)
page_result = models.ForeignKey(PageResult, on_delete=models.CASCADE, related_name="page_rule_results")
page_rc_result = models.ForeignKey(PageRuleCategoryResult, related_name="page_rule_results")
page_gl_result = models.ForeignKey(PageGuidelineResult, related_name="page_rule_results")
page_rs_result = models.ForeignKey(PageRuleScopeResult, related_name="page_rule_results")
result_message = models.CharField("Rule Result Message", max_length=4096, default="none")
elements_passed = models.IntegerField(default=0)
elements_violation = models.IntegerField(default=0)
elements_warning = models.IntegerField(default=0)
else:
rule.rev = rev
if rule.category != self:
rule.category = self
rule.msg = msg
rules_update["updated"].append(rule)
rule.updated_date = creation_date
rule.parse_metadata()
rule.save()
rule.parse_flowbits(source, flowbits)
else:
rules_unchanged.append(rule)
else:
if rev == None:
rev = 0
rule = Rule(category = self, sid = sid,
rev = rev, content = line, msg = msg,
state_in_source = state, state = state, imported_date = creation_date, updated_date = creation_date)
rule.parse_metadata()
rules_update["added"].append(rule)
rule.parse_flowbits(source, flowbits, addition = True)
if len(duplicate_sids):
sids = sorted(duplicate_sids)
if len(sids) == 20:
sids += '...'
sids = ', '.join(sids)
source_name = ', '.join(sorted(duplicate_source))
raise ValidationError('The source contains conflicting SID (%s) with other sources (%s)' % (sids, source_name))
if len(rules_update["added"]):
rules = self.generate()
self.rules_count = len(rules)
file_content = "# Rules file for %s generated by Scirius at %s\n" % (self.name, unicode(timezone.now()))
if len(rules) > 0:
try:
Rule.enable_cache()
rules_content = []
for rule in rules:
c = rule.generate_content(self)
if c:
rules_content.append(c)
file_content += "\n".join(rules_content)
finally:
Rule.disable_cache()
return file_content
def generate(self):
# FIXME extract archive file for sources
# generate rule file
rules = self.ruleset.to_buffer()
# write to file
with open(self.output_directory + "/" + "scirius.rules", 'w') as rfile:
rfile.write(rules.encode('utf-8'))
# export files at version
self.ruleset.export_files(self.output_directory)
# FIXME gruick
with open(self.output_directory + "/" + "rules.json", 'w') as rfile:
for rule in Rule.objects.all():
dic = {'sid': rule.pk, 'created': unicode(rule.created), 'updated': unicode(rule.updated)}
rfile.write(json.dumps(dic) + '\n')
# Export IPrep
export_iprep_files(self.output_directory)