Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Merge pull request #847 from groovecoder/attachment-host-834300

fix bug 834300 - attachments from ATTACHMENT_HOST
  • Loading branch information...
commit 53f679b1aaccffb092edeba7751d212f2193e4e3 2 parents 955446f + 814128a
@lmorchard lmorchard authored
View
43 apps/wiki/models.py
@@ -53,7 +53,8 @@
# 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',
+ 'section', 'header', 'footer', 'nav', 'article', 'aside', 'figure',
+ 'figcaption',
'dialog', 'hgroup', 'mark', 'time', 'meter', 'command', 'output',
'progress', 'audio', 'video', 'details', 'datagrid', 'datalist', 'table',
'address', 'font',
@@ -73,7 +74,8 @@
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']
+ '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',
@@ -86,10 +88,12 @@
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'])
+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']) for x in (
+ALLOWED_ATTRIBUTES.update(dict((x, ['style', 'class', 'id', 'lang', 'dir'])
+ 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',
@@ -357,7 +361,7 @@ def clean_content(self, content_in, use_constance_bleach_whitelists=False):
.parse(content_in)
.filterIframeHosts(allowed_hosts)
.serialize())
-
+
if use_constance_bleach_whitelists:
tags = constance.config.BLEACH_ALLOWED_TAGS
attributes = constance.config.BLEACH_ALLOWED_ATTRIBUTES
@@ -646,7 +650,6 @@ def calculate_etag(self, section_id=None):
.serialize())
return '"%s"' % hashlib.sha1(content.encode('utf8')).hexdigest()
-
@property
def is_rendering_scheduled(self):
"""Does this have a rendering scheduled?"""
@@ -763,7 +766,8 @@ def render(self, cache_control=None, base_url=None, timeout=None):
self.rendered_html, self.rendered_errors = self.html, []
else:
self.rendered_html, errors = kumascript.get(self, cache_control,
- base_url, timeout=timeout)
+ 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.
@@ -949,7 +953,7 @@ def revise(self, user, data, section_id=None):
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
@@ -1041,7 +1045,7 @@ def _tree_conflicts(self, new_slug):
child_title = child.slug.split('/')[-1]
try:
existing = Document.objects.get(locale=self.locale,
- slug='/'.join([new_slug, child_title]))
+ slug='/'.join([new_slug, child_title]))
if not existing.redirect_url():
conflicts.append(existing)
except Document.DoesNotExist:
@@ -1169,7 +1173,7 @@ def files_dict(self):
'description': rev.description,
'mime_type': rev.mime_type,
'html': attachment.get_embed_html(),
- 'url': attachment.get_file_url(),}
+ 'url': attachment.get_file_url()}
return files
@property
@@ -1388,9 +1392,8 @@ def other_translations(self):
if self.parent == None:
translations = list(self.translations.all().order_by('locale'))
else:
- translations = list(self.parent.translations.all().exclude(
- id=self.id).
- order_by('locale'))
+ translations = list(self.parent.translations.all().
+ exclude(id=self.id).order_by('locale'))
translations.insert(0, self.parent)
return translations
@@ -1796,7 +1799,7 @@ 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('Attachment')
document = models.ForeignKey(Document)
@@ -1839,11 +1842,13 @@ class Meta(object):
def get_absolute_url(self):
return ('wiki.attachment_detail', (), {'attachment_id': self.id})
- @models.permalink
def get_file_url(self):
- return ('wiki.raw_file', (),
- {'attachment_id': self.id,
- 'filename': self.current_revision.filename()})
+ uri = reverse('wiki.raw_file', kwargs={'attachment_id': self.id,
+ 'filename': self.current_revision.filename()})
+ url = '%s%s%s' % (settings.PROTOCOL,
+ settings.ATTACHMENT_HOST,
+ uri)
+ return url
def attach(self, document, user, name):
if self.id not in document.attachments.values_list('id', flat=True):
@@ -1876,7 +1881,7 @@ def get_embed_html(self):
'wiki/attachments/%s.html' % rev.mime_type.split('/')[0],
'wiki/attachments/generic.html'])
return t.render({'attachment': rev})
-
+
class AttachmentRevision(models.Model):
"""
View
95 apps/wiki/tests/test_views.py
@@ -148,7 +148,8 @@ def test_toc_view(self):
slug = 'toc_test_doc'
html = '<h2>Head 2</h2><h3>Head 3</h3>'
- doc = document(title='blah', slug=slug, html=html, save=True, locale=settings.WIKI_DEFAULT_LANGUAGE)
+ doc = document(title='blah', slug=slug, html=html, save=True,
+ locale=settings.WIKI_DEFAULT_LANGUAGE)
doc.save()
rev = revision(document=doc, content=html, is_approved=True, save=True)
rev.save()
@@ -157,7 +158,9 @@ def test_toc_view(self):
locale=settings.WIKI_DEFAULT_LANGUAGE)
resp = self.client.get(url)
- eq_(resp.content, '<ol><li><a href="#Head_2" rel="internal">Head 2</a><ol><li><a href="#Head_3" rel="internal">Head 3</a></ol></li></ol>')
+ eq_(resp.content, '<ol><li><a href="#Head_2" rel="internal">Head 2</a>'
+ '<ol><li><a href="#Head_3" rel="internal">Head 3</a>'
+ '</ol></li></ol>')
def test_children_view(self):
def _make_doc(title, slug, parent=None):
@@ -189,8 +192,8 @@ def _make_doc(title, slug, parent=None):
# Depth parameter testing
def _depth_test(depth, aught):
- url = reverse('wiki.get_children', args=['Root'],
- locale=settings.WIKI_DEFAULT_LANGUAGE) + '?depth=' + str(depth)
+ url = reverse('wiki.get_children', args=['Root'],
+ locale=settings.WIKI_DEFAULT_LANGUAGE) + '?depth=' + str(depth)
resp = self.client.get(url)
json_obj = json.loads(resp.content)
eq_(len(json_obj['subpages'][0]['subpages'][1]['subpages']), aught)
@@ -201,8 +204,10 @@ def _depth_test(depth, aught):
# Sorting test
sort_root_doc = _make_doc('Sort Root', 'Sort_Root')
- sort_child_doc_1 = _make_doc('B Child', 'Sort_Root/B_Child', sort_root_doc)
- sort_child_doc_2 = _make_doc('A Child', 'Sort_Root/A_Child', sort_root_doc)
+ sort_child_doc_1 = _make_doc('B Child', 'Sort_Root/B_Child',
+ sort_root_doc)
+ sort_child_doc_2 = _make_doc('A Child', 'Sort_Root/A_Child',
+ sort_root_doc)
resp = self.client.get(reverse('wiki.get_children', args=['Sort_Root'],
locale=settings.WIKI_DEFAULT_LANGUAGE))
json_obj = json.loads(resp.content)
@@ -717,7 +722,7 @@ def test_noindex_post(self):
# Go to new document page to ensure no-index header works
response = client.get(reverse('wiki.new_document', args=[],
- locale=settings.WIKI_DEFAULT_LANGUAGE))
+ locale=settings.WIKI_DEFAULT_LANGUAGE))
eq_(response['X-Robots-Tag'], 'noindex')
def test_seo_title(self):
@@ -1027,7 +1032,7 @@ def test_invalid_slug(self):
response = client.post(reverse('wiki.new_document'), data)
self.assertRedirects(response,
reverse('wiki.document', args=[data['slug']],
- locale=settings.WIKI_DEFAULT_LANGUAGE))
+ locale=settings.WIKI_DEFAULT_LANGUAGE))
# Slashes should not be acceptable via form input
data['title'] = 'valid with slash'
@@ -1256,7 +1261,6 @@ def test_invalid_slug_edit(inv_slug, url, data):
locale=locale,
args=[edit_doc.slug]))
-
""" TRANSLATION DOCUMENT TESTING """
def _run_translate_tests(translate_slug, translate_data,
translate_doc):
@@ -1294,7 +1298,6 @@ def test_invalid_slug_translate(inv_slug, url, data):
' Redirect 1',
locale=foreign_locale)))
-
# Push a valid translation
translate_data['slug'] = translate_slug
translate_data['form'] = 'both'
@@ -1342,7 +1345,6 @@ def _run_translate_edit_tests(edit_slug, edit_data, edit_doc):
eq_(0, len(Document.objects.filter(title=edit_data['title'] + ' Redirect 1', locale=foreign_locale))) # Ensure no redirect
self.assertRedirects(response, reverse('wiki.document', locale=foreign_locale, args=[edit_doc.slug]))
-
""" TEST EDITING SLUGS AND TRANSLATIONS """
def _run_slug_edit_tests(edit_slug, edit_data, edit_doc, loc):
@@ -1354,7 +1356,6 @@ def _run_slug_edit_tests(edit_slug, edit_data, edit_doc, loc):
eq_(1, len(Document.objects.filter(title__contains=edit_data['title'] + ' Redir', locale=loc))) # Ensure *1* redirect
self.assertRedirects(response, reverse('wiki.document', locale=loc, args=[edit_doc.slug.replace(edit_slug, edit_data['slug'])]))
-
# Run all of the tests
_createAndRunTests("parent")
@@ -1460,7 +1461,7 @@ def test_clone(self):
content = '<p>Hello!</p>'
document = revision(save=True, title=title, slug=slug, content=content).document
-
+
response = self.client.get(reverse('wiki.new_document', args=[], locale=settings.WIKI_DEFAULT_LANGUAGE) + '?clone=' + str(document.id))
page = pq(response.content)
@@ -1468,7 +1469,6 @@ def test_clone(self):
eq_(page.find('input[name=slug]')[0].value, slug + '_clone')
eq_(page.find('textarea[name=content]')[0].value, content)
-
def test_localized_based_on(self):
"""Editing a localized article 'based on' an older revision of the
localization is OK."""
@@ -1646,7 +1646,7 @@ def test_review_tags(self, get_current):
# Post an edit that removes one of the tags.
data.update({
'form': 'rev',
- 'review_tags': ['editorial',],
+ 'review_tags': ['editorial',]
})
response = client.post(reverse('wiki.edit_document', args=[doc.full_path]), data)
@@ -2415,11 +2415,11 @@ def test_document_redirects(self):
def test_list_no_redirects(self):
invalidDocuments = (
- {'title': 'Something Redirect 8', 'slug': 'xx',
+ {'title': 'Something Redirect 8', 'slug': 'xx',
'html': 'REDIRECT <a class="redirect" href="http://davidwalsh.name">yo</a>'},
{'title': 'My Template', 'slug': 'Template:Something', 'html': 'blah'},
)
- validDocuments = ({ 'title': 'A Doc', 'slug': 'blah', 'html': 'Blah blah blah'},)
+ validDocuments = ({'title': 'A Doc', 'slug': 'blah', 'html': 'Blah blah blah'},)
allDocuments = invalidDocuments + validDocuments
for doc in allDocuments:
@@ -2629,7 +2629,7 @@ def test_raw_content_during_initial_render(self, mock_kumascript_get):
ok_(self.rendered_content not in txt)
ok_(self.raw_content in txt)
eq_(0, p.find('#doc-render-raw-fallback').length)
-
+
# Only for logged-in users, ensure that a warning is displayed about
# the fallback
self.client.login(username='testuser', password='testpass')
@@ -2686,7 +2686,7 @@ def test_alternate_bleach_whitelist(self, mock_requests_post, mock_kumascript_ge
<textarea name="foo"></textarea>
</p>
"""
-
+
# Expected result filtered through alternate whitelist
expected_content_new = """
<p id="foo">
@@ -2697,7 +2697,7 @@ def test_alternate_bleach_whitelist(self, mock_requests_post, mock_kumascript_ge
# Set up an alternate set of whitelists...
constance.config.BLEACH_ALLOWED_TAGS = json.dumps([
- "a","p"
+ "a", "p"
])
constance.config.BLEACH_ALLOWED_ATTRIBUTES = json.dumps({
"a": ['href', 'style'],
@@ -2744,7 +2744,7 @@ def test_alternate_bleach_whitelist(self, mock_requests_post, mock_kumascript_ge
resp = self.client.get(url, follow=True)
eq_(normalize_html(expected),
normalize_html(resp.content),
- "Should match? %s %s %s %s" %
+ "Should match? %s %s %s %s" %
(do_login, param, expected, resp.content))
@@ -3109,6 +3109,22 @@ def setUp(self):
def tearDown(self):
constance.config.WIKI_ATTACHMENT_ALLOWED_TYPES = self.old_allowed_types
+ def _post_new_attachment(self):
+ self.client = Client() # file views don't need LocalizingClient
+ self.client.login(username='admin', password='testpass')
+
+ file_for_upload = make_test_file(
+ content='A test file uploaded into kuma.')
+ post_data = {
+ 'title': 'Test uploaded file',
+ 'description': 'A test file uploaded into kuma.',
+ 'comment': 'Initial upload',
+ 'file': file_for_upload,
+ }
+
+ resp = self.client.post(reverse('wiki.new_attachment'), data=post_data)
+ return resp
+
def test_legacy_redirect(self):
self.client = Client() # file views don't need LocalizingClient
test_user = User.objects.get(username='testuser2')
@@ -3148,19 +3164,7 @@ def test_legacy_redirect(self):
ok_(a.get_file_url() in resp['Location'])
def test_new_attachment(self):
- self.client = Client() # file views don't need LocalizingClient
- self.client.login(username='admin', password='testpass')
-
- file_for_upload = make_test_file(
- content='A test file uploaded into kuma.')
- post_data = {
- 'title': 'Test uploaded file',
- 'description': 'A test file uploaded into kuma.',
- 'comment': 'Initial upload',
- 'file': file_for_upload,
- }
-
- resp = self.client.post(reverse('wiki.new_attachment'), data=post_data)
+ resp = self._post_new_attachment()
eq_(302, resp.status_code)
attachment = Attachment.objects.get(title='Test uploaded file')
@@ -3219,10 +3223,24 @@ def test_edit_attachment(self):
eq_('Second revision.', rev.comment)
ok_(rev.is_approved)
- resp = self.client.get(attachment.get_file_url())
+ url = attachment.get_file_url()
+ resp = self.client.get(url, HTTP_HOST=settings.ATTACHMENT_HOST)
eq_('text/plain', rev.mime_type)
ok_('I am a new version of the test file for editing.' in resp.content)
+ def test_attachment_raw_requires_attachment_host(self):
+ resp = self._post_new_attachment()
+ attachment = Attachment.objects.get(title='Test uploaded file')
+
+ url = attachment.get_file_url()
+ resp = self.client.get(url)
+ eq_(301, resp.status_code)
+ eq_(attachment.get_file_url(), resp['Location'])
+
+ url = attachment.get_file_url()
+ resp = self.client.get(url, HTTP_HOST=settings.ATTACHMENT_HOST)
+ eq_(200, resp.status_code)
+
def test_attachment_detail(self):
self.client = Client() # file views don't need LocalizingClient
self.client.login(username='admin', password='testpass')
@@ -3335,7 +3353,7 @@ def test_intermediate(self):
"""
Test that the intermediate DocumentAttachment gets created
correctly when adding an Attachment with a document_id.
-
+
"""
doc = document(locale='en', slug='attachment-test-intermediate')
doc.save()
@@ -3391,7 +3409,7 @@ def test_files_dict(self):
self.client.login(username='admin', password='testpass')
resp = self.client.post(add_url, data=post_data)
-
+
test_file_2 = make_test_file(
content='Another file for testing the files dict')
@@ -3401,7 +3419,7 @@ def test_files_dict(self):
'comment': 'Initial upload',
'file': test_file_2,
}
-
+
resp = self.client.post(add_url, data=post_data)
doc = Document.objects.get(pk=doc.id)
@@ -3578,7 +3596,6 @@ def test_move_top_level_docs(self):
page_child_doc.parent_topic = page_to_move_doc
page_child_doc.save()
-
# move page to new slug
new_title = page_to_move_title + ' Moved'
data = {'slug': page_moved_slug, 'title': new_title}
View
120 apps/wiki/views.py
@@ -63,8 +63,9 @@
from wiki.decorators import check_readonly
from wiki.events import (EditDocumentEvent, ReviewableRevisionInLocaleEvent,
ApproveRevisionInLocaleEvent)
-from wiki.forms import (DocumentForm, RevisionForm, ReviewForm, RevisionValidationForm,
- AttachmentRevisionForm, TreeMoveForm)
+from wiki.forms import (DocumentForm, RevisionForm, ReviewForm,
+ RevisionValidationForm, AttachmentRevisionForm,
+ TreeMoveForm)
from wiki.models import (Document, Revision, HelpfulVote, EditorToolbar,
DocumentTag, ReviewTag, Attachment,
DocumentRenderingInProgress,
@@ -220,7 +221,8 @@ def _added_header(request, *args, **kwargs):
def _format_attachment_obj(attachments):
attachments_list = []
for attachment in attachments:
- html = jingo.get_env().select_template(['wiki/includes/attachment_row.html'])
+ html = jingo.get_env().select_template(
+ ['wiki/includes/attachment_row.html'])
obj = {
'title': attachment.title,
'date': str(attachment.current_revision.created),
@@ -228,7 +230,7 @@ def _format_attachment_obj(attachments):
'url': attachment.get_file_url(),
'size': 0,
'creator': attachment.current_revision.creator.username,
- 'creatorUrl': reverse('devmo.views.profile_view',
+ 'creatorUrl': reverse('devmo.views.profile_view',
args=[attachment.current_revision.creator]),
'revision': attachment.current_revision.id,
'id': attachment.id,
@@ -241,7 +243,7 @@ def _format_attachment_obj(attachments):
except:
pass
- obj['html'] = mark_safe(html.render({ 'attachment': obj }))
+ obj['html'] = mark_safe(html.render({'attachment': obj}))
attachments_list.append(obj)
return attachments_list
@@ -264,6 +266,7 @@ def _join_slug(parent_split, slug):
parent_split.append(slug)
return '/'.join(parent_split)
+
def _get_document_for_json(doc, addLocaleToTitle=False):
"""Returns a document in object format for output as JSON"""
content = (wiki.content.parse(doc.html)
@@ -283,7 +286,8 @@ def _get_document_for_json(doc, addLocaleToTitle=False):
translations.append({
'locale': translation.locale,
'title': translation.title,
- 'url': reverse('wiki.document', args=[translation.full_path], locale=translation.locale)
+ 'url': reverse('wiki.document', args=[translation.full_path],
+ locale=translation.locale)
})
return {
@@ -301,13 +305,13 @@ def _get_document_for_json(doc, addLocaleToTitle=False):
def get_seo_description(content):
# Create an SEO summary
- # TODO: Google only takes the first 180 characters, so maybe we find a logical
- # way to find the end of sentence before 180?
+ # TODO: Google only takes the first 180 characters, so maybe we find a
+ # logical way to find the end of sentence before 180?
seo_summary = ''
try:
if content:
- # Need to add a BR to the page content otherwise pyQuery wont find a
- # <p></p> element if it's the only element in the doc_html
+ # Need to add a BR to the page content otherwise pyQuery wont find
+ # a <p></p> element if it's the only element in the doc_html
seo_analyze_doc_html = content + '<br />'
page = pq(seo_analyze_doc_html)
@@ -321,12 +325,12 @@ def get_seo_description(content):
for p in range(len(paragraphs)):
item = paragraphs.eq(p)
text = item.text()
- # Checking for a parent length of 2
+ # Checking for a parent length of 2
# because we don't want p's wrapped
- # in DIVs ("<div class='warning'>") and pyQuery adds
+ # in DIVs ("<div class='warning'>") and pyQuery adds
# "<html><div>" wrapping to entire document
- if (len(text) and
- not 'Redirect' in text and
+ if (len(text) and
+ not 'Redirect' in text and
text.find(u'«') == -1 and
text.find('&laquo') == -1 and
item.parents().length == 2):
@@ -500,8 +504,9 @@ def set_common_headers(r):
if r_errors:
ks_errors = r_errors
except DocumentRenderedContentNotAvailable:
- # There was no rendered content available, and we were unable to
- # render it on the spot. So, fall back to presenting raw content
+ # There was no rendered content available, and we were unable
+ # to render it on the spot. So, fall back to presenting raw
+ # content
render_raw_fallback = True
toc_html = None
@@ -587,7 +592,7 @@ def set_common_headers(r):
# Retrieve file attachments
attachments = _format_attachment_obj(doc.attachments)
-
+
data = {'document': doc, 'document_html': doc_html, 'toc_html': toc_html,
'redirected_from': redirected_from,
'related': related, 'contributors': contributors,
@@ -725,7 +730,7 @@ def revision(request, document_slug, document_locale, revision_id):
document__slug=document_slug)
prev = rev.get_previous()
- data = {'document': rev.document, 'revision': rev,
+ data = {'document': rev.document, 'revision': rev,
'comment': format_comment(rev)}
data.update(SHOWFOR_DATA)
return jingo.render(request, 'wiki/revision.html', data)
@@ -757,6 +762,7 @@ def list_documents(request, category=None, tag=None):
'category': category,
'tag': tag})
+
@require_GET
def list_templates(request):
"""Returns listing of all templates"""
@@ -879,7 +885,8 @@ def new_document(request):
'show_toc': initial_toc
})
- allow_add_attachment = Attachment.objects.allow_add_attachment_by(request.user)
+ allow_add_attachment = (
+ Attachment.objects.allow_add_attachment_by(request.user))
return jingo.render(request, 'wiki/new_document.html',
{'is_template': is_template,
'parent_slug': parent_slug,
@@ -922,7 +929,8 @@ def new_document(request):
else:
doc_form.data['slug'] = posted_slug
- allow_add_attachment = Attachment.objects.allow_add_attachment_by(request.user)
+ allow_add_attachment = (
+ Attachment.objects.allow_add_attachment_by(request.user))
return jingo.render(request, 'wiki/new_document.html',
{'is_template': is_template,
'document_form': doc_form,
@@ -1003,7 +1011,6 @@ def edit_document(request, document_slug, document_locale, revision_id=None):
except Document.DoesNotExist:
pass
-
# Comparing against localized names for the Save button bothers me, so
# I embedded a hidden input:
which_form = request.POST.get('form')
@@ -1015,9 +1022,10 @@ def edit_document(request, document_slug, document_locale, revision_id=None):
post_data.update({'locale': document_locale})
doc_form = DocumentForm(post_data, instance=doc)
if doc_form.is_valid():
-
- if 'slug' in post_data: # if must be here for section edits
- post_data['slug'] = _join_slug(slug_dict['parent_split'], post_data['slug'])
+ # if must be here for section edits
+ if 'slug' in post_data:
+ post_data['slug'] = _join_slug(
+ slug_dict['parent_split'], post_data['slug'])
# Get the possibly new slug for the imminent redirection:
doc = doc_form.save(None)
@@ -1133,9 +1141,9 @@ def edit_document(request, document_slug, document_locale, revision_id=None):
parent_path = parent_doc.get_absolute_url()
parent_slug = parent_doc.slug
-
attachments = _format_attachment_obj(doc.attachments)
- allow_add_attachment = Attachment.objects.allow_add_attachment_by(request.user)
+ allow_add_attachment = (
+ Attachment.objects.allow_add_attachment_by(request.user))
docInfo = json.dumps(_get_document_for_json(doc))
return jingo.render(request, 'wiki/edit_document.html',
@@ -1257,7 +1265,7 @@ def move(request, document_slug, document_locale):
'descendants': descendants,
'descendants_count': len(descendants),
})
-
+
def ckeditor_config(request):
"""Return ckeditor config from database"""
@@ -1314,23 +1322,24 @@ def _make_doc_structure(d, level):
'url': d.get_absolute_url(),
'subpages': []
}
-
+
if level < depth:
descendants = d.get_descendants(1)
descendants.sort(key=lambda item: item.title)
for descendant in descendants:
- res['subpages'].append(_make_doc_structure(descendant, level + 1))
+ res['subpages'].append(_make_doc_structure(descendant,
+ level + 1))
return res
result = _make_doc_structure(Document.objects.
get(locale=document_locale, slug=document_slug), 0)
except Document.DoesNotExist:
- result = { 'error': 'Document does not exist.' }
+ result = {'error': 'Document does not exist.'}
result = json.dumps(result)
return HttpResponse(result, mimetype='application/json')
-
+
@require_GET
def autosuggest_documents(request):
@@ -1342,7 +1351,7 @@ def autosuggest_documents(request):
# Retrieve all documents that aren't redirects or templates
docs = (Document.objects.
- extra(select={'length':'Length(slug)'}).
+ extra(select={'length': 'Length(slug)'}).
filter(title__icontains=partial_title, is_template=0, is_redirect=0).
exclude(slug__icontains='Talk:'). # Remove old talk pages
order_by('title', 'length'))
@@ -1459,7 +1468,8 @@ def compare_revisions(request, document_slug, document_locale):
context = {'document': doc, 'revision_from': revision_from,
'revision_to': revision_to}
if request.GET.get('raw', 0):
- response = jingo.render(request, 'wiki/includes/revision_diff_table.html',
+ response = jingo.render(request,
+ 'wiki/includes/revision_diff_table.html',
context)
else:
response = jingo.render(request, 'wiki/compare_revisions.html',
@@ -1535,8 +1545,11 @@ def translate(request, document_slug, document_locale, revision_id=None):
# Find the "real" parent topic, which is its translation
try:
- parent_topic_translated_doc = parent_doc.parent_topic.translations.get(locale=document_locale)
- slug_dict = _split_slug(parent_topic_translated_doc.slug + '/' + slug_dict['specific'])
+ parent_topic_translated_doc = (
+ parent_doc.parent_topic.translations.get(
+ locale=document_locale))
+ slug_dict = _split_slug(
+ parent_topic_translated_doc.slug + '/' + slug_dict['specific'])
except:
pass
@@ -1650,7 +1663,8 @@ def translate(request, document_slug, document_locale, revision_id=None):
'locale': document_locale, 'based_on': based_on_rev,
'disclose_description': disclose_description,
'discard_href': discard_href,
- 'specific_slug': parent_split['specific'], 'parent_slug': parent_split['parent']})
+ 'specific_slug': parent_split['specific'],
+ 'parent_slug': parent_split['parent']})
@require_POST
@@ -1771,7 +1785,7 @@ def toc_view(request, document_slug=None, document_locale=None):
if toc_html:
toc_html = '<ol>' + toc_html + '</ol>'
- return HttpResponse(toc_html)
+ return HttpResponse(toc_html)
@require_GET
@@ -1841,7 +1855,7 @@ def revert_document(request, document_path, revision_id):
revision = get_object_or_404(Revision, pk=revision_id,
document__slug=document_slug)
document = revision.document
-
+
if request.method == 'GET':
# Render the confirmation page
return jingo.render(request, 'wiki/confirm_revision_revert.html',
@@ -1850,7 +1864,7 @@ def revert_document(request, document_path, revision_id):
document.revert(revision, request.user)
return HttpResponseRedirect(reverse('wiki.document_revisions',
args=[document.full_path]))
-
+
@login_required
@permission_required('wiki.delete_revision')
@@ -2074,11 +2088,14 @@ def raw_file(request, attachment_id, filename):
attachment = get_object_or_404(Attachment, pk=attachment_id)
if attachment.current_revision is None:
raise Http404
- rev = attachment.current_revision
- resp = HttpResponse(rev.file.read(), mimetype=rev.mime_type)
- resp["Last-Modified"] = rev.created
- resp["Content-Length"] = rev.file.size
- return resp
+ if request.get_host() == settings.ATTACHMENT_HOST:
+ rev = attachment.current_revision
+ resp = HttpResponse(rev.file.read(), mimetype=rev.mime_type)
+ resp["Last-Modified"] = rev.created
+ resp["Content-Length"] = rev.file.size
+ return resp
+ else:
+ return HttpResponsePermanentRedirect(attachment.get_file_url())
def mindtouch_file_redirect(request, file_id, filename):
@@ -2106,6 +2123,7 @@ def attachment_history(request, attachment_id):
{'attachment': attachment,
'revision': attachment.current_revision})
+
@require_POST
@login_required
def new_attachment(request):
@@ -2123,7 +2141,7 @@ def new_attachment(request):
document = Document.objects.get(id=int(document_id))
except (Document.DoesNotExist, ValueError):
pass
-
+
form = AttachmentRevisionForm(data=request.POST, files=request.FILES)
if form.is_valid():
rev = form.save(commit=False)
@@ -2138,8 +2156,10 @@ def new_attachment(request):
rev.filename())
if request.POST.get('is_ajax', ''):
- response = jingo.render(request, 'wiki/includes/attachment_upload_results.html',
- { 'result': json.dumps(_format_attachment_obj([attachment])) })
+ response = jingo.render(
+ request,
+ 'wiki/includes/attachment_upload_results.html',
+ {'result': json.dumps(_format_attachment_obj([attachment]))})
else:
return HttpResponseRedirect(attachment.get_absolute_url())
else:
@@ -2148,8 +2168,10 @@ def new_attachment(request):
'title': request.POST.get('is_ajax', ''),
'error': _(u'The file provided is not valid')
}
- response = jingo.render(request, 'wiki/includes/attachment_upload_results.html',
- { 'result': json.dumps([error_obj]) })
+ response = jingo.render(
+ request,
+ 'wiki/includes/attachment_upload_results.html',
+ {'result': json.dumps([error_obj])})
else:
response = jingo.render(request, 'wiki/edit_attachment.html',
{'form': form})
View
3  docs/installation-vagrant.rst
@@ -72,7 +72,8 @@ Getting up and running
- Add developer-dev.mozilla.org to /etc/hosts::
- echo '192.168.10.55 developer-local.allizom.org' >> /etc/hosts
+ echo '192.168.10.55 developer-local.allizom.org
+ mdn-local.mozillademos.org' >> /etc/hosts
- Everything should be working now, from the host side::
View
1  puppet/files/etc/apache2/conf.d/mozilla-kuma-apache.conf
@@ -16,6 +16,7 @@ WSGISocketPrefix /var/run/wsgi
ServerAlias developer-kumadev.mozilla.org
ServerAlias developer-mdndev.mozilla.org
ServerAlias developer-dev.mozilla.org
+ ServerAlias mdn-local.mozillademos.org
DirectoryIndex index.html
Options -Indexes
View
2  puppet/files/vagrant/settings_local.py
@@ -129,3 +129,5 @@
KUMASCRIPT_URL_TEMPLATE = 'http://localhost:9080/docs/{path}'
STATSD_CLIENT = 'django_statsd.clients.toolbar'
+
+ATTACHMENT_HOST = 'mdn-local.mozillademos.org'
View
2  settings.py
@@ -763,6 +763,8 @@ def JINJA_CONFIG():
# Default storage engine - ours does not preserve filenames
#DEFAULT_FILE_STORAGE = 'upload.storage.RenameFileStorage'
+ATTACHMENT_HOST = 'mdn.mozillademos.org'
+
# Auth and permissions related constants
LOGIN_URL = '/users/login'
LOGOUT_URL = '/users/logout'
Please sign in to comment.
Something went wrong with that request. Please try again.