Exemplo n.º 1
0
    def testPageCorrectness(self):

        self.client.logout()

        #   Check that QSD with desired URL does not exist
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 404)

        #   Create QSD with desired URL
        qsd_rec_new = QuasiStaticData()
        qsd_rec_new.url = 'learn/foo'
        qsd_rec_new.name = "learn:foo"
        qsd_rec_new.author = self.author
        qsd_rec_new.nav_category = NavBarCategory.default()
        qsd_rec_new.content = "Testing 123"
        qsd_rec_new.title = "Test QSD page"
        qsd_rec_new.description = ""
        qsd_rec_new.keywords = ""
        qsd_rec_new.save()

        #   Check that page now exists and has proper content
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        self.assertTrue('Testing 123' in response.content)

        #   Edit QSD and check that page content has updated
        qsd_rec_new.content = "Testing 456"
        qsd_rec_new.save()
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        self.assertTrue('Testing 456' in response.content)
Exemplo n.º 2
0
    def testInlineCorrectness(self):

        self.client.logout()

        #   Create an inline QSD
        qsd_rec_new = QuasiStaticData()
        qsd_rec_new.url = 'learn/bar'
        qsd_rec_new.name = "learn:bar"
        qsd_rec_new.author = self.author
        qsd_rec_new.nav_category = NavBarCategory.default()
        qsd_rec_new.content = "Inline Testing 123"
        qsd_rec_new.title = "Test QSD page"
        qsd_rec_new.description = ""
        qsd_rec_new.keywords = ""
        qsd_rec_new.save()

        #   Render a template that uses the inline_qsd template tag
        template_data = """
            {% load render_qsd %}
            {% render_inline_qsd "learn/bar" %}
        """
        template = Template(template_data)
        response_content = template.render(Context({}))
        self.assertTrue("Inline Testing 123" in response_content)

        #   Update the template and check again
        qsd_rec_new.content = "Inline Testing 456"
        qsd_rec_new.save()
        response_content = template.render(Context({}))
        self.assertTrue("Inline Testing 456" in response_content)

        response_content = template.render(Context({}))
        self.assertTrue("Inline Testing 456" in response_content)
Exemplo n.º 3
0
    def setUp(self):
        SeleniumTestCase.setUp(self)

        # Make Q/Web public
        UserBit.objects.create(verb=GetNode('V/Flags/Public'),
                               qsc=GetNode('Q/Web'))

        # Make our users
        self.admin_user, created = ESPUser.objects.get_or_create(
            username='******', first_name='Harry', last_name='Alborez')
        self.admin_user.set_password(self.PASSWORD_STRING)
        make_user_admin(self.admin_user)
        self.qsd_user, created = ESPUser.objects.get_or_create(
            username='******', first_name='Aylik', last_name='Kewesd')
        self.qsd_user.set_password(self.PASSWORD_STRING)
        self.qsd_user.userbit_set.add(
            UserBit(verb=GetNode('V/Administer/Edit'),
                    qsc=GetNode('Q'),
                    recursive=True))
        self.qsd_user.save()

        # Check that a NavBarCategory exists
        if len(NavBarCategory.objects.all()) < 1:
            nbc = NavBarCategory()
            nbc.name = 'default'
            nbc.save()

        # Make our test page
        qsd_rec_new = QuasiStaticData()
        qsd_rec_new.path = GetNode('Q/Web')
        qsd_rec_new.name = 'test'
        qsd_rec_new.author = self.admin_user
        qsd_rec_new.nav_category = NavBarCategory.default()
        qsd_rec_new.content = ''
        qsd_rec_new.title = 'Test page'
        qsd_rec_new.description = ''
        qsd_rec_new.keywords = ''
        qsd_rec_new.save()

        # Set the port that the webdriver will try to access
        self.driver.testserver_port = settings.VARNISH_PORT

        # Add the varnish_purge tag
        Tag.objects.get_or_create(key='varnish_purge', value='true')

        # Set up the correct site
        site = Site.objects.get_current()
        site.domain = settings.VARNISH_HOST + ":" + str(settings.VARNISH_PORT)
        site.save()
Exemplo n.º 4
0
    def setUp(self):
        super(NoVaryOnCookieTest, self).setUp()

        #   Create a QSD page associated with the program
        from esp.qsd.models import QuasiStaticData
        from esp.web.models import NavBarCategory

        qsd_rec_new = QuasiStaticData()
        qsd_rec_new.name = "learn:index"
        qsd_rec_new.author = self.admins[0]
        qsd_rec_new.nav_category = default_navbarcategory()
        qsd_rec_new.content = "This is the content of the test QSD page"
        qsd_rec_new.title = "Test QSD page"
        qsd_rec_new.description = ""
        qsd_rec_new.keywords = ""
        qsd_rec_new.save()
Exemplo n.º 5
0
    def setUp(self):
        SeleniumTestCase.setUp(self)

        # Make our users
        self.admin_user, created = ESPUser.objects.get_or_create(
            username='******', first_name='Harry', last_name='Alborez')
        self.admin_user.set_password(self.PASSWORD_STRING)
        self.admin_user.makeAdmin()
        self.qsd_user, created = ESPUser.objects.get_or_create(
            username='******', first_name='Aylik', last_name='Kewesd')
        self.qsd_user.set_password(self.PASSWORD_STRING)
        self.qsd_user.save()

        # Check that a NavBarCategory exists
        if len(NavBarCategory.objects.all()) < 1:
            nbc = NavBarCategory()
            nbc.name = 'default'
            nbc.save()

        # Make our test page
        qsd_rec_new = QuasiStaticData()
        qsd_rec_new.url = 'test'
        qsd_rec_new.name = 'test'
        qsd_rec_new.author = self.admin_user
        qsd_rec_new.nav_category = default_navbarcategory()
        qsd_rec_new.content = ''
        qsd_rec_new.title = 'Test page'
        qsd_rec_new.description = ''
        qsd_rec_new.keywords = ''
        qsd_rec_new.save()

        # Set the port that the webdriver will try to access
        self._old_port = self.driver.testserver_port
        self.driver.testserver_port = settings.VARNISH_PORT

        # Add the varnish_purge tag
        Tag.objects.get_or_create(key='varnish_purge', value='true')

        # Set up the correct site
        site = Site.objects.get_current()
        site.domain = settings.VARNISH_HOST + ":" + str(settings.VARNISH_PORT)
        site.save()
Exemplo n.º 6
0
    def testInlineCorrectness(self):

        for user in self.users:
            if user is None:
                self.client.logout()
            else:
                self.client.logout()
                self.client.login(username=user[0], password=user[1])

            #   Create an inline QSD
            qsd_rec_new = QuasiStaticData()
            qsd_rec_new.url = 'learn/bar'
            qsd_rec_new.name = "learn:bar"
            qsd_rec_new.author = self.author
            qsd_rec_new.nav_category = default_navbarcategory()
            qsd_rec_new.content = "Inline Testing 123"
            qsd_rec_new.title = "Test QSD page"
            qsd_rec_new.description = ""
            qsd_rec_new.keywords = ""
            qsd_rec_new.save()

            #   Render a template that uses the inline_qsd template tag
            template_data = """
                {% load render_qsd %}
                {% render_inline_qsd "learn/bar" %}
            """
            template = Template(template_data)
            response_content = template.render(Context({}))
            self.assertTrue("Inline Testing 123" in response_content)

            #   Update the template and check again
            qsd_rec_new.content = "Inline Testing 456"
            qsd_rec_new.save()
            response_content = template.render(Context({}))
            self.assertTrue("Inline Testing 456" in response_content)

            response_content = template.render(Context({}))
            self.assertTrue("Inline Testing 456" in response_content)

            #   Delete it so we can start again
            qsd_rec_new.delete()
Exemplo n.º 7
0
    def setUp(self):
        SeleniumTestCase.setUp(self)

        # Make our users
        self.admin_user, created = ESPUser.objects.get_or_create(username='******', first_name='Harry', last_name='Alborez')
        self.admin_user.set_password(self.PASSWORD_STRING)
        self.admin_user.makeAdmin()
        self.qsd_user, created = ESPUser.objects.get_or_create(username='******', first_name='Aylik', last_name='Kewesd')
        self.qsd_user.set_password(self.PASSWORD_STRING)
        self.qsd_user.save()

        # Check that a NavBarCategory exists
        if len(NavBarCategory.objects.all()) < 1:
            nbc = NavBarCategory()
            nbc.name = 'default'
            nbc.save()

        # Make our test page
        qsd_rec_new = QuasiStaticData()
        qsd_rec_new.url = 'test'
        qsd_rec_new.name = 'test'
        qsd_rec_new.author = self.admin_user
        qsd_rec_new.nav_category = default_navbarcategory()
        qsd_rec_new.content = ''
        qsd_rec_new.title = 'Test page'
        qsd_rec_new.description = ''
        qsd_rec_new.keywords    = ''
        qsd_rec_new.save()

        # Set the port that the webdriver will try to access
        self._old_port = self.driver.testserver_port
        self.driver.testserver_port = settings.VARNISH_PORT

        # Add the varnish_purge tag
        Tag.objects.get_or_create(key='varnish_purge', value='true')

        # Set up the correct site
        site = Site.objects.get_current()
        site.domain = settings.VARNISH_HOST+":"+str(settings.VARNISH_PORT)
        site.save()
Exemplo n.º 8
0
    def backwards(self, orm):
        print "Converting from reversion format to separate-QSD format (this may take a while)..."

        # go through each QuasiStaticData, get reversions, and create new objects for each reversion
        # then delete the object

        qsdObjects = QuasiStaticData.objects.all()
        counter = 0

        for qsd in qsdObjects:
            # reversion.get_for_object will return in descending order by create date
            # but we want to create these objects in the reverse order

            for qsdRevision in reversed(reversion.get_for_object(qsd)):
                if all(k in qsdRevision.field_dict
                       for k in ('url', 'author', 'content', 'title',
                                 'description', 'nav_category', 'keywords',
                                 'disabled', 'create_date')):
                    qsdCopy = QuasiStaticData()
                    qsdCopy.url = qsdRevision.field_dict['url']
                    qsdCopy.author = ESPUser.objects.get(
                        id=qsdRevision.field_dict['author'])
                    qsdCopy.content = qsdRevision.field_dict['content']
                    qsdCopy.title = qsdRevision.field_dict['title']
                    qsdCopy.description = qsdRevision.field_dict['description']
                    qsdCopy.nav_category = NavBarCategory.objects.get(
                        id=qsdRevision.field_dict['nav_category'])
                    qsdCopy.keywords = qsdRevision.field_dict['keywords']
                    qsdCopy.disabled = qsdRevision.field_dict['disabled']
                    qsdCopy.create_date = qsdRevision.revision.date_created
                    qsdCopy.save()

            qsd.delete()

            counter += 1
            if counter % 50 == 0:
                print "... " + str(counter) + "/" + str(len(qsdObjects))

        print "Finished QSD conversion"
Exemplo n.º 9
0
    def testPageCorrectness(self):

        for user in self.users:
            if user is None:
                self.client.logout()
            else:
                self.client.logout()
                self.client.login(username=user[0], password=user[1])

            #   Check that QSD with desired URL does not exist
            response = self.client.get(self.url)
            self.assertEqual(response.status_code, 404)

            #   Create QSD with desired URL
            qsd_rec_new = QuasiStaticData()
            qsd_rec_new.url = 'learn/foo'
            qsd_rec_new.name = "learn:foo"
            qsd_rec_new.author = self.author
            qsd_rec_new.nav_category = default_navbarcategory()
            qsd_rec_new.content = "Testing 123"
            qsd_rec_new.title = "Test QSD page"
            qsd_rec_new.description = ""
            qsd_rec_new.keywords = ""
            qsd_rec_new.save()

            #   Check that page now exists and has proper content
            response = self.client.get(self.url)
            self.assertEqual(response.status_code, 200)
            self.assertTrue('Testing 123' in response.content)

            #   Edit QSD and check that page content has updated
            qsd_rec_new.content = "Testing 456"
            qsd_rec_new.save()
            response = self.client.get(self.url)
            self.assertEqual(response.status_code, 200)
            self.assertTrue('Testing 456' in response.content)

            #   Delete the new QSD so we can start again.
            qsd_rec_new.delete()
Exemplo n.º 10
0
def qsd(request, branch, name, section, action):

    READ_VERB = 'V/Flags/Public'
    EDIT_VERB = 'V/Administer/Edit/QSD'

    if action == 'read':
        base_url = request.path[:-5]
    else:
        base_url = request.path[:(-len(action) - 6)]

    # Detect edit authorizations
    have_read = True

    if not have_read and action == 'read':
        raise Http403, "You do not have permission to access this page."

    # Fetch the QSD object
    try:
        qsd_rec = QuasiStaticData.objects.get_by_path__name(branch, name)
        if qsd_rec == None:
            raise QuasiStaticData.DoesNotExist
        if qsd_rec.disabled:
            raise QuasiStaticData.DoesNotExist

    except QuasiStaticData.DoesNotExist:
        have_edit = UserBit.UserHasPerms(request.user, branch, EDIT_VERB)

        if have_edit:
            if action in (
                    'edit',
                    'create',
            ):
                qsd_rec = QuasiStaticData()
                qsd_rec.path = branch
                qsd_rec.name = name
                qsd_rec.nav_category = NavBarCategory.default()
                qsd_rec.title = 'New Page'
                qsd_rec.content = 'Please insert your text here'
                qsd_rec.create_date = datetime.now()
                qsd_rec.keywords = ''
                qsd_rec.description = ''
                action = 'edit'

            if (action == 'read'):
                edit_link = base_url + '.edit.html'
                return render_to_response('qsd/nopage_edit.html',
                                          request, (branch, section),
                                          {'edit_link': edit_link},
                                          use_request_context=False)
        else:
            if action == 'read':
                raise Http404, 'This page does not exist.'
            else:
                raise Http403, 'Sorry, you can not modify <tt>%s</tt>.' % request.path

    if action == 'create':
        action = 'edit'

    # Detect the standard read verb
    if action == 'read':
        if not have_read:
            raise Http403, 'You do not have permission to read this page.'

        # Render response
        response = render_to_response(
            'qsd/qsd.html',
            request,
            (branch, section),
            {
                'title': qsd_rec.title,
                'nav_category': qsd_rec.nav_category,
                'content': qsd_rec.html(),
                'qsdrec': qsd_rec,
                'have_edit':
                True,  ## Edit-ness is determined client-side these days
                'edit_url': base_url + ".edit.html"
            },
            use_request_context=False)

        #        patch_vary_headers(response, ['Cookie'])
        #        if have_edit:
        #            add_never_cache_headers(response)
        #            patch_cache_control(response, no_cache=True, no_store=True)
        #        else:
        patch_cache_control(response, max_age=3600, public=True)

        return response

    # Detect POST
    if request.POST.has_key('post_edit'):
        have_edit = UserBit.UserHasPerms(request.user, branch, EDIT_VERB)

        if not have_edit:
            raise Http403, "Sorry, you do not have permission to edit this page."

        # Arguably, this should retrieve the DB object, use the .copy()
        # method, and then update it. Doing it this way saves a DB call
        # (and requires me to make fewer changes).
        qsd_rec_new = QuasiStaticData()
        qsd_rec_new.path = branch
        qsd_rec_new.name = name
        qsd_rec_new.author = request.user
        qsd_rec_new.nav_category = NavBarCategory.objects.get(
            id=request.POST['nav_category'])
        qsd_rec_new.content = request.POST['content']
        qsd_rec_new.title = request.POST['title']
        qsd_rec_new.description = request.POST['description']
        qsd_rec_new.keywords = request.POST['keywords']
        qsd_rec_new.save()

        # We should also purge the cache
        purge_page(qsd_rec_new.url())

        qsd_rec = qsd_rec_new

        # If any files were uploaded, save them
        for name, file in request.FILES.iteritems():
            m = Media()

            # Strip "media/" from FILE, and strip the file name; just return the path
            path = dirname(name[9:])
            if path == '':
                m.anchor = qsd_rec.path
            else:
                m.anchor = GetNode('Q/' + dirname(name))

            # Do we want a better/manual mechanism for setting friendly_name?
            m.friendly_name = basename(name)

            m.format = ''

            local_filename = name
            if name[:9] == 'qsdmedia/':
                local_filename = name[9:]

            m.handle_file(file, local_filename)
            m.save()

    # Detect the edit verb
    if action == 'edit':
        have_edit = UserBit.UserHasPerms(request.user, branch, EDIT_VERB)

        # Enforce authorizations (FIXME: SHOW A REAL ERROR!)
        if not have_edit:
            raise ESPError(
                False), "You don't have permission to edit this page."

        m = ESPMarkdown(qsd_rec.content, media={})

        m.toString()
        #        assert False, m.BrokenLinks()

        # Render an edit form
        return render_to_response(
            'qsd/qsd_edit.html',
            request, (branch, section), {
                'title': qsd_rec.title,
                'content': qsd_rec.content,
                'keywords': qsd_rec.keywords,
                'description': qsd_rec.description,
                'nav_category': qsd_rec.nav_category,
                'nav_categories': NavBarCategory.objects.all(),
                'qsdrec': qsd_rec,
                'qsd': True,
                'missing_files': m.BrokenLinks(),
                'target_url': base_url.split("/")[-1] + ".edit.html",
                'return_to_view': base_url.split("/")[-1] + ".html"
            },
            use_request_context=False)

    # Operation Complete!
    raise Http404('Unexpected QSD operation')
Exemplo n.º 11
0
def qsd(request, url):

    #   Extract the 'action' from the supplied URL if there is one
    url_parts = url.split('/')
    page_name = url_parts[-1]
    page_name_parts = page_name.split('.')
    if len(page_name_parts) > 1:
        action = page_name_parts[-1]
        page_name_base = '.'.join(page_name_parts[:-1])
    else:
        action = 'read'
        page_name_base = page_name
    base_url = '/'.join(url_parts[:-1] + [page_name_base])

    # Detect edit authorizations
    have_read = True

    if not have_read and action == 'read':
        raise Http403, "You do not have permission to access this page."

    # Fetch the QSD object
    try:
        qsd_rec = QuasiStaticData.objects.get_by_url(base_url)
        if qsd_rec == None:
            raise QuasiStaticData.DoesNotExist
        if qsd_rec.disabled:
            raise QuasiStaticData.DoesNotExist

    except QuasiStaticData.DoesNotExist:
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        if have_edit:
            if action in (
                    'edit',
                    'create',
            ):
                qsd_rec = QuasiStaticData()
                qsd_rec.url = base_url
                qsd_rec.nav_category = NavBarCategory.default()
                qsd_rec.title = 'New Page'
                qsd_rec.content = 'Please insert your text here'
                qsd_rec.create_date = datetime.now()
                qsd_rec.keywords = ''
                qsd_rec.description = ''
                action = 'edit'

            if (action == 'read'):
                edit_link = '/' + base_url + '.edit.html'
                return render_to_response('qsd/nopage_create.html',
                                          request, {'edit_link': edit_link},
                                          use_request_context=False)
        else:
            if action == 'read':
                raise Http404, 'This page does not exist.'
            else:
                raise Http403, 'Sorry, you can not modify <tt>%s</tt>.' % request.path

    if action == 'create':
        action = 'edit'

    # Detect the standard read verb
    if action == 'read':
        if not have_read:
            raise Http403, 'You do not have permission to read this page.'

        # Render response
        response = render_to_response(
            'qsd/qsd.html',
            request,
            {
                'title': qsd_rec.title,
                'nav_category': qsd_rec.nav_category,
                'content': qsd_rec.html(),
                'settings': settings,
                'qsdrec': qsd_rec,
                'have_edit':
                True,  ## Edit-ness is determined client-side these days
                'edit_url': '/' + base_url + ".edit.html"
            },
            use_request_context=False)

        #        patch_vary_headers(response, ['Cookie'])
        #        if have_edit:
        #            add_never_cache_headers(response)
        #            patch_cache_control(response, no_cache=True, no_store=True)
        #        else:
        patch_cache_control(response, max_age=3600, public=True)

        return response

    # Detect POST
    if request.POST.has_key('post_edit'):
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        if not have_edit:
            raise Http403, "Sorry, you do not have permission to edit this page."

        nav_category_target = NavBarCategory.objects.get(
            id=request.POST['nav_category'])

        # Since QSD now uses reversion, we want to only modify the data if we've actually changed something
        # The revision will automatically be created upon calling the save function of the model object
        if qsd_rec.url != base_url or qsd_rec.nav_category != nav_category_target or qsd_rec.content != request.POST[
                'content'] or qsd_rec.description != request.POST[
                    'description'] or qsd_rec.keywords != request.POST[
                        'keywords']:
            qsd_rec.url = base_url
            qsd_rec.nav_category = NavBarCategory.objects.get(
                id=request.POST['nav_category'])
            qsd_rec.content = request.POST['content']
            qsd_rec.title = request.POST['title']
            qsd_rec.description = request.POST['description']
            qsd_rec.keywords = request.POST['keywords']

            qsd_rec.load_cur_user_time(request)
            qsd_rec.save()

            # We should also purge the cache
            purge_page(qsd_rec.url + ".html")

        # If any files were uploaded, save them
        for name, file in request.FILES.iteritems():
            m = Media()

            # Strip "media/" from FILE, and strip the file name; just return the path
            path = dirname(name[9:])

            # Do we want a better/manual mechanism for setting friendly_name?
            m.friendly_name = basename(name)

            m.format = ''

            local_filename = name
            if name[:9] == 'qsdmedia/':
                local_filename = name[9:]

            m.handle_file(file, local_filename)
            m.save()

    # Detect the edit verb
    if action == 'edit':
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        # Enforce authorizations (FIXME: SHOW A REAL ERROR!)
        if not have_edit:
            raise ESPError(
                False), "You don't have permission to edit this page."

        m = ESPMarkdown(qsd_rec.content, media={})

        m.toString()
        #        assert False, m.BrokenLinks()

        # Render an edit form
        return render_to_response(
            'qsd/qsd_edit.html',
            request, {
                'title': qsd_rec.title,
                'content': qsd_rec.content,
                'keywords': qsd_rec.keywords,
                'description': qsd_rec.description,
                'nav_category': qsd_rec.nav_category,
                'nav_categories': NavBarCategory.objects.all(),
                'qsdrec': qsd_rec,
                'qsd': True,
                'missing_files': m.BrokenLinks(),
                'target_url': base_url.split("/")[-1] + ".edit.html",
                'return_to_view': base_url.split("/")[-1] + ".html#refresh"
            },
            use_request_context=False)

    # Operation Complete!
    raise Http404('Unexpected QSD operation')
Exemplo n.º 12
0
def qsd(request, url):

    #   Extract the 'action' from the supplied URL if there is one
    url_parts = url.split('/')
    page_name = url_parts[-1]
    page_name_parts = page_name.split('.')
    if len(page_name_parts) > 1:
        action = page_name_parts[-1]
        page_name_base = '.'.join(page_name_parts[:-1])
    else:
        action = 'read'
        page_name_base = page_name
    base_url = '/'.join(url_parts[:-1] + [page_name_base])

    # Detect edit authorizations
    have_read = True

    if not have_read and action == 'read':
        raise Http403, "You do not have permission to access this page."

    # Fetch the QSD object
    try:
        qsd_rec = QuasiStaticData.objects.get_by_url(base_url)
        if qsd_rec == None:
            raise QuasiStaticData.DoesNotExist
        if qsd_rec.disabled:
            raise QuasiStaticData.DoesNotExist

    except QuasiStaticData.DoesNotExist:
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        if have_edit:
            if action in ('edit','create',):
                qsd_rec = QuasiStaticData()
                qsd_rec.url = base_url
                qsd_rec.nav_category = default_navbarcategory()
                qsd_rec.title = 'New Page'
                qsd_rec.content = 'Please insert your text here'
                qsd_rec.create_date = datetime.now()
                qsd_rec.keywords = ''
                qsd_rec.description = ''
                action = 'edit'

            if (action == 'read'):
                edit_link = '/' + base_url + '.edit.html'
                response = render_to_response('qsd/nopage_create.html', request, {'edit_link': edit_link}, use_request_context=False)
                response.status_code = 404 # Make sure we actually 404, so that if there is a redirect the middleware can catch it.
                return response
        else:
            if action == 'read':
                raise Http404, 'This page does not exist.'
            else:
                raise Http403, 'Sorry, you can not modify <tt>%s</tt>.' % request.path

    if action == 'create':
        action = 'edit'

    # Detect the standard read verb
    if action == 'read':
        if not have_read:
            raise Http403, 'You do not have permission to read this page.'

        # Render response
        response = render_to_response('qsd/qsd.html', request, {
            'title': qsd_rec.title,
            'nav_category': qsd_rec.nav_category,
            'content': qsd_rec.html(),
            'settings': settings,
            'qsdrec': qsd_rec,
            'have_edit': True,  ## Edit-ness is determined client-side these days
            'edit_url': '/' + base_url + ".edit.html" }, use_request_context=False)

#        patch_vary_headers(response, ['Cookie'])
#        if have_edit:
#            add_never_cache_headers(response)
#            patch_cache_control(response, no_cache=True, no_store=True)
#        else:
        patch_cache_control(response, max_age=3600, public=True)

        return response


    # Detect POST
    if 'post_edit' in request.POST:
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        if not have_edit:
            raise Http403, "Sorry, you do not have permission to edit this page."

        nav_category_target = NavBarCategory.objects.get(id=request.POST['nav_category'])

        # Since QSD now uses reversion, we want to only modify the data if we've actually changed something
        # The revision will automatically be created upon calling the save function of the model object
        copy_map = {
            'url': base_url,
            'nav_category': nav_category_target,
            'content': request.POST['content'],
            'title': request.POST['title'],
            'description': request.POST['description'],
            'keywords': request.POST['keywords'],
        }
        diff_found = False
        for field, new_value in copy_map.items():
            if getattr(qsd_rec, field) != new_value:
                setattr(qsd_rec, field, new_value)
                diff_found = True

        if diff_found:
            qsd_rec.load_cur_user_time(request)
            qsd_rec.save()

            # We should also purge the cache
            purge_page(qsd_rec.url+".html")


    # Detect the edit verb
    if action == 'edit':
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        # Enforce authorizations (FIXME: SHOW A REAL ERROR!)
        if not have_edit:
            raise Http403, "You don't have permission to edit this page."

        # Render an edit form
        return render_to_response('qsd/qsd_edit.html', request, {
            'title'        : qsd_rec.title,
            'content'      : qsd_rec.content,
            'keywords'     : qsd_rec.keywords,
            'description'  : qsd_rec.description,
            'nav_category' : qsd_rec.nav_category,
            'nav_categories': NavBarCategory.objects.all(),
            'qsdrec'       : qsd_rec,
            'qsd'          : True,
            'target_url'   : base_url.split("/")[-1] + ".edit.html",
            'return_to_view': base_url.split("/")[-1] + ".html#refresh" },
            use_request_context=False)

    # Operation Complete!
    raise Http404('Unexpected QSD operation')
Exemplo n.º 13
0
def qsd(request, url):

    #   Extract the 'action' from the supplied URL if there is one
    url_parts = url.split('/')
    page_name = url_parts[-1]
    page_name_parts = page_name.split('.')
    if len(page_name_parts) > 1:
        action = page_name_parts[-1]
        page_name_base = '.'.join(page_name_parts[:-1])
    else:
        action = 'read'
        page_name_base = page_name
    base_url = '/'.join(url_parts[:-1] + [page_name_base])

    # Detect edit authorizations
    have_read = True

    if not have_read and action == 'read':
        raise Http403, "You do not have permission to access this page."

    # Fetch the QSD object
    try:
        qsd_rec = QuasiStaticData.objects.get_by_url(base_url)
        if qsd_rec == None:
            raise QuasiStaticData.DoesNotExist
        if qsd_rec.disabled:
            raise QuasiStaticData.DoesNotExist

    except QuasiStaticData.DoesNotExist:
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        if have_edit:
            if action in ('edit','create',):
                qsd_rec = QuasiStaticData()
                qsd_rec.url = base_url
                qsd_rec.nav_category = default_navbarcategory()
                qsd_rec.title = 'New Page'
                qsd_rec.content = 'Please insert your text here'
                qsd_rec.create_date = datetime.now()
                qsd_rec.keywords = ''
                qsd_rec.description = ''
                action = 'edit'

            if (action == 'read'):
                edit_link = '/' + base_url + '.edit.html'
                response = render_to_response('qsd/nopage_create.html', request, {'edit_link': edit_link}, use_request_context=False)
                response.status_code = 404 # Make sure we actually 404, so that if there is a redirect the middleware can catch it.
                return response
        else:
            if action == 'read':
                raise Http404, 'This page does not exist.'
            else:
                raise Http403, 'Sorry, you can not modify <tt>%s</tt>.' % request.path

    if action == 'create':
        action = 'edit'

    # Detect the standard read verb
    if action == 'read':
        if not have_read:
            raise Http403, 'You do not have permission to read this page.'

        # Render response
        response = render_to_response('qsd/qsd.html', request, {
            'title': qsd_rec.title,
            'nav_category': qsd_rec.nav_category,
            'content': qsd_rec.html(),
            'settings': settings,
            'qsdrec': qsd_rec,
            'have_edit': True,  ## Edit-ness is determined client-side these days
            'edit_url': '/' + base_url + ".edit.html" }, use_request_context=False)

#        patch_vary_headers(response, ['Cookie'])
#        if have_edit:
#            add_never_cache_headers(response)
#            patch_cache_control(response, no_cache=True, no_store=True)
#        else:
        patch_cache_control(response, max_age=3600, public=True)

        return response


    # Detect POST
    if 'post_edit' in request.POST:
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        if not have_edit:
            raise Http403, "Sorry, you do not have permission to edit this page."

        nav_category_target = NavBarCategory.objects.get(id=request.POST['nav_category'])

        # Since QSD now uses reversion, we want to only modify the data if we've actually changed something
        # The revision will automatically be created upon calling the save function of the model object
        copy_map = {
            'url': base_url,
            'nav_category': nav_category_target,
            'content': request.POST['content'],
            'title': request.POST['title'],
            'description': request.POST['description'],
            'keywords': request.POST['keywords'],
        }
        diff_found = False
        for field, new_value in copy_map.items():
            if getattr(qsd_rec, field) != new_value:
                setattr(qsd_rec, field, new_value)
                diff_found = True

        if diff_found:
            qsd_rec.load_cur_user_time(request)
            qsd_rec.save()

            # We should also purge the cache
            purge_page(qsd_rec.url+".html")


    # Detect the edit verb
    if action == 'edit':
        have_edit = Permission.user_can_edit_qsd(request.user, base_url)

        # Enforce authorizations (FIXME: SHOW A REAL ERROR!)
        if not have_edit:
            raise Http403, "You don't have permission to edit this page."

        # Render an edit form
        return render_to_response('qsd/qsd_edit.html', request, {
            'title'        : qsd_rec.title,
            'content'      : qsd_rec.content,
            'keywords'     : qsd_rec.keywords,
            'description'  : qsd_rec.description,
            'nav_category' : qsd_rec.nav_category,
            'nav_categories': NavBarCategory.objects.all(),
            'qsdrec'       : qsd_rec,
            'qsd'          : True,
            'target_url'   : base_url.split("/")[-1] + ".edit.html",
            'return_to_view': base_url.split("/")[-1] + ".html#refresh" },
            use_request_context=False)

    # Operation Complete!
    raise Http404('Unexpected QSD operation')