-
Notifications
You must be signed in to change notification settings - Fork 549
Expand file tree
/
Copy pathhtmllib.py
More file actions
3007 lines (2452 loc) · 113 KB
/
Copy pathhtmllib.py
File metadata and controls
3007 lines (2452 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# +------------------------------------------------------------------+
# | ____ _ _ __ __ _ __ |
# | / ___| |__ ___ ___| | __ | \/ | |/ / |
# | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / |
# | | |___| | | | __/ (__| < | | | | . \ |
# | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ |
# | |
# | Copyright Mathias Kettner 2014 mk@mathias-kettner.de |
# +------------------------------------------------------------------+
#
# This file is part of Check_MK.
# The official homepage is at http://mathias-kettner.de/check_mk.
#
# check_mk is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation in version 2. check_mk is distributed
# in the hope that it will be useful, but WITHOUT ANY WARRANTY; with-
# out even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more de-
# tails. You should have received a copy of the GNU General Public
# License along with GNU Make; see the file COPYING. If not, write
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
# TODO:
#
# Notes for future rewrite:
#
# - Find all call sites which do something like "int(html.request.var(...))"
# and replace it with html.get_integer_input(...)
#
# - Make clear which functions return values and which write out values
# render_*, add_*, write_* (e.g. icon() -> outputs directly,
# render_icon() -> returns icon
#
# - Order of arguments:
# e.g. icon(help, icon) -> change and make help otional?
#
# - Fix names of message() show_error() show_warning()
#
# - change naming of html.attrencode() to html.render()
#
# - General rules:
# 1. values of type str that are passed as arguments or
# return values or are stored in datastructures must not contain
# non-Ascii characters! UTF-8 encoding must just be used in
# the last few CPU cycles before outputting. Conversion from
# input to str or unicode must happen as early as possible,
# directly when reading from file or URL.
#
# - indentify internal helper methods and prefix them with "_"
#
# - Split HTML handling (page generating) code and generic request
# handling (vars, cookies, ...) up into separate classes to make
# the different tasks clearer. For HTMLGenerator() or similar.
import time
import os
import urllib
import ast
import random
import re
import signal
import json
import abc
import pprint
from contextlib import contextmanager
import six
try:
# First try python3
# suppress missing import error from mypy
from html import escape as html_escape # type: ignore
except ImportError:
# Default to python2
from cgi import escape as html_escape
# TODO: Cleanup this dirty hack. Import of htmllib must not magically modify the behaviour of
# the json module. Better would be to create a JSON wrapper in cmk.utils.json which uses a
# custom subclass of the JSONEncoder.
#
# Monkey patch in order to make the HTML class below json-serializable without changing the default json calls.
def _default(self, obj):
return getattr(obj.__class__, "to_json", _default.default)(obj)
# TODO: suppress mypy warnings for this monkey patch right now. See also:
# https://github.com/python/mypy/issues/2087
# Save unmodified default:
_default.default = json.JSONEncoder().default # type: ignore
# replacement:
json.JSONEncoder.default = _default # type: ignore
import cmk.utils.paths
from cmk.utils.exceptions import MKGeneralException
from cmk.gui.exceptions import MKUserError, RequestTimeout
import cmk.gui.utils as utils
import cmk.gui.config as config
import cmk.gui.log as log
from cmk.gui.i18n import _
#.
# .--Escaper-------------------------------------------------------------.
# | _____ |
# | | ____|___ ___ __ _ _ __ ___ _ __ |
# | | _| / __|/ __/ _` | '_ \ / _ \ '__| |
# | | |___\__ \ (_| (_| | |_) | __/ | |
# | |_____|___/\___\__,_| .__/ \___|_| |
# | |_| |
# +----------------------------------------------------------------------+
# | |
# '----------------------------------------------------------------------
class Escaper(object):
def __init__(self):
super(Escaper, self).__init__()
self._unescaper_text = re.compile(
r'<(/?)(h1|h2|b|tt|i|u|br(?: /)?|nobr(?: /)?|pre|a|sup|p|li|ul|ol)>')
self._quote = re.compile(r"(?:"|')")
self._a_href = re.compile(r'<a href=((?:"|').*?(?:"|'))>')
# Encode HTML attributes. Replace HTML syntax with HTML text.
# For example: replace '"' with '"', '<' with '<'.
# This code is slow. Works on str and unicode without changing
# the type. Also works on things that can be converted with '%s'.
def escape_attribute(self, value):
attr_type = type(value)
if value is None:
return ''
elif attr_type == int:
return str(value)
elif isinstance(value, HTML):
return "%s" % value # This is HTML code which must not be escaped
elif attr_type not in [str, unicode]: # also possible: type Exception!
value = "%s" % value # Note: this allows Unicode. value might not have type str now
return html_escape(value, quote=True)
def unescape_attributes(self, value):
# In python3 use html.unescape
return value.replace("&", "&")\
.replace(""", "\"")\
.replace("<", "<")\
.replace(">", ">")
# render HTML text.
# We only strip od some tags and allow some simple tags
# such as <h1>, <b> or <i> to be part of the string.
# This is useful for messages where we want to keep formatting
# options. (Formerly known as 'permissive_attrencode') """
# for the escaping functions
def escape_text(self, text):
if isinstance(text, HTML):
return "%s" % text # This is HTML code which must not be escaped
text = self.escape_attribute(text)
text = self._unescaper_text.sub(r'<\1\2>', text)
for a_href in self._a_href.finditer(text):
text = text.replace(a_href.group(0),
"<a href=%s>" % self._quote.sub("\"", a_href.group(1)))
return text.replace("&nbsp;", " ")
#.
# .--Encoding------------------------------------------------------------.
# | _____ _ _ |
# | | ____|_ __ ___ ___ __| (_)_ __ __ _ |
# | | _| | '_ \ / __/ _ \ / _` | | '_ \ / _` | |
# | | |___| | | | (_| (_) | (_| | | | | | (_| | |
# | |_____|_| |_|\___\___/ \__,_|_|_| |_|\__, | |
# | |___/ |
# +----------------------------------------------------------------------+
# | |
# '----------------------------------------------------------------------'
class Encoder(object):
def urlencode_vars(self, vars_):
"""Convert a mapping object or a sequence of two-element tuples to a “percent-encoded” string
This function returns a str object, never unicode!
Note: This should be changed once we change everything to
unicode internally.
"""
assert isinstance(vars_, list)
pairs = []
for varname, value in sorted(vars_):
assert isinstance(varname, (str, unicode))
if isinstance(value, int):
value = str(value)
elif isinstance(value, unicode):
value = value.encode("utf-8")
elif value is None:
# TODO: This is not ideal and should better be cleaned up somehow. Shouldn't
# variables with None values simply be skipped? We currently can not find the
# call sites easily. This may be cleaned up once we establish typing. Until then
# we need to be compatible with the previous behavior.
value = ""
#assert type(value) == str, "%s: %s" % (varname, value)
pairs.append((varname, value))
return urllib.urlencode(pairs)
def urlencode(self, value):
"""Replace special characters in string using the %xx escape.
This function returns a str object, never unicode!
Note: This should be changed once we change everything to
unicode internally.
"""
if isinstance(value, unicode):
value = value.encode("utf-8")
elif value is None:
return ""
assert isinstance(value, str)
return urllib.quote_plus(value)
#.
# .--HTML----------------------------------------------------------------.
# | _ _ _____ __ __ _ |
# | | | | |_ _| \/ | | |
# | | |_| | | | | |\/| | | |
# | | _ | | | | | | | |___ |
# | |_| |_| |_| |_| |_|_____| |
# | |
# +----------------------------------------------------------------------+
# | This is a simple class which wraps a unicode string provided by |
# | the caller to make html.attrencode() know that this string should |
# | not be escaped. |
# | |
# | This way we can implement encodings while still allowing HTML code. |
# | This is useful when one needs to print out HTML tables in messages |
# | or help texts. |
# | |
# | The HTML class is implemented as an immutable type. |
# | Every instance of the class is a unicode string. |
# | Only utf-8 compatible encodings are supported. |
# '----------------------------------------------------------------------'
class HTML(object):
def __init__(self, value=u''):
super(HTML, self).__init__()
self.value = self._ensure_unicode(value)
def __unicode__(self):
return self.value
def _ensure_unicode(self, thing, encoding_index=0):
try:
return unicode(thing)
except UnicodeDecodeError:
return thing.decode("utf-8")
def __bytebatzen__(self):
return self.value.encode("utf-8")
def __str__(self):
# Against the sense of the __str__() method, we need to return the value
# as unicode here. Why? There are many cases where something like
# "%s" % HTML(...) is done in the GUI code. This calls the __str__ function
# because the origin is a str() object. The call will then return a UTF-8
# encoded str() object. This brings a lot of compatbility issues to the code
# which can not be solved easily.
# To deal with this situation we need the implicit conversion from str to
# unicode that happens when we return a unicode value here. In all relevant
# cases this does exactly what we need. It would only fail if the origin
# string contained characters that can not be decoded with the ascii codec
# which is not relevant for us here.
#
# This is problematic:
# html.write("%s" % HTML("ä"))
#
# Bottom line: We should relly cleanup internal unicode/str handling.
return self.value
def __repr__(self):
return ("HTML(\"%s\")" % self.value).encode("utf-8")
def to_json(self):
return self.value
def __add__(self, other):
return HTML(self.value + self._ensure_unicode(other))
def __iadd__(self, other):
return self.__add__(other)
def __radd__(self, other):
return HTML(self._ensure_unicode(other) + self.value)
def join(self, iterable):
return HTML(self.value.join(map(self._ensure_unicode, iterable)))
def __eq__(self, other):
return self.value == self._ensure_unicode(other)
def __ne__(self, other):
return self.value != self._ensure_unicode(other)
def __len__(self):
return len(self.value)
def __getitem__(self, index):
return HTML(self.value[index])
def __contains__(self, item):
return self._ensure_unicode(item) in self.value
def count(self, sub, *args):
return self.value.count(self._ensure_unicode(sub), *args)
def index(self, sub, *args):
return self.value.index(self._ensure_unicode(sub), *args)
def lstrip(self, *args):
args = tuple(map(self._ensure_unicode, args[:1])) + args[1:]
return HTML(self.value.lstrip(*args))
def rstrip(self, *args):
args = tuple(map(self._ensure_unicode, args[:1])) + args[1:]
return HTML(self.value.rstrip(*args))
def strip(self, *args):
args = tuple(map(self._ensure_unicode, args[:1])) + args[1:]
return HTML(self.value.strip(*args))
def lower(self):
return HTML(self.value.lower())
def upper(self):
return HTML(self.value.upper())
def startswith(self, prefix, *args):
return self.value.startswith(self._ensure_unicode(prefix), *args)
#.
# .--OutputFunnel--------------------------------------------------------.
# | ___ _ _ _____ _ |
# | / _ \ _ _| |_ _ __ _ _| |_| ___| _ _ __ _ __ ___| | |
# | | | | | | | | __| '_ \| | | | __| |_ | | | | '_ \| '_ \ / _ \ | |
# | | |_| | |_| | |_| |_) | |_| | |_| _|| |_| | | | | | | | __/ | |
# | \___/ \__,_|\__| .__/ \__,_|\__|_| \__,_|_| |_|_| |_|\___|_| |
# | |_| |
# +----------------------------------------------------------------------+
# | Provides the write functionality. The method _lowlevel_write needs |
# | to be overwritten in the specific subclass! |
# | |
# | Usage of plugged context: |
# | with html.plugged(): |
# | html.write("something") |
# | html_code = html.drain() |
# | print html_code |
# '----------------------------------------------------------------------'
class OutputFunnel(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
super(OutputFunnel, self).__init__()
self.plug_text = []
# Accepts str and unicode objects only!
# The plugged functionality can be used for debugging.
def write(self, text):
if not text:
return
if isinstance(text, HTML):
text = "%s" % text
if not isinstance(text, six.string_types): # also possible: type Exception!
raise MKGeneralException(
_('Type Error: html.write accepts str and unicode input objects only!'))
if self._is_plugged():
self.plug_text[-1].append(text)
else:
# encode when really writing out the data. Not when writing plugged,
# because the plugged code will be handled somehow by our code. We
# only encode when leaving the pythonic world.
if isinstance(text, unicode):
text = text.encode("utf-8")
self._lowlevel_write(text)
@abc.abstractmethod
def _lowlevel_write(self, text):
raise NotImplementedError()
@contextmanager
def plugged(self):
self.plug_text.append([])
try:
yield
finally:
text = self.drain()
self.plug_text.pop()
self.write(text)
def _is_plugged(self):
return bool(self.plug_text)
# Get the sink content in order to do something with it.
def drain(self):
if not self._is_plugged(): # TODO: Raise exception or even remove "if"?
return ''
text = "".join(self.plug_text.pop())
self.plug_text.append([])
return text
#.
# .--HTML Generator------------------------------------------------------.
# | _ _ _____ __ __ _ |
# | | | | |_ _| \/ | | |
# | | |_| | | | | |\/| | | |
# | | _ | | | | | | | |___ |
# | |_| |_| |_| |_| |_|_____| |
# | |
# | ____ _ |
# | / ___| ___ _ __ ___ _ __ __ _| |_ ___ _ __ |
# | | | _ / _ \ '_ \ / _ \ '__/ _` | __/ _ \| '__| |
# | | |_| | __/ | | | __/ | | (_| | || (_) | | |
# | \____|\___|_| |_|\___|_| \__,_|\__\___/|_| |
# | |
# +----------------------------------------------------------------------+
# | Generator which provides top level HTML writing functionality. |
# '----------------------------------------------------------------------'
class HTMLGenerator(OutputFunnel):
""" Usage Notes:
- Tags can be opened using the open_[tag]() call where [tag] is one of the possible tag names.
All attributes can be passed as function arguments, such as open_div(class_="example").
However, python specific key words need to be escaped using a trailing underscore.
One can also provide a dictionary as attributes: open_div(**{"class": "example"}).
- All tags can be closed again using the close_[tag]() syntax.
- For tags which shall only contain plain text (i.e. no tags other than highlighting tags)
you can a the direct call using the tag name only as function name,
self.div("Text content", **attrs). Tags featuring this functionality are listed in
the "featured shortcuts" list.
- Some tags require mandatory arguments. Those are defined explicitly below.
For example an a tag needs the href attribute everytime.
- If you want to provide plain HTML to a tag, please use the tag_content function or
facillitate the HTML class.
HOWTO HTML Attributes:
- Python specific attributes have to be escaped using a trailing underscore
- All attributes can be python objects. However, some attributes can also be lists of attrs:
'class' attributes will be concatenated using one whitespace
'style' attributes will be concatenated using the semicolon and one whitespace
Behaviorial attributes such as 'onclick', 'onmouseover' will bec concatenated using
a semicolon and one whitespace.
- All attributes will be escaped, i.e. the characters '&', '<', '>', '"' will be replaced by
non HtML relevant signs '&', '<', '>' and '"'. """
# TODO: Replace u, i, b with underline, italic, bold, usw.
# these tags can be called by their tag names, e.g. 'self.title(content)'
_shortcut_tags = set(["title", "h1", "h2", "h3", "h4", "th", "tr", "td", "center", "pre", "style", "iframe",\
"div", "p", "span", "canvas", "strong", "sub", "tt", "u", "i", "b", "x", "option"])
# these tags can be called by open_name(), close_name() and render_name(), e.g. 'self.open_html()'
_tag_names = set([
'html', 'head', 'body', 'header', 'footer', 'a', 'b', 'sup', 'script', 'form', 'button',
'p', 'select', 'fieldset', 'table', 'tbody', 'thead', 'row', 'ul', 'li', 'br', 'nobr',
'input', 'span', 'tags', 'tag'
])
# Of course all shortcut tags can be used as well.
_tag_names.update(_shortcut_tags)
def __init__(self):
super(HTMLGenerator, self).__init__()
self.escaper = Escaper()
#
# Rendering
#
def _render_attributes(self, **attrs):
# make class attribute foolproof
css = []
for k in ["class_", "css", "cssclass", "class"]:
if k in attrs:
if isinstance(attrs[k], list):
css.extend(attrs.pop(k))
elif attrs[k] is not None:
css.append(attrs.pop(k))
if css:
attrs["class"] = css
# options such as 'selected' and 'checked' dont have a value in html tags
options = []
# Links require href to be first attribute
href = attrs.pop('href', None)
if href:
attributes = [("href", href)]
else:
attributes = []
attributes += attrs.iteritems()
# render all attributes
for k, v in attributes:
if v is None:
continue
k = self.escaper.escape_attribute(k.rstrip('_'))
if v == '':
options.append(k)
continue
if not isinstance(v, list):
v = self.escaper.escape_attribute(v)
else:
if k == "class":
sep = ' '
elif k == "style" or k.startswith('on'):
sep = '; '
else:
sep = '_'
v = sep.join([a for a in (self.escaper.escape_attribute(vi) for vi in v) if a])
if sep.startswith(';'):
v = re.sub(';+', ';', v)
yield ' %s=\"%s\"' % (k, v)
for k in options:
yield " %s=\'\'" % k
# applies attribute encoding to prevent code injections.
def _render_opening_tag(self, tag_name, close_tag=False, **attrs):
""" You have to replace attributes which are also python elements such as
'class', 'id', 'for' or 'type' using a trailing underscore (e.g. 'class_' or 'id_'). """
return HTML("<%s%s%s>" %
(tag_name, '' if not attrs else ''.join(self._render_attributes(**attrs)),
'' if not close_tag else ' /'))
def _render_closing_tag(self, tag_name):
return HTML("</%s>" % (tag_name))
def _render_content_tag(self, tag_name, tag_content, **attrs):
open_tag = self._render_opening_tag(tag_name, **attrs)
if not tag_content:
tag_content = ""
elif not isinstance(tag_content, HTML):
tag_content = self.escaper.escape_text(tag_content)
return HTML("%s%s</%s>" % (open_tag, tag_content, tag_name))
# This is used to create all the render_tag() and close_tag() functions
def __getattr__(self, name):
""" All closing tags can be called like this:
self.close_html(), self.close_tr(), etc. """
parts = name.split('_')
# generating the shortcut tag calls
if len(parts) == 1 and name in self._shortcut_tags:
return lambda content, **attrs: self.write_html(
self._render_content_tag(name, content, **attrs))
# generating the open, close and render calls
elif len(parts) == 2:
what, tag_name = parts[0], parts[1]
if what == "open" and tag_name in self._tag_names:
return lambda **attrs: self.write_html(self._render_opening_tag(tag_name, **attrs))
elif what == "close" and tag_name in self._tag_names:
return lambda: self.write_html(self._render_closing_tag(tag_name))
elif what == "render" and tag_name in self._tag_names:
return lambda content, **attrs: HTML(
self._render_content_tag(tag_name, content, **attrs))
else:
# FIXME: This returns None, which is not a very informative error message
return object.__getattribute__(self, name)
#
# HTML element methods
# If an argument is mandatory, it is used as default and it will overwrite an
# implicit argument (e.g. id_ will overwrite attrs["id"]).
#
#
# basic elements
#
def render_text(self, text):
return HTML(self.escaper.escape_text(text))
def write_text(self, text):
""" Write text. Highlighting tags such as h2|b|tt|i|br|pre|a|sup|p|li|ul|ol are not escaped. """
self.write(self.render_text(text))
def write_html(self, content):
""" Write HTML code directly, without escaping. """
self.write(content)
def comment(self, comment_text):
self.write("<!--%s-->" % self.encode_attribute(comment_text))
def meta(self, httpequiv=None, **attrs):
if httpequiv:
attrs['http-equiv'] = httpequiv
self.write_html(self._render_opening_tag('meta', close_tag=True, **attrs))
def base(self, target):
self.write_html(self._render_opening_tag('base', close_tag=True, target=target))
def open_a(self, href, **attrs):
attrs['href'] = href
self.write_html(self._render_opening_tag('a', **attrs))
def render_a(self, content, href, **attrs):
attrs['href'] = href
return self._render_content_tag('a', content, **attrs)
def a(self, content, href, **attrs):
self.write_html(self.render_a(content, href, **attrs))
def stylesheet(self, href):
self.write_html(
self._render_opening_tag('link',
rel="stylesheet",
type_="text/css",
href=href,
close_tag=True))
#
# Scriptingi
#
def render_javascript(self, code):
return HTML("<script type=\"text/javascript\">\n%s\n</script>\n" % code)
def javascript(self, code):
self.write_html(self.render_javascript(code))
def javascript_file(self, src):
""" <script type="text/javascript" src="%(name)"/>\n """
self.write_html(self._render_content_tag('script', '', type_="text/javascript", src=src))
def render_img(self, src, **attrs):
attrs['src'] = src
return self._render_opening_tag('img', close_tag=True, **attrs)
def img(self, src, **attrs):
self.write_html(self.render_img(src, **attrs))
def open_button(self, type_, **attrs):
attrs['type'] = type_
self.write_html(self._render_opening_tag('button', close_tag=True, **attrs))
def play_sound(self, url):
self.write_html(self._render_opening_tag('audio autoplay', src_=url))
#
# form elements
#
def render_label(self, content, for_, **attrs):
attrs['for'] = for_
return self._render_content_tag('label', content, **attrs)
def label(self, content, for_, **attrs):
self.write_html(self.render_label(content, for_, **attrs))
def render_input(self, name, type_, **attrs):
attrs['type_'] = type_
attrs['name'] = name
return self._render_opening_tag('input', close_tag=True, **attrs)
def input(self, name, type_, **attrs):
self.write_html(self.render_input(name, type_, **attrs))
#
# table and list elements
#
def td(self, content, **attrs):
""" Only for text content. You can't put HTML structure here. """
self.write_html(self._render_content_tag('td', content, **attrs))
def li(self, content, **attrs):
""" Only for text content. You can't put HTML structure here. """
self.write_html(self._render_content_tag('li', content, **attrs))
#
# structural text elements
#
def render_heading(self, content):
""" <h2>%(content)</h2> """
return self._render_content_tag('h2', content)
def heading(self, content):
self.write_html(self.render_heading(content))
def render_br(self):
return HTML("<br/>")
def br(self):
self.write_html(self.render_br())
def render_hr(self, **attrs):
return self._render_opening_tag('hr', close_tag=True, **attrs)
def hr(self, **attrs):
self.write_html(self.render_hr(**attrs))
def rule(self):
return self.hr()
def render_nbsp(self):
return HTML(" ")
def nbsp(self):
self.write_html(self.render_nbsp())
#.
# .--TimeoutMgr.---------------------------------------------------------.
# | _____ _ _ __ __ |
# | |_ _(_)_ __ ___ ___ ___ _ _| |_| \/ | __ _ _ __ |
# | | | | | '_ ` _ \ / _ \/ _ \| | | | __| |\/| |/ _` | '__| |
# | | | | | | | | | | __/ (_) | |_| | |_| | | | (_| | | _ |
# | |_| |_|_| |_| |_|\___|\___/ \__,_|\__|_| |_|\__, |_|(_) |
# | |___/ |
# '----------------------------------------------------------------------'
class TimeoutManager(object):
"""Request timeout handling
The system apache process will end the communication with the client after
the timeout configured for the proxy connection from system apache to site
apache. This is done in /omd/sites/[site]/etc/apache/proxy-port.conf file
in the "timeout=x" parameter of the ProxyPass statement.
The regular request timeout configured here should always be lower to make
it possible to abort the page processing and send a helpful answer to the
client.
It is possible to disable the applications request timeout (temoporarily)
or totally for specific calls, but the timeout to the client will always
be applied by the system webserver. So the client will always get a error
page while the site apache continues processing the request (until the
first try to write anything to the client) which will result in an
exception.
"""
def enable_timeout(self, duration):
def handle_request_timeout(signum, frame):
raise RequestTimeout(
_("Your request timed out after %d seconds. This issue may be "
"related to a local configuration problem or a request which works "
"with a too large number of objects. But if you think this "
"issue is a bug, please send a crash report.") % duration)
signal.signal(signal.SIGALRM, handle_request_timeout)
signal.alarm(duration)
def disable_timeout(self):
signal.alarm(0)
#.
# .--Transactions--------------------------------------------------------.
# | _____ _ _ |
# | |_ _| __ __ _ _ __ ___ __ _ ___| |_(_) ___ _ __ ___ |
# | | || '__/ _` | '_ \/ __|/ _` |/ __| __| |/ _ \| '_ \/ __| |
# | | || | | (_| | | | \__ \ (_| | (__| |_| | (_) | | | \__ \ |
# | |_||_| \__,_|_| |_|___/\__,_|\___|\__|_|\___/|_| |_|___/ |
# | |
# '----------------------------------------------------------------------'
class TransactionManager(object):
"""Manages the handling of transaction IDs used by the GUI to prevent against
performing the same action multiple times."""
def __init__(self, request):
super(TransactionManager, self).__init__()
self._request = request
self._new_transids = []
self._ignore_transids = False
self._current_transid = None
def ignore(self):
"""Makes the GUI skip all transaction validation steps"""
self._ignore_transids = True
def get(self):
"""Returns a transaction ID that can be used during a subsequent action"""
if not self._current_transid:
self._current_transid = self.fresh_transid()
return self._current_transid
def fresh_transid(self):
"""Compute a (hopefully) unique transaction id.
This is generated during rendering of a form or an action link, stored
in a user specific file for later validation, sent to the users browser
via HTML code, then submitted by the user together with the action
(link / form) and then validated if it is a known transid. When it is a
known transid, it will be used and invalidated. If the id is not known,
the action will not be processed."""
transid = "%d/%d" % (int(time.time()), random.getrandbits(32))
self._new_transids.append(transid)
return transid
def store_new(self):
"""All generated transids are saved per user.
They are stored in the transids.mk. Per user only up to 20 transids of
the already existing ones are kept. The transids generated on the
current page are all kept. IDs older than one day are deleted."""
if not self._new_transids:
return
valid_ids = self._load_transids(lock=True)
cleared_ids = []
now = time.time()
for valid_id in valid_ids:
timestamp = valid_id.split("/")[0]
if now - int(timestamp) < 86400: # one day
cleared_ids.append(valid_id)
self._save_transids((cleared_ids[-20:] + self._new_transids))
def transaction_valid(self):
"""Checks if the current transaction is valid
i.e. in case of browser reload a browser reload, the form submit should
not be handled a second time.. The HTML variable _transid must be
present.
In case of automation users (authed by _secret in URL): If it is empty
or -1, then it's always valid (this is used for webservice calls).
This was also possible for normal users, but has been removed to preven
security related issues."""
if not self._request.has_var("_transid"):
return False
transid = self._request.var("_transid")
if self._ignore_transids and (not transid or transid == '-1'):
return True # automation
if '/' not in transid:
return False
# Normal user/password auth user handling
timestamp = transid.split("/", 1)[0]
# If age is too old (one week), it is always
# invalid:
now = time.time()
if now - int(timestamp) >= 604800: # 7 * 24 hours
return False
# Now check, if this transid is a valid one
return transid in self._load_transids()
def is_transaction(self):
"""Checks, if the current page is a transation, i.e. something that is secured by
a transid (such as a submitted form)"""
return self._request.has_var("_transid")
def check_transaction(self):
"""called by page functions in order to check, if this was a reload or the original form submission.
Increases the transid of the user, if the latter was the case.
There are three return codes:
True: -> positive confirmation by the user
False: -> not yet confirmed, question is being shown
None: -> a browser reload or a negative confirmation
"""
if self.transaction_valid():
transid = self._request.var("_transid")
if transid and transid != "-1":
self._invalidate(transid)
return True
else:
return False
def _invalidate(self, used_id):
"""Remove the used transid from the list of valid ones"""
valid_ids = self._load_transids(lock=True)
try:
valid_ids.remove(used_id)
except ValueError:
return
self._save_transids(valid_ids)
def _load_transids(self, lock=False):
return config.user.load_file("transids", [], lock)
def _save_transids(self, used_ids):
if config.user.id:
config.user.save_file("transids", used_ids)
#.
# .--html----------------------------------------------------------------.
# | _ _ _ |
# | | |__ | |_ _ __ ___ | | |
# | | '_ \| __| '_ ` _ \| | |
# | | | | | |_| | | | | | | |
# | |_| |_|\__|_| |_| |_|_| |
# | |
# +----------------------------------------------------------------------+
# | Caution! The class needs to be derived from Outputfunnel first! |
# '----------------------------------------------------------------------'
class html(HTMLGenerator):
def __init__(self, request, response):
super(html, self).__init__()
self._logger = log.logger.getChild("html")
# rendering state
self._header_sent = False
self._context_buttons_open = False
# style options
self._body_classes = ['main']
self._default_javascripts = ["main"]
# behaviour options
self.render_headfoot = True
self.enable_debug = False
self.screenshotmode = False
self.have_help = False
self.help_visible = False
# browser options
self.output_format = "html"
self.browser_reload = 0
self.browser_redirect = ''
self.link_target = None
self.myfile = None
# Browser options
self._user_id = None
self.user_errors = {}
self.focus_object = None
self.events = set([]) # currently used only for sounds
self.status_icons = {}
self.final_javascript_code = ""
self.treestates = None
self.page_context = {}
# Settings
self.mobile = False
self._theme = "facelift"
# Forms
self.form_name = None
self.form_vars = []
# Time measurement
self.times = {}
self.start_time = time.time()
self.last_measurement = self.start_time
# Register helpers