This repository has been archived by the owner on Aug 26, 2022. It is now read-only.
/
models.py
2057 lines (1737 loc) · 82.5 KB
/
models.py
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
import logging
from collections import namedtuple
from datetime import datetime, timedelta
from itertools import chain
from urlparse import urlparse
import hashlib
import re
import time
import json
from pyquery import PyQuery
from tower import ugettext_lazy as _lazy, ugettext as _
import bleach
import jingo
from django.conf import settings
from django.contrib.auth.models import User
from django.core import serializers
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.core.urlresolvers import resolve
from django.db import models, transaction
from django.http import Http404
from django.utils.html import strip_tags
from south.modelsinspector import add_introspection_rules
import constance.config
from elasticutils.contrib.django import Indexable
from tidings.models import NotificationsMixin
from search.index import SearchMappingType, register_mapping_type
from search.tasks import register_live_index
from sumo import ProgrammingError
from sumo_locales import LOCALES
from sumo.models import ManagerBase, ModelBase, LocaleField
from sumo.urlresolvers import reverse, split_path
from taggit.models import ItemBase, TagBase
from taggit.managers import TaggableManager
from taggit.utils import parse_tags, edit_string_for_tags
import waffle
from wiki import TEMPLATE_TITLE_PREFIX
import wiki.content
from . import kumascript
ALLOWED_TAGS = bleach.ALLOWED_TAGS + [
'div', 'span', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'pre', 'code', 'cite',
'dl', 'dt', 'dd', 'small', 'sub', 'sup', 'u', 'strike', 'samp',
'ul', 'ol', 'li',
'nobr', 'dfn', 'caption', 'var', 's',
'img', 'hr',
'input', 'label', 'select', 'option', 'textarea',
# Note: <iframe> is allowed, but src="" is pre-filtered before bleach
'iframe',
'table', 'tbody', 'thead', 'tfoot', 'tr', 'th', 'td', 'colgroup', 'col',
'section', 'header', 'footer', 'nav', 'article', 'aside', 'figure',
'figcaption',
'dialog', 'hgroup', 'mark', 'time', 'meter', 'command', 'output',
'progress', 'audio', 'video', 'details', 'datagrid', 'datalist', 'table',
'address', 'font',
'bdi', 'bdo', 'del', 'ins', 'kbd', 'samp', 'var',
'ruby', 'rp', 'rt', 'q',
# MathML
'math', 'maction', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph',
'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded',
'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle',
'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
'munderover', 'none', 'mprescripts',
]
ALLOWED_ATTRIBUTES = bleach.ALLOWED_ATTRIBUTES
# Note: <iframe> is allowed, but src="" is pre-filtered before bleach
ALLOWED_ATTRIBUTES['iframe'] = ['id', 'src', 'sandbox', 'seamless',
'frameborder', 'width', 'height']
ALLOWED_ATTRIBUTES['p'] = ['style', 'class', 'id', 'align', 'lang', 'dir']
ALLOWED_ATTRIBUTES['span'] = ['style', 'class', 'id', 'title', 'lang', 'dir']
ALLOWED_ATTRIBUTES['img'] = ['src', 'id', 'align', 'alt', 'class', 'is',
'title', 'style', 'lang', 'dir', 'width',
'height']
ALLOWED_ATTRIBUTES['a'] = ['style', 'id', 'class', 'href', 'title',
'lang', 'name', 'dir', 'hreflang', 'rel']
ALLOWED_ATTRIBUTES['td'] = ['style', 'id', 'class', 'colspan', 'rowspan',
'lang', 'dir']
ALLOWED_ATTRIBUTES['th'] = ['style', 'id', 'class', 'colspan', 'rowspan',
'scope', 'lang', 'dir']
ALLOWED_ATTRIBUTES['video'] = ['style', 'id', 'class', 'lang', 'src',
'controls', 'dir']
ALLOWED_ATTRIBUTES['font'] = ['color', 'face', 'size', 'dir']
ALLOWED_ATTRIBUTES['select'] = ['name', 'dir']
ALLOWED_ATTRIBUTES['option'] = ['value', 'selected', 'dir']
ALLOWED_ATTRIBUTES['ol'] = ['style', 'class', 'id', 'lang', 'start', 'dir']
ALLOWED_ATTRIBUTES.update(dict((x, ['style', 'class', 'id', 'name', 'lang',
'dir'])
for x in
('h1', 'h2', 'h3', 'h4', 'h5', 'h6')))
ALLOWED_ATTRIBUTES.update(dict((x, ['style', 'class', 'id', 'lang', 'dir', 'title'])
for x in (
'div', 'pre', 'ul', 'li', 'code', 'dl', 'dt', 'dd',
'section', 'header', 'footer', 'nav', 'article', 'aside', 'figure',
'dialog', 'hgroup', 'mark', 'time', 'meter', 'command', 'output',
'progress', 'audio', 'details', 'datagrid', 'datalist', 'table',
'tr', 'address', 'col', 's', 'strong'
)))
ALLOWED_ATTRIBUTES.update(dict((x, ['cite']) for x in (
'blockquote', 'del', 'ins', 'q'
)))
ALLOWED_ATTRIBUTES['time'] += ['datetime']
ALLOWED_ATTRIBUTES['ins'] = ['datetime']
ALLOWED_ATTRIBUTES['del'] = ['datetime']
# MathML
ALLOWED_ATTRIBUTES.update(dict((x, ['href', 'mathbackground', 'mathcolor',
'id', 'class', 'style']) for x in (
'math', 'maction', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph',
'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded',
'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle',
'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder',
'munderover', 'none', 'mprescripts')))
ALLOWED_ATTRIBUTES['math'] += ['display', 'dir', 'selection', 'notation',
'close', 'open', 'separators', 'bevelled', 'denomalign', 'linethickness',
'numalign', 'largeop', 'maxsize', 'minsize', 'movablelimits', 'rspace',
'separator', 'stretchy', 'symmetric', 'depth', 'lquote', 'rquote', 'align',
'columnlines', 'frame', 'rowalign', 'rowspacing', 'rowspan', 'columnspan',
'accent', 'accentunder', 'dir', 'mathsize', 'mathvariant',
'subscriptshift', 'supscriptshift', 'scriptlevel', 'displaystyle',
'scriptsizemultiplier', 'scriptminsize']
ALLOWED_ATTRIBUTES['maction'] += ['actiontype', 'selection']
ALLOWED_ATTRIBUTES['menclose'] += ['notation']
ALLOWED_ATTRIBUTES['mfenced'] += ['close', 'open', 'separators']
ALLOWED_ATTRIBUTES['mfrac'] += ['bevelled', 'denomalign', 'linethickness',
'numalign']
ALLOWED_ATTRIBUTES['mi'] += ['dir', 'mathsize', 'mathvariant']
ALLOWED_ATTRIBUTES['mi'] += ['mathsize', 'mathvariant']
ALLOWED_ATTRIBUTES['mmultiscripts'] += ['subscriptshift', 'superscriptshift']
ALLOWED_ATTRIBUTES['mo'] += ['largeop', 'lspace', 'maxsize', 'minsize',
'movablelimits', 'rspace', 'separator', 'stretchy', 'symmetric', 'accent',
'dir', 'mathsize', 'mathvariant']
ALLOWED_ATTRIBUTES['mover'] += ['accent']
ALLOWED_ATTRIBUTES['mpadded'] += ['lspace', 'voffset', 'depth']
ALLOWED_ATTRIBUTES['mrow'] += ['dir']
ALLOWED_ATTRIBUTES['ms'] += ['lquote', 'rquote', 'dir', 'mathsize',
'mathvariant']
ALLOWED_ATTRIBUTES['mspace'] += ['depth', 'height', 'width']
ALLOWED_ATTRIBUTES['mstyle'] += ['display', 'dir', 'selection', 'notation',
'close', 'open', 'separators', 'bevelled', 'denomalign', 'linethickness',
'numalign', 'largeop', 'maxsize', 'minsize', 'movablelimits', 'rspace',
'separator', 'stretchy', 'symmetric', 'depth', 'lquote', 'rquote', 'align',
'columnlines', 'frame', 'rowalign', 'rowspacing', 'rowspan', 'columnspan',
'accent', 'accentunder', 'dir', 'mathsize', 'mathvariant',
'subscriptshift', 'supscriptshift', 'scriptlevel', 'displaystyle',
'scriptsizemultiplier',
'scriptminsize']
ALLOWED_ATTRIBUTES['msub'] += ['subscriptshift']
ALLOWED_ATTRIBUTES['msubsup'] += ['subscriptshift', 'superscriptshift']
ALLOWED_ATTRIBUTES['msup'] += ['superscriptshift']
ALLOWED_ATTRIBUTES['mtable'] += ['align', 'columnalign', 'columnlines',
'frame', 'rowalign', 'rowspacing', 'rowlines']
ALLOWED_ATTRIBUTES['mtd'] += ['columnalign', 'columnspan', 'rowalign',
'rowspan']
ALLOWED_ATTRIBUTES['mtext'] += ['dir', 'mathsize', 'mathvariant']
ALLOWED_ATTRIBUTES['mtr'] += ['columnalign', 'rowalign']
ALLOWED_ATTRIBUTES['munder'] += ['accentunder']
ALLOWED_ATTRIBUTES['mundermover'] = ['accent', 'accentunder']
# CSS
ALLOWED_STYLES = [
'border', 'border-top', 'border-right', 'border-bottom', 'border-left',
'float', 'overflow', 'min-height', 'vertical-align',
'white-space', 'color', 'border-radius', '-webkit-border-radius',
'-moz-border-radius, -o-border-radius',
'margin', 'margin-left', 'margin-top', 'margin-bottom', 'margin-right',
'padding', 'padding-left', 'padding-top', 'padding-bottom',
'padding-right', 'position', 'top', 'height', 'left', 'right',
'background', # TODO: Maybe not this one, it can load URLs
'background-color',
'font', 'font-size', 'font-weight', 'font-family', 'font-variant',
'text-align', 'text-transform',
'-moz-column-width', '-webkit-columns', 'columns', 'width',
'list-style-type', 'line-height',
# CSS properties needed for live examples (pending proper solution):
'backface-visibility', '-moz-backface-visibility',
'-webkit-backface-visibility', '-o-backface-visibility', 'perspective',
'-moz-perspective', '-webkit-perspective', '-o-perspective',
'perspective-origin', '-moz-perspective-origin',
'-webkit-perspective-origin', '-o-perspective-origin', 'transform',
'-moz-transform', '-webkit-transform', '-o-transform', 'transform-style',
'-moz-transform-style', '-webkit-transform-style', '-o-transform-style',
'columns', '-moz-columns', '-webkit-columns', 'column-rule',
'-moz-column-rule', '-webkit-column-rule', 'column-width',
'-moz-column-width', '-webkit-column-width', 'image-rendering',
'-ms-interpolation-mode', 'position', 'border-style', 'background-clip',
'border-bottom-right-radius', 'border-bottom-left-radius',
'border-top-right-radius', 'border-top-left-radius', 'border-bottom-style',
'border-left-style', 'border-right-style', 'border-top-style',
'border-bottom-width', 'border-left-width', 'border-right-width',
'border-top-width', 'vertical-align', 'border-collapse', 'border-width',
'border-color', 'border-left', 'border-right', 'border-bottom',
'border-top', 'clip', 'cursor', 'filter', 'float', 'max-width',
'font-style', 'letter-spacing', 'opacity', 'zoom', 'text-overflow',
'text-indent', 'text-rendering', 'text-shadow', 'transition', 'transition',
'transition', 'transition', 'transition-delay', '-moz-transition-delay',
'-webkit-transition-delay', '-o-transition-delay', 'transition-duration',
'-moz-transition-duration', '-webkit-transition-duration',
'-o-transition-duration', 'transition-property',
'-moz-transition-property', '-webkit-transition-property',
'-o-transition-property', 'transition-timing-function',
'-moz-transition-timing-function', '-webkit-transition-timing-function',
'-o-transition-timing-function', 'color', 'display', 'position',
'outline-color', 'outline', 'outline-offset', 'box-shadow',
'-moz-box-shadow', '-webkit-box-shadow', '-o-box-shadow',
'linear-gradient', '-moz-linear-gradient', '-webkit-linear-gradient',
'radial-gradient', '-moz-radial-gradient', '-webkit-radial-gradient',
'text-decoration-style', '-moz-text-decoration-style', 'text-decoration',
'direction', 'white-space', 'unicode-bidi', 'word-wrap'
]
# Disruptiveness of edits to translated versions. Numerical magnitude indicate
# the relative severity.
TYPO_SIGNIFICANCE = 10
MEDIUM_SIGNIFICANCE = 20
MAJOR_SIGNIFICANCE = 30
SIGNIFICANCES = (
(TYPO_SIGNIFICANCE,
_lazy(u'Minor details like punctuation and spelling errors')),
(MEDIUM_SIGNIFICANCE,
_lazy(u"Content changes that don't require immediate translation")),
(MAJOR_SIGNIFICANCE,
_lazy(u'Major content changes that will make older translations '
'inaccurate')),
)
CATEGORIES = (
(00, _lazy(u'Uncategorized')),
(10, _lazy(u'Reference')),
)
# Depth of table-of-contents in document display.
TOC_DEPTH_NONE = 0
TOC_DEPTH_ALL = 1
TOC_DEPTH_H2 = 2
TOC_DEPTH_H3 = 3
TOC_DEPTH_H4 = 4
TOC_DEPTH_CHOICES = (
(TOC_DEPTH_NONE, _lazy(u'No table of contents')),
(TOC_DEPTH_ALL, _lazy(u'All levels')),
(TOC_DEPTH_H2, _lazy(u'H2 and higher')),
(TOC_DEPTH_H3, _lazy(u'H3 and higher')),
(TOC_DEPTH_H4, _lazy('H4 and higher')),
)
# FF versions used to filter article searches, power {for} tags, etc.:
#
# Iterables of (ID, name, abbreviation for {for} tags, max version this version
# group encompasses) grouped into optgroups. To add the ability to sniff a new
# version of an existing browser (assuming it doesn't change the user agent
# string too radically), you should need only to add a line here; no JS
# required. Just be wary of inexact floating point comparisons when setting
# max_version, which should be read as "From the next smaller max_version up to
# but not including version x.y".
VersionMetadata = namedtuple('VersionMetadata',
'id, name, long, slug, max_version, show_in_ui')
GROUPED_FIREFOX_VERSIONS = (
((_lazy(u'Desktop:'), 'desktop'), (
# The first option is the default for {for} display. This should be the
# newest version.
VersionMetadata(2, _lazy(u'Firefox 3.5-3.6'),
_lazy(u'Firefox 3.5-3.6'), 'fx35', 3.9999, True),
VersionMetadata(1, _lazy(u'Firefox 4'),
_lazy(u'Firefox 4'), 'fx4', 4.9999, True),
VersionMetadata(3, _lazy(u'Firefox 3.0'),
_lazy(u'Firefox 3.0'), 'fx3', 3.4999, False))),
((_lazy(u'Mobile:'), 'mobile'), (
VersionMetadata(4, _lazy(u'Firefox 4'),
_lazy(u'Firefox 4 for Mobile'), 'm4', 4.9999, True),)))
# Flattened: # TODO: perhaps use optgroups everywhere instead
FIREFOX_VERSIONS = tuple(chain(*[options for label, options in
GROUPED_FIREFOX_VERSIONS]))
# OSes used to filter articles and declare {for} sections:
OsMetaData = namedtuple('OsMetaData', 'id, name, slug')
GROUPED_OPERATING_SYSTEMS = (
((_lazy(u'Desktop OS:'), 'desktop'), (
OsMetaData(1, _lazy(u'Windows'), 'win'),
OsMetaData(2, _lazy(u'Mac OS X'), 'mac'),
OsMetaData(3, _lazy(u'Linux'), 'linux'))),
((_lazy(u'Mobile OS:'), 'mobile'), (
OsMetaData(5, _lazy(u'Android'), 'android'),
OsMetaData(4, _lazy(u'Maemo'), 'maemo'))))
# Flattened
OPERATING_SYSTEMS = tuple(chain(*[options for label, options in
GROUPED_OPERATING_SYSTEMS]))
# how a redirect looks as rendered HTML
REDIRECT_HTML = 'REDIRECT <a class="redirect"'
REDIRECT_CONTENT = 'REDIRECT <a class="redirect" href="%(href)s">%(title)s</a>'
REDIRECT_TITLE = _lazy(u'%(old)s Redirect %(number)i')
REDIRECT_SLUG = _lazy(u'%(old)s-redirect-%(number)i')
# TODO: Put this under the control of Constance / Waffle?
# Flags used to signify revisions in need of review
REVIEW_FLAG_TAGS = (
('technical', _('Technical - code samples, APIs, or technologies')),
('editorial', _('Editorial - prose, grammar, or content')),
('template', _('Template - KumaScript code')),
)
REVIEW_FLAG_TAGS_DEFAULT = ['technical', 'editorial']
# TODO: This is info derived from urls.py, but unsure how to DRY it
RESERVED_SLUGS = (
'ckeditor_config.js$',
'watch-ready-for-review$',
'unwatch-ready-for-review$',
'watch-approved$',
'unwatch-approved$',
'.json$',
'new$',
'all$',
'templates$',
'preview-wiki-content$',
'category/\d+$',
'needs-review/?[^/]+$',
'needs-review/?',
'feeds/[^/]+/all/?',
'feeds/[^/]+/needs-review/[^/]+$',
'feeds/[^/]+/needs-review/?',
'tag/[^/]+'
)
DOCUMENT_LAST_MODIFIED_CACHE_KEY_TMPL = u'kuma:document-last-modified:%s'
DEKI_FILE_URL = re.compile(r'@api/deki/files/(?P<file_id>\d+)/=')
KUMA_FILE_URL = re.compile(r'/files/(?P<file_id>\d+)/.+\..+')
class UniqueCollision(Exception):
"""An attempt to create two pages with the same unique metadata"""
def __init__(self, existing):
self.existing = existing
class SlugCollision(UniqueCollision):
"""An attempt to create two pages of the same slug in one locale"""
def _inherited(parent_attr, direct_attr):
"""Return a descriptor delegating to an attr of the original document.
If `self` is a translation, the descriptor delegates to the attribute
`parent_attr` from the original document. Otherwise, it delegates to the
attribute `direct_attr` from `self`.
Use this only on a reference to another object, like a ManyToMany or a
ForeignKey. Using it on a normal field won't work well, as it'll preclude
the use of that field in QuerySet field lookups. Also, ModelForms that are
passed instance=this_obj won't see the inherited value.
"""
getter = lambda self: (getattr(self.parent, parent_attr)
if self.parent and
self.parent.id != self.id
else getattr(self, direct_attr))
setter = lambda self, val: (setattr(self.parent, parent_attr,
val) if self.parent and
self.parent.id != self.id else
setattr(self, direct_attr, val))
return property(getter, setter)
class DocumentManager(ManagerBase):
"""Manager for Documents, assists for queries"""
def clean_content(self, content_in, use_constance_bleach_whitelists=False):
allowed_hosts = constance.config.KUMA_CODE_SAMPLE_HOSTS.split(' ')
out = (wiki.content
.parse(content_in)
.filterIframeHosts(allowed_hosts)
.serialize())
if use_constance_bleach_whitelists:
tags = constance.config.BLEACH_ALLOWED_TAGS
attributes = constance.config.BLEACH_ALLOWED_ATTRIBUTES
styles = constance.config.BLEACH_ALLOWED_STYLES
else:
tags = ALLOWED_TAGS
attributes = ALLOWED_ATTRIBUTES
styles = ALLOWED_STYLES
out = bleach.clean(out, attributes=attributes, tags=tags,
styles=styles, skip_gauntlet=True)
return out
def get_by_natural_key(self, locale, slug):
return self.get(locale=locale, slug=slug)
def allows_add_by(self, user, slug):
"""Determine whether the user can create a document with the given
slug. Mainly for enforcing Template: editing permissions"""
if (slug.startswith(TEMPLATE_TITLE_PREFIX) and
not user.has_perm('wiki.add_template_document')):
return False
# NOTE: We could enforce wiki.add_document here, but it's implicitly
# assumed everyone is allowed.
return True
def filter_for_list(self, locale=None, category=None, tag=None,
tag_name=None):
docs = (self.filter(is_template=False, is_redirect=False).
exclude(slug__startswith='User:').
exclude(slug__startswith='Talk:').order_by('title'))
if locale:
docs = docs.filter(locale=locale)
if category:
try:
docs = docs.filter(category=int(category))
except ValueError:
pass
if tag:
docs = docs.filter(tags__in=[tag])
if tag_name:
docs = docs.filter(tags__name=tag_name)
# Leave out the html, since that leads to huge cache objects and we
# never use the content in lists.
docs = docs.defer('html')
return docs
def filter_for_review(self, locale=None, tag=None, tag_name=None):
"""Filter for documents with current revision flagged for review"""
bq = 'current_revision__review_tags__%s'
if tag_name:
q = {bq % 'name': tag_name}
elif tag:
q = {bq % 'in': [tag]}
else:
q = {bq % 'name__isnull': False}
if locale:
q['locale'] = locale
return self.filter(**q).distinct()
def dump_json(self, queryset, stream):
"""Export a stream of JSON-serialized Documents and Revisions
This is inspired by smuggler.views.dump_data with customizations for
Document specifics, per bug 747137
"""
objects = []
for doc in queryset.all():
rev = get_current_or_latest_revision(doc)
if not rev:
# Skip this doc if, for some reason, there's no revision.
continue
# Drop the pk and circular reference to rev.
doc.pk = None
doc.current_revision = None
objects.append(doc)
# Drop the rev pk
rev.pk = None
objects.append(rev)
# HACK: This is kind of awkward, but the serializer only accepts a flat
# list of field names across all model classes that get handled. So,
# this is a mashup whitelist of Document and Revision fields.
fields = (
# TODO: Maybe make this an *exclusion* list by getting the list of
# fields from Document and Revision models and knocking out what we
# don't want? Serializer doesn't support exclusion list directly.
'title', 'locale', 'slug', 'tags', 'is_template', 'is_localizable',
'parent', 'parent_topic', 'category', 'document', 'is_redirect',
'summary', 'content', 'comment',
'keywords', 'tags', 'toc_depth', 'significance', 'is_approved',
'creator', # HACK: Replaced on import, but deserialize needs it
'mindtouch_page_id', 'mindtouch_old_id', 'is_mindtouch_migration',
)
serializers.serialize('json', objects, indent=2, stream=stream,
fields=fields, use_natural_keys=True)
def load_json(self, creator, stream):
"""Import a stream of JSON-serialized Documents and Revisions
This is inspired by smuggler.views.load_data with customizations for
Document specifics, per bug 747137
"""
counter = 0
objects = serializers.deserialize('json', stream)
for obj in objects:
# HACK: Dig up the deserializer wrapped model object & manager,
# because the deserializer wrapper bypasses some things we need to
# un-bypass here
actual = obj.object
mgr = actual._default_manager
actual.pk = None
if hasattr(mgr, 'get_by_natural_key'):
# If the model uses natural keys, attempt to find the pk of an
# existing record to overwrite.
try:
nk = actual.natural_key()
existing = mgr.get_by_natural_key(*nk)
actual.pk = existing.pk
except actual.DoesNotExist:
pass
# Tweak a few fields on the way through for Revisions.
if type(actual) is Revision:
actual.creator = creator
actual.created = datetime.now()
actual.save()
counter += 1
return counter
class DocumentTag(TagBase):
"""A tag indexing a document"""
class Meta:
verbose_name = _("Document Tag")
verbose_name_plural = _("Document Tags")
class TaggedDocument(ItemBase):
"""Through model, for tags on Documents"""
content_object = models.ForeignKey('Document')
tag = models.ForeignKey(DocumentTag)
# FIXME: This is copypasta from taggit/models.py#TaggedItemBase, which I
# don't like. But, it seems to be the only way to get *both* a custom tag
# *and* a custom through model.
# See: https://github.com/boar/boar/blob/master/boar/articles/models.py#L63
@classmethod
def tags_for(cls, model, instance=None):
if instance is not None:
return DocumentTag.objects.filter(
taggeddocument__content_object=instance)
return DocumentTag.objects.filter(
taggeddocument__content_object__isnull=False).distinct()
class DocumentRenderingInProgress(Exception):
"""An attempt to render a page while a rendering is already in progress is
disallowed."""
pass
class DocumentRenderedContentNotAvailable(Exception):
"""No rendered content available, and an attempt to render on the spot was
denied. So, the view should fall back to presenting raw content for now."""
pass
@register_live_index
class Document(NotificationsMixin, ModelBase):
"""A localized knowledgebase document, not revision-specific."""
class Meta(object):
unique_together = (('parent', 'locale'), ('slug', 'locale'))
permissions = (
("add_template_document", "Can add Template:* document"),
("change_template_document", "Can change Template:* document"),
("move_tree", "Can move a tree of documents"),
)
objects = DocumentManager()
title = models.CharField(max_length=255, db_index=True)
slug = models.CharField(max_length=255, db_index=True)
# NOTE: Documents are indexed by tags, but tags are edited in Revisions.
# Also, using a custom through table to isolate Document tags from those
# used in other models and apps. (Works better than namespaces, for
# completion and such.)
tags = TaggableManager(through=TaggedDocument)
# Is this document a template or not?
is_template = models.BooleanField(default=False, editable=False,
db_index=True)
# Is this a redirect or not?
is_redirect = models.BooleanField(default=False, editable=False,
db_index=True)
# Is this document localizable or not?
is_localizable = models.BooleanField(default=True, db_index=True)
# TODO: validate (against settings.SUMO_LANGUAGES?)
locale = LocaleField(default=settings.WIKI_DEFAULT_LANGUAGE, db_index=True)
# Latest approved revision. L10n dashboard depends on this being so (rather
# than being able to set it to earlier approved revisions). (Remove "+" to
# enable reverse link.)
current_revision = models.ForeignKey('Revision', null=True,
related_name='current_for+')
# The Document I was translated from. NULL iff this doc is in the default
# locale or it is nonlocalizable. TODO: validate against
# settings.WIKI_DEFAULT_LANGUAGE.
parent = models.ForeignKey('self', related_name='translations',
null=True, blank=True)
parent_topic = models.ForeignKey('self', related_name='children',
null=True, blank=True)
# Related documents, based on tags in common.
# The RelatedDocument table is populated by
# wiki.cron.calculate_related_documents.
related_documents = models.ManyToManyField('self',
through='RelatedDocument',
symmetrical=False)
files = models.ManyToManyField('Attachment',
through='DocumentAttachment')
# Raw HTML of approved revision's wiki markup
html = models.TextField(editable=False)
# Cached result of kumascript and other offline processors (if any)
rendered_html = models.TextField(editable=False, blank=True, null=True)
# Errors (if any) from the last rendering run
rendered_errors = models.TextField(editable=False, blank=True, null=True)
# Whether or not to automatically defer rendering of this page to a queued
# offline task. Generally used for complex pages that need time
defer_rendering = models.BooleanField(default=False, db_index=True)
# Timestamp when this document was last scheduled for a render
render_scheduled_at = models.DateTimeField(null=True, db_index=True)
# Timestamp when a render for this document was last started
render_started_at = models.DateTimeField(null=True, db_index=True)
# Timestamp when this document was last rendered
last_rendered_at = models.DateTimeField(null=True, db_index=True)
# A document's category much always be that of its parent. If it has no
# parent, it can do what it wants. This invariant is enforced in save().
category = models.IntegerField(choices=CATEGORIES, db_index=True)
# HACK: Migration bookkeeping - index by the old_id of MindTouch revisions
# so that migrations can be idempotent.
mindtouch_page_id = models.IntegerField(
help_text="ID for migrated MindTouch page",
null=True, db_index=True)
# Last modified time for the document. Should be equal-to or greater than
# the current revision's created field
modified = models.DateTimeField(auto_now=True, null=True, db_index=True)
# firefox_versions,
# operating_systems:
# defined in the respective classes below. Use them as in
# test_firefox_versions.
def calculate_etag(self, section_id=None):
"""Calculate an etag-suitable hash for document content or a section"""
if not section_id:
content = self.html
else:
content = (wiki.content
.parse(self.html)
.extractSection(section_id)
.serialize())
return '"%s"' % hashlib.sha1(content.encode('utf8')).hexdigest()
@property
def is_rendering_scheduled(self):
"""Does this have a rendering scheduled?"""
if not self.render_scheduled_at:
return False
# Check whether a scheduled rendering has waited for too long. Assume
# failure, in this case, and allow another scheduling attempt.
timeout = constance.config.KUMA_DOCUMENT_RENDER_TIMEOUT
max_duration = timedelta(seconds=timeout)
duration = datetime.now() - self.render_scheduled_at
if (duration > max_duration):
return False
if not self.last_rendered_at:
return True
return self.render_scheduled_at > self.last_rendered_at
@property
def is_rendering_in_progress(self):
"""Does this have a rendering in progress?"""
if not self.render_started_at:
# No start time, so False.
return False
# Check whether an in-progress rendering has gone on for too long.
# Assume failure, in this case, and allow another rendering attempt.
timeout = constance.config.KUMA_DOCUMENT_RENDER_TIMEOUT
max_duration = timedelta(seconds=timeout)
duration = datetime.now() - self.render_started_at
if (duration > max_duration):
return False
if not self.last_rendered_at:
# No rendering ever, so in progress.
return True
# Finally, if the render start is more recent than last completed
# render, then we have one in progress.
return self.render_started_at > self.last_rendered_at
def get_rendered(self, cache_control=None, base_url=None):
"""Attempt to get rendered content for this document"""
# No rendered content yet, so schedule the first render.
if not self.rendered_html:
try:
self.schedule_rendering(cache_control, base_url)
except DocumentRenderingInProgress:
# Unable to trigger a rendering right now, so we bail.
raise DocumentRenderedContentNotAvailable()
# If we have a cache_control directive, try scheduling a render.
if cache_control:
try:
self.schedule_rendering(cache_control, base_url)
except DocumentRenderingInProgress:
pass
# Parse JSON errors, if available.
errors = None
try:
errors = (self.rendered_errors and
json.loads(self.rendered_errors) or None)
except ValueError:
pass
# If the above resulted in an immediate render, we might have content.
if not self.rendered_html:
if errors:
return ('', errors)
else:
# But, no such luck, so bail out.
raise DocumentRenderedContentNotAvailable()
return (self.rendered_html, errors)
def schedule_rendering(self, cache_control=None, base_url=None):
"""Attempt to schedule rendering. Honor the deferred_rendering field to
decide between an immediate or a queued render."""
# Avoid scheduling a rendering if already scheduled or in progress.
if self.is_rendering_scheduled or self.is_rendering_in_progress:
return False
# Note when the rendering was scheduled. Kind of a hack, doing a quick
# update and setting the local property rather than doing a save()
now = datetime.now()
Document.objects.filter(pk=self.pk).update(render_scheduled_at=now)
self.render_scheduled_at = now
if not self.defer_rendering:
# Attempt an immediate rendering.
self.render(cache_control, base_url)
else:
# Attempt to queue a rendering. If celery.conf.ALWAYS_EAGER is
# True, this is also an immediate rendering.
from . import tasks
tasks.render_document.delay(self, cache_control, base_url)
def render(self, cache_control=None, base_url=None, timeout=None):
"""Render content using kumascript and any other services necessary."""
# Disallow rendering while another is in progress.
if self.is_rendering_in_progress:
raise DocumentRenderingInProgress()
# Note when the rendering was started. Kind of a hack, doing a quick
# update and setting the local property rather than doing a save()
now = datetime.now()
Document.objects.filter(pk=self.pk).update(render_started_at=now)
self.render_started_at = now
# Perform rendering and update document
if not constance.config.KUMASCRIPT_TIMEOUT:
# A timeout of 0 should shortcircuit kumascript usage.
self.rendered_html, self.rendered_errors = self.html, []
else:
self.rendered_html, errors = kumascript.get(self, cache_control,
base_url,
timeout=timeout)
self.rendered_errors = errors and json.dumps(errors) or None
# Finally, note the end time of rendering and update the document.
self.last_rendered_at = datetime.now()
# If this rendering took longer than we'd like, mark it for deferred
# rendering in the future.
timeout = constance.config.KUMA_DOCUMENT_FORCE_DEFERRED_TIMEOUT
max_duration = timedelta(seconds=timeout)
duration = self.last_rendered_at - self.render_started_at
if (duration >= max_duration):
self.defer_rendering = True
# TODO: Automatically clear the defer_rendering flag if the rendering
# time falls under the limit? Probably safer to require manual
# intervention to free docs from deferred jail.
self.save()
def get_summary(self, strip_markup=True, use_rendered=True):
"""Attempt to get the document summary from rendered content, with
fallback to raw HTML"""
src = self.html
if use_rendered:
try:
r_src, errors = self.get_rendered()
if not errors:
src = r_src
except:
pass
summary = wiki.content.get_seo_description(src, self.locale,
strip_markup)
return summary
def extract_code_sample(self, id):
"""Given the id of a code sample, attempt to extract it from rendered
HTML with a fallback to non-rendered in case of errors."""
try:
src, errors = self.get_rendered()
if errors:
src = self.html
except:
src = self.html
return wiki.content.extract_code_sample(id, src)
def natural_key(self):
return (self.locale, self.slug,)
@property
def natural_cache_key(self):
nk = u'/'.join(self.natural_key())
return hashlib.md5(nk.encode('utf8')).hexdigest()
def _existing(self, attr, value):
"""Return an existing doc (if any) in this locale whose `attr` attr is
equal to mine."""
return Document.uncached.filter(locale=self.locale,
**{attr: value})
def _raise_if_collides(self, attr, exception):
"""Raise an exception if a page of this title/slug already exists."""
if self.id is None or hasattr(self, 'old_' + attr):
# If I am new or my title/slug changed...
existing = self._existing(attr, getattr(self, attr))
if existing.exists():
raise exception(existing[0])
def clean(self):
"""Translations can't be localizable."""
self._clean_is_localizable()
self._clean_category()
def _clean_is_localizable(self):
"""is_localizable == allowed to have translations. Make sure that isn't
violated.
For default language (en-US), is_localizable means it can have
translations. Enforce:
* is_localizable=True if it has translations
* if has translations, unable to make is_localizable=False
For non-default langauges, is_localizable must be False.
"""
if self.locale != settings.WIKI_DEFAULT_LANGUAGE:
self.is_localizable = False
# Can't save this translation if parent not localizable
if (self.parent and self.parent.id != self.id and
not self.parent.is_localizable):
raise ValidationError('"%s": parent "%s" is not localizable.' % (
unicode(self), unicode(self.parent)))
# Can't make not localizable if it has translations
# This only applies to documents that already exist, hence self.pk
# TODO: Use uncached manager here, if we notice problems
if self.pk and not self.is_localizable and self.translations.exists():
raise ValidationError('"%s": document has %s translations but is '
'not localizable.' % (
unicode(self), self.translations.count()))
def _clean_category(self):
"""Make sure a doc's category is the same as its parent's."""
parent = self.parent
if parent:
self.category = parent.category
elif self.category not in (id for id, name in CATEGORIES):
# All we really need to do here is make sure category != '' (which
# is what it is when it's missing from the DocumentForm). The extra
# validation is just a nicety.
raise ValidationError(_('Please choose a category.'))
else: # An article cannot have both a parent and children.
# Make my children the same as me:
if self.id:
self.translations.all().update(category=self.category)
def _attr_for_redirect(self, attr, template):
"""Return the slug or title for a new redirect.
`template` is a Python string template with "old" and "number" tokens
used to create the variant.
"""
def unique_attr():
"""Return a variant of getattr(self, attr) such that there is no
Document of my locale with string attribute `attr` equal to it.
Never returns the original attr value.
"""
# "My God, it's full of race conditions!"
i = 1
while True:
new_value = template % dict(old=getattr(self, attr), number=i)
if not self._existing(attr, new_value).exists():
return new_value
i += 1
old_attr = 'old_' + attr
if hasattr(self, old_attr):
# My slug (or title) is changing; we can reuse it for the redirect.
return getattr(self, old_attr)
else:
# Come up with a unique slug (or title):
return unique_attr()
def revert(self, revision, user):
old_review_tags = [t.name for t in revision.review_tags.all()]
if revision.document.original == self:
revision.based_on = revision
revision.id = None
revision.comment = "Revert to revision of %s by %s" % (
revision.created, revision.creator)
revision.created = datetime.now()
revision.creator = user
revision.save()
if old_review_tags:
revision.review_tags.set(*old_review_tags)
revision.make_current()
return revision
def revise(self, user, data, section_id=None):
"""Given a dict of changes to make, build and save a new Revision to
revise this document"""
curr_rev = self.current_revision
new_rev = Revision(creator=user, document=self, content=self.html)
for n in ('title', 'slug', 'category'):
setattr(new_rev, n, getattr(self, n))
if curr_rev:
new_rev.toc_depth = curr_rev.toc_depth
# Accept optional field edits...
new_title = data.get('title', False)
new_rev.title = (new_title and new_title or self.title)
new_tags = data.get('tags', False)
new_rev.tags = (new_tags and new_tags or
edit_string_for_tags(self.tags.all()))
new_review_tags = data.get('review_tags', False)
if new_review_tags:
review_tags = new_review_tags
elif curr_rev:
review_tags = edit_string_for_tags(curr_rev.review_tags.all())
else:
review_tags = ''
new_rev.summary = data.get('summary', '')
# Accept HTML edits, optionally by section
new_html = data.get('content', data.get('html', False))
if new_html:
if not section_id:
new_rev.content = new_html
else:
new_rev.content = (wiki.content.parse(self.html)
.replaceSection(section_id, new_html)
.serialize())
# Finally, commit the revision changes and return the new rev.
new_rev.save()
new_rev.review_tags.set(*parse_tags(review_tags))
return new_rev
def save(self, *args, **kwargs):
self.is_template = self.slug.startswith(TEMPLATE_TITLE_PREFIX)
self.is_redirect = 1 if self.redirect_url() else 0
try:
# Check if the slug would collide with an existing doc