This repository has been archived by the owner on Aug 26, 2022. It is now read-only.
/
models.py
2016 lines (1694 loc) · 73.7 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 hashlib
import json
import sys
import traceback
from datetime import datetime, timedelta
from functools import wraps
from uuid import uuid4
import newrelic.agent
import waffle
from constance import config
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models, transaction
from django.db.models import signals
from django.utils.decorators import available_attrs
from django.utils.functional import cached_property
from django.utils.translation import ugettext, ugettext_lazy as _
from pyquery import PyQuery
from taggit.managers import TaggableManager
from taggit.models import ItemBase, TagBase
from taggit.utils import edit_string_for_tags, parse_tags
from tidings.models import NotificationsMixin
from kuma.core.cache import memcache
from kuma.core.exceptions import ProgrammingError
from kuma.core.i18n import get_language_mapping
from kuma.core.urlresolvers import reverse
from kuma.search.decorators import register_live_index
from kuma.spam.models import AkismetSubmission, SpamAttempt
from . import kumascript
from .constants import (DEKI_FILE_URL, DOCUMENT_LAST_MODIFIED_CACHE_KEY_TMPL,
EXPERIMENT_TITLE_PREFIX, KUMA_FILE_URL,
REDIRECT_CONTENT, REDIRECT_HTML)
from .content import parse as parse_content
from .content import (Extractor, H2TOCFilter, H3TOCFilter, SectionTOCFilter,
get_content_sections, get_seo_description)
from .exceptions import (DocumentRenderedContentNotAvailable,
DocumentRenderingInProgress, PageMoveError,
SlugCollision, UniqueCollision, NotDocumentView)
from .jobs import DocumentContributorsJob, DocumentNearestZoneJob
from .managers import (DeletedDocumentManager, DocumentAdminManager,
DocumentManager, RevisionIPManager,
TaggedDocumentManager)
from .signals import render_done
from .templatetags.jinja_helpers import absolutify
from .utils import tidy_content, get_doc_components_from_url
def cache_with_field(field_name):
"""Decorator for generated content methods.
If the backing model field is null, or kwarg force_fresh is True, call the
decorated method to generate and return the content.
Otherwise, just return the value in the backing model field.
"""
def decorator(fn):
@wraps(fn, assigned=available_attrs(fn))
def wrapper(self, *args, **kwargs):
force_fresh = kwargs.pop('force_fresh', False)
# Try getting the value using the DB field.
field_val = getattr(self, field_name)
if field_val is not None and not force_fresh:
return field_val
# DB field is blank, or we're forced to generate it fresh.
field_val = fn(self, force_fresh=force_fresh)
setattr(self, field_name, field_val)
return field_val
return wrapper
return decorator
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)
def valid_slug_parent(slug, locale):
slug_bits = slug.split('/')
slug_bits.pop()
parent = None
if slug_bits:
parent_slug = '/'.join(slug_bits)
try:
parent = Document.objects.get(locale=locale, slug=parent_slug)
except Document.DoesNotExist:
raise Exception(
ugettext('Parent %s does not exist.' % (
'%s/%s' % (locale, parent_slug))))
return parent
class DocumentTag(TagBase):
"""A tag indexing a document"""
class Meta:
verbose_name = _('Document Tag')
verbose_name_plural = _('Document Tags')
def tags_for(cls, model, instance=None, **extra_filters):
"""
Sadly copied from taggit to work around the issue of not being
able to use the TaggedItemBase class that has tag field already
defined.
"""
kwargs = extra_filters or {}
if instance is not None:
kwargs.update({
'%s__content_object' % cls.tag_relname(): instance
})
return cls.tag_model().objects.filter(**kwargs)
kwargs.update({
'%s__content_object__isnull' % cls.tag_relname(): False
})
return cls.tag_model().objects.filter(**kwargs).distinct()
class TaggedDocument(ItemBase):
"""Through model, for tags on Documents"""
content_object = models.ForeignKey('Document')
tag = models.ForeignKey(DocumentTag, related_name="%(app_label)s_%(class)s_items")
objects = TaggedDocumentManager()
@classmethod
def tags_for(cls, *args, **kwargs):
return tags_for(cls, *args, **kwargs)
class DocumentAttachment(models.Model):
"""
Intermediary between Documents and Attachments. Allows storing the
user who attached a file to a document, and a (unique for that
document) name for referring to the file from the document.
"""
file = models.ForeignKey(
'attachments.Attachment',
related_name='document_attachments',
)
document = models.ForeignKey(
'wiki.Document',
related_name='attached_files',
)
attached_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True)
name = models.TextField()
# whether or not this attachment was uploaded for the document
is_original = models.BooleanField(
verbose_name=_('uploaded to the document'),
default=False,
)
# whether or not this attachment is linked in the document's content
is_linked = models.BooleanField(
verbose_name=_('linked in the document content'),
default=False,
)
class Meta:
db_table = 'attachments_documentattachment'
def __unicode__(self):
return u'"%s" for document "%s"' % (self.file, self.document)
def clean(self):
if self.pk and (self.document.files.through.objects.exclude(pk=self.pk)
.exists()):
raise ValidationError(
_("Attachment %(attachment_id)s can't be attached "
"multiple times to document %(document_id)s") %
{'attachment_id': self.pk, 'document_id': self.document.pk}
)
@register_live_index
class Document(NotificationsMixin, models.Model):
"""A localized knowledgebase document, not revision-specific."""
TOC_FILTERS = {
1: SectionTOCFilter,
2: H2TOCFilter,
3: H3TOCFilter,
4: SectionTOCFilter
}
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)
# DEPRECATED: Is this document a template or not?
# Droping or altering this column will require a table rebuild, so it
# should be done in a maintenance window.
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)
locale = models.CharField(
max_length=7,
choices=settings.LANGUAGES,
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).
current_revision = models.ForeignKey(
'Revision',
null=True,
related_name='current_for+',
)
# The Document I was translated from. NULL if 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,
)
# The files attached to the document, represented by a custom intermediate
# model so we can store some metadata about the relation
files = models.ManyToManyField(
'attachments.Attachment',
through=DocumentAttachment,
)
# JSON representation of Document for API results, built on save
json = models.TextField(editable=False, blank=True, null=True)
# 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)
# Maximum age (in seconds) before this document needs re-rendering
render_max_age = models.IntegerField(blank=True, null=True)
# Time after which this document needs re-rendering
render_expires = models.DateTimeField(blank=True, null=True, db_index=True)
# Whether this page is deleted.
deleted = models.BooleanField(default=False, 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)
body_html = models.TextField(editable=False, blank=True, null=True)
quick_links_html = models.TextField(editable=False, blank=True, null=True)
zone_subnav_local_html = models.TextField(editable=False,
blank=True, null=True)
toc_html = models.TextField(editable=False, blank=True, null=True)
summary_html = models.TextField(editable=False, blank=True, null=True)
summary_text = models.TextField(editable=False, blank=True, null=True)
uuid = models.UUIDField(default=uuid4, editable=False)
class Meta(object):
unique_together = (
('parent', 'locale'),
('slug', 'locale'),
)
permissions = (
('view_document', 'Can view document'),
('move_tree', 'Can move a tree of documents'),
('purge_document', 'Can permanently delete document'),
('restore_document', 'Can restore deleted document'),
)
objects = DocumentManager()
deleted_objects = DeletedDocumentManager()
admin_objects = DocumentAdminManager()
def __unicode__(self):
return u'%s (%s)' % (self.get_absolute_url(), self.title)
@cache_with_field('body_html')
def get_body_html(self, *args, **kwargs):
html = self.rendered_html and self.rendered_html or self.html
sections_to_hide = ('Quick_Links', 'Subnav')
doc = parse_content(html)
for sid in sections_to_hide:
doc = doc.replaceSection(sid, '<!-- -->')
doc.injectSectionIDs()
doc.annotateLinks(base_url=settings.SITE_URL)
return doc.serialize()
@cache_with_field('quick_links_html')
def get_quick_links_html(self, *args, **kwargs):
return self.get_section_content('Quick_Links')
@cache_with_field('zone_subnav_local_html')
def get_zone_subnav_local_html(self, *args, **kwargs):
return self.get_section_content('Subnav')
@cache_with_field('toc_html')
def get_toc_html(self, *args, **kwargs):
if not self.current_revision:
return ''
toc_depth = self.current_revision.toc_depth
if not toc_depth:
return ''
html = self.rendered_html and self.rendered_html or self.html
return (parse_content(html)
.injectSectionIDs()
.filter(self.TOC_FILTERS[toc_depth])
.serialize())
@cache_with_field('summary_html')
def get_summary_html(self, *args, **kwargs):
return self.get_summary(strip_markup=False)
@cache_with_field('summary_text')
def get_summary_text(self, *args, **kwargs):
return self.get_summary(strip_markup=True)
@classmethod
def from_url(cls, url, id_only=True):
"""
Return the approved Document the URL represents, None if there isn't one.
Taken from:
https://github.com/mozilla/kitsune/blob/dd944c9ebb126cc1e660fba569cd68a6c7e88430/kitsune/wiki/models.py#L388
Return None if the URL is a 404, the URL doesn't point to the right
view, or the indicated document doesn't exist.
To fetch all values of the returned Document not only ID,
set `id_only` to True.
"""
try:
components = get_doc_components_from_url(url)
except NotDocumentView:
return None
if not components:
return None
locale, path, slug = components
doc = cls.objects
if id_only:
doc = doc.only('id')
try:
doc = doc.get(locale=locale, slug=slug)
except cls.DoesNotExist:
try:
# Check if the slug belongs to any default language document
doc = doc.get(locale=settings.WIKI_DEFAULT_LANGUAGE, slug=slug)
translation = doc.translated_to(locale)
if translation:
return translation
except cls.DoesNotExist:
return None
return doc
def regenerate_cache_with_fields(self):
"""Regenerate fresh content for all the cached fields"""
# TODO: Maybe @cache_with_field can build a registry over which this
# method can iterate?
self.get_body_html(force_fresh=True)
self.get_quick_links_html(force_fresh=True)
self.get_zone_subnav_local_html(force_fresh=True)
self.get_toc_html(force_fresh=True)
self.get_summary_html(force_fresh=True)
self.get_summary_text(force_fresh=True)
def get_zone_subnav_html(self):
"""
Search this document and, if nothing is found, the document directly
associated with its nearest zone, returning the first zone nav HTML
found.
"""
src = self.get_zone_subnav_local_html()
if (not src) and self.nearest_zone:
src = self.nearest_zone.document.get_zone_subnav_local_html()
return src
def get_section_content(self, section_id, ignore_heading=True):
"""
Convenience method to extract the rendered content for a single section
"""
if self.rendered_html:
content = self.rendered_html
else:
content = self.html
return self.extract.section(content, section_id, ignore_heading)
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 = self.extract.section(self.html, section_id)
return '"%s"' % hashlib.sha1(content.encode('utf8')).hexdigest()
def current_or_latest_revision(self):
"""Returns current revision if there is one, else the last created
revision."""
rev = self.current_revision
if not rev:
revs = self.revisions.order_by('-created')
if revs.exists():
rev = revs[0]
return rev
@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 = 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 = 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
@newrelic.agent.function_trace()
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.
"""
if settings.MAINTENANCE_MODE:
return
# Avoid scheduling a rendering if already scheduled or in progress.
if self.is_rendering_scheduled or self.is_rendering_in_progress:
return
# 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 (waffle.switch_is_active('wiki_force_immediate_rendering') or
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.pk, cache_control, base_url)
def render(self, cache_control=None, base_url=None, timeout=None):
"""
Render content using kumascript and any other services necessary.
"""
if settings.MAINTENANCE_MODE:
return
if not base_url:
base_url = settings.SITE_URL
# 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 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
# Regenerate the cached content fields
self.regenerate_cache_with_fields()
# 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 = 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.
if self.render_max_age:
# If there's a render_max_age, automatically update render_expires
self.render_expires = (datetime.now() +
timedelta(seconds=self.render_max_age))
else:
# Otherwise, just clear the expiration time as a one-shot
self.render_expires = None
self.save()
render_done.send(sender=self.__class__, instance=self)
def get_summary(self, strip_markup=True, use_rendered=True):
"""
Attempt to get the document summary from rendered content, with
fallback to raw HTML
"""
if use_rendered and self.rendered_html:
src = self.rendered_html
else:
src = self.html
return get_seo_description(src, self.locale, strip_markup)
def build_json_data(self):
html = self.rendered_html and self.rendered_html or self.html
content = parse_content(html).injectSectionIDs().serialize()
sections = get_content_sections(content)
translations = []
if self.pk:
for translation in self.other_translations:
revision = translation.current_revision
if revision.summary:
summary = revision.summary
else:
summary = translation.get_summary(strip_markup=False)
translations.append({
'last_edit': revision.created.isoformat(),
'locale': translation.locale,
'localization_tags': list(revision.localization_tags
.names()),
'review_tags': list(revision.review_tags.names()),
'summary': summary,
'tags': list(translation.tags.names()),
'title': translation.title,
'url': translation.get_absolute_url(),
'uuid': str(translation.uuid)
})
if self.current_revision:
review_tags = list(self.current_revision.review_tags.names())
localization_tags = list(self.current_revision
.localization_tags
.names())
last_edit = self.current_revision.created.isoformat()
if self.current_revision.summary:
summary = self.current_revision.summary
else:
summary = self.get_summary(strip_markup=False)
else:
review_tags = []
localization_tags = []
last_edit = ''
summary = ''
if not self.pk:
tags = []
else:
tags = list(self.tags.names())
now_iso = datetime.now().isoformat()
if self.modified:
modified = self.modified.isoformat()
else:
modified = now_iso
return {
'title': self.title,
'label': self.title,
'url': self.get_absolute_url(),
'id': self.id,
'uuid': str(self.uuid),
'slug': self.slug,
'tags': tags,
'review_tags': review_tags,
'localization_tags': localization_tags,
'sections': sections,
'locale': self.locale,
'summary': summary,
'translations': translations,
'modified': modified,
'json_modified': now_iso,
'last_edit': last_edit
}
def get_json_data(self, stale=True):
"""Returns a document in object format for output as JSON.
The stale parameter, when True, accepts stale cached data even after
the document has been modified."""
# Have parsed data & don't care about freshness? Here's a quick out..
curr_json_data = getattr(self, '_json_data', None)
if curr_json_data and stale:
return curr_json_data
# Attempt to parse the current contents of self.json, taking care in
# case it's empty or broken JSON.
self._json_data = {}
if self.json:
try:
self._json_data = json.loads(self.json)
except (TypeError, ValueError):
pass
# Try to get ISO 8601 datestamps for the doc and the json
json_lmod = self._json_data.get('json_modified', '')
doc_lmod = self.modified.isoformat()
# If there's no parsed data or the data is stale & we care, it's time
# to rebuild the cached JSON data.
if (not self._json_data) or (not stale and doc_lmod > json_lmod):
self._json_data = self.build_json_data()
self.json = json.dumps(self._json_data)
if not settings.MAINTENANCE_MODE:
Document.objects.filter(pk=self.pk).update(json=self.json)
return self._json_data
@cached_property
def extract(self):
return Extractor(self)
def natural_key(self):
return (self.locale, self.slug)
@staticmethod
def natural_key_hash(keys):
natural_key = u'/'.join(keys)
return hashlib.md5(natural_key.encode('utf8')).hexdigest()
@cached_property
def natural_cache_key(self):
return self.natural_key_hash(self.natural_key())
def _existing(self, attr, value):
"""Return an existing doc (if any) in this locale whose `attr` attr is
equal to mine."""
return Document.objects.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()
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
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 _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, comment=None):
"""
Reverts the given revision by creating a new one.
- Sets its comment to the given value and points the new revision
to the old revision
- Keeps review tags
- Make new revision the current one of the document
"""
# remember the current revision's primary key for later
old_revision_pk = revision.pk
# get a list of review tag names for later
old_review_tags = list(revision.review_tags.names())
with transaction.atomic():
# reset primary key
revision.pk = None
# add a sensible comment
revision.comment = ("Revert to revision of %s by %s" %
(revision.created, revision.creator))
if comment:
revision.comment = u'%s: "%s"' % (revision.comment, comment)
revision.created = datetime.now()
revision.creator = user
if revision.document.original.pk == self.pk:
revision.based_on_id = old_revision_pk
revision.save()
# set review tags
if old_review_tags:
revision.review_tags.set(*old_review_tags)
# populate model instance with fresh data from database
revision.refresh_from_db()
# make this new revision the current one for the document
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', 'render_max_age'):
setattr(new_rev, n, getattr(self, n))
if curr_rev:
new_rev.toc_depth = curr_rev.toc_depth
original_doc = curr_rev.document.original
if original_doc == self:
new_rev.based_on = curr_rev
else:
new_rev.based_on = original_doc.current_revision
# 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', '')
# To add comment, when Technical/Editorial review completed
new_rev.comment = data.get('comment', '')
# 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:
content = parse_content(self.html)
new_rev.content = (content.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
@cached_property
def last_modified_cache_key(self):
return DOCUMENT_LAST_MODIFIED_CACHE_KEY_TMPL % self.natural_cache_key
def fill_last_modified_cache(self):
"""
Convert python datetime to Unix epoch seconds. This is more
easily digested by the cache, and is more compatible with other
services that might spy on Kuma's cache entries (eg. KumaScript)
"""
modified_epoch = self.modified.strftime('%s')
memcache.set(self.last_modified_cache_key, modified_epoch)
return modified_epoch
def save(self, *args, **kwargs):
self.is_redirect = bool(self.get_redirect_url())
try:
# Check if the slug would collide with an existing doc
self._raise_if_collides('slug', SlugCollision)
except UniqueCollision as err:
if err.existing.get_redirect_url() is not None:
# If the existing doc is a redirect, delete it and clobber it.
err.existing.delete()
else:
raise err
# These are too important to leave to a (possibly omitted) is_valid
# call:
self._clean_is_localizable()
if not self.parent_topic and self.parent:
# If this is a translation without a topic parent, try to get one.
self.acquire_translated_topic_parent()
super(Document, self).save(*args, **kwargs)
# Delete any cached last-modified timestamp.
self.fill_last_modified_cache()
def delete(self, *args, **kwargs):
if waffle.switch_is_active('wiki_error_on_delete'):
# bug 863692: Temporary while we investigate disappearing pages.
raise Exception("Attempt to delete document %s: %s" %
(self.id, self.title))
else:
if self.is_redirect or 'purge' in kwargs:
if 'purge' in kwargs:
kwargs.pop('purge')
return super(Document, self).delete(*args, **kwargs)
signals.pre_delete.send(sender=self.__class__,
instance=self)
if not self.deleted:
Document.objects.filter(pk=self.pk).update(deleted=True)
memcache.delete(self.last_modified_cache_key)
signals.post_delete.send(sender=self.__class__, instance=self)
def purge(self):
if waffle.switch_is_active('wiki_error_on_delete'):
# bug 863692: Temporary while we investigate disappearing pages.
raise Exception("Attempt to purge document %s: %s" %
(self.id, self.title))