Beispiel #1
0
 def get_class(self, el):
     href = el.get("href")
     if not href:
         return
     # The autolinker turns email links into links with many HTML entities.
     # These entities are further escaped using markdown-specific codes.
     # First unescape the markdown-specific, then use html.unescape.
     href = AndSubstitutePostprocessor().run(href)
     href = html.unescape(href)
     try:
         url = urlparse(href)
     except ValueError:
         return
     if url.scheme == "mailto":
         return
     if url.scheme or url.netloc or url.path.startswith("/"):
         # Contains a hostname or is an absolute link => external
         return self.external_class
     # Ensure that path ends with a slash
     relpath = url.path.rstrip("/") + "/"
     target = urljoin_internal(self.my_urlpath.path, relpath)
     if target is None:
         # Relative path goes outside wiki URL space => external
         return self.external_class
     try:
         URLPath.get_by_path(target)
     except URLPath.DoesNotExist:
         return self.broken_class
     return self.internal_class
Beispiel #2
0
 def get_class(self, el):
     href = el.get("href")
     if not href:
         return
     # The autolinker turns email links into links with many HTML entities.
     # These entities are further escaped using markdown-specific codes.
     # First unescape the markdown-specific, then use html.unescape.
     href = AndSubstitutePostprocessor().run(href)
     href = html.unescape(href)
     try:
         url = urlparse(href)
     except ValueError:
         return
     if url.scheme == "mailto":
         return
     if url.scheme or url.netloc or url.path.startswith("/"):
         # Contains a hostname or is an absolute link => external
         return self.external_class
     # Ensure that path ends with a slash
     relpath = url.path.rstrip("/") + "/"
     target = urljoin_internal(self.my_urlpath.path, relpath)
     if target is None:
         # Relative path goes outside wiki URL space => external
         return self.external_class
     try:
         URLPath.get_by_path(target)
     except URLPath.DoesNotExist:
         return self.broken_class
     return self.internal_class
Beispiel #3
0
def unitgroup(request: HttpRequest, pk: int) -> HttpResponse:
    group = UnitGroup.objects.get(pk=pk)

    if group.subject == "A" or group.subject == "F":
        subject_name = 'algebra'
    elif group.subject == "C":
        subject_name = 'combinatorics'
    elif group.subject == "G":
        subject_name = 'geometry'
    elif group.subject == "N":
        subject_name = 'number-theory'
    elif group.subject == "M":
        subject_name = 'miscellaneous'
    elif group.subject == "K":
        subject_name = 'null'
    else:
        raise Exception(f"No subject for {group.name}.")

    slug = slugify(group.name)
    try:
        u = URLPath.get_by_path(
            path=f'/units/list-of-{subject_name}-units/{slug}')
    except URLPath.DoesNotExist:
        parent = URLPath.get_by_path(
            path=f'/units/list-of-{subject_name}-units/')
        content = f'[unit {group.slug}]' + '\n' + '[/unit]' + '\n' * 2
        content += f'(This is an automatically generated article for {group.name}. Please add some content!)' + '\n' * 2
        u = URLPath.create_urlpath(
            parent=parent,
            slug=slug,
            title=group.name,
            request=request,
            content=content,
        )
    return wiki_redirect(u)
Beispiel #4
0
def get_urlpath(course_id):
    """Returns url path of root wiki page for course."""
    # Offical edX way to replace slashes by dots: course_key.replace('/', '.')
    course_key = CourseKey.from_string(course_id)
    course = get_course_by_id(course_key)
    course_slug = course_wiki_slug(course)
    try:
        urlpath = URLPath.get_by_path(course_slug)
    except URLPath.DoesNotExist:
        urlpath = None
    return urlpath
Beispiel #5
0
def create(path, title, content, user=None, message=""):
    """
    Create a new wiki page.

    Args:
        path (str): the page's new path (must be unusued).
        title (str): the title of the new page.
        content (str): the new page's content.
        user (Account, optional): the new page's owner.
        message (str, optional): the new revision's message.

    Returns:
        article (Artidcle): the new article.

    Notes:
        If `user` is unset, use Account #1 (the superuser).
        If `slug` is unset, use the path.

        The provided path is an URL.  The parent is taken to be the
        one before the last '/' sign.  For example: 'a/b/c/' as a
        path would mean 'a/b' is taken to mean the parent, and 'c'
        is taken to be the article's new slug.

    """
    print "Try to create a wiki page..."
    path = path.strip("/")
    if "/" in path:
        parent_path, slug = path.rsplit("/", 1)
    else:
        parent_path = ""
        slug = path
    parent = URLPath.get_by_path(parent_path)

    user = user or AccountDB.objects.get(id=1)
    newpath = URLPath.create_article(
        parent,
        slug,
        title=title,
        content=content,
        user_message=message,
        user=user,
        ip_address="127.0.0.1",
        article_kwargs={'owner': user,
                        'group': None,
                        'group_read': True,
                        'group_write': True,
                        'other_read': False,
                        'other_write': False,
                        })

    return newpath.article
Beispiel #6
0
def article_toc(article_slug=None):
    article = None
    if not article_slug:
        root = URLPath.root()
        article = root.article
    else:
        urlpath = URLPath.get_by_path(article_slug, select_related=True)
        article = urlpath.article
    toc_tree = article.get_children(
        article__current_revision__deleted=False)
    return {
        'article_children': toc_tree,
        'article': article,
        'article_path': article_slug + "/",
    }
def inner_article_toc(article_slug=None, dropdown=True, current_article=None):
    article = None
    if not article_slug:
        root = URLPath.root()
        article = root.article
    else:
        urlpath = URLPath.get_by_path(article_slug, select_related=True)
        article = urlpath.article
    toc_tree = get_article_children(article,
                                    article__current_revision__deleted=False)
    return {
        'article_children': toc_tree,
        'article_parent': article,
        'article_path': article_slug + "/",
        'is_dropdown': dropdown,
        'current_article': current_article,
    }
Beispiel #8
0
def get_URI(uri):
    """
    Return the wiki article (Article) to a given URI.

    Args:
        uri (str): the URI (a page URI).

    Returns:
        article (Article or None): the article, if found, or None.

    Example:
        article = get("/facts")

    """
    try:
        path = URLPath.get_by_path(uri)
    except URLPath.DoesNotExist:
        return None

    return path.article
Beispiel #9
0
    def create_article(self,
                       parent_path,
                       title,
                       slug,
                       content,
                       message,
                       user=None):
        parent = URLPath.get_by_path(parent_path)

        # title = 'This is article ONE'
        # slug = slugify(title)
        # content = 'body text etc'
        # message = 'user message??'

        if not user:
            user = User.objects.get(id=1)

        try:
            newpath = URLPath.create_urlpath(parent,
                                             slug,
                                             title=title,
                                             content=content,
                                             user_message=message,
                                             user=user,
                                             ip_address="127.0.0.1",
                                             article_kwargs={
                                                 'owner': user,
                                                 'group': None,
                                                 'group_read': True,
                                                 'group_write': True,
                                                 'other_read': False,
                                                 'other_write': False,
                                             })
            return newpath
        except Exception as e1:
            print(e1)

        return None
Beispiel #10
0
    def test_move(self):
        # Create a hierarchy of pages
        self.client.post(resolve_url('wiki:create', path=''), {
            'title': 'Test',
            'slug': 'test0',
            'content': 'Content .0.'
        })
        self.client.post(resolve_url('wiki:create', path='test0/'), {
            'title': 'Test00',
            'slug': 'test00',
            'content': 'Content .00.'
        })
        self.client.post(resolve_url('wiki:create', path=''), {
            'title': 'Test1',
            'slug': 'test1',
            'content': 'Content .1.'
        })
        self.client.post(resolve_url('wiki:create', path='test1/'), {
            'title': 'Tes10',
            'slug': 'test10',
            'content': 'Content .10.'
        })
        self.client.post(resolve_url('wiki:create', path='test1/test10/'), {
            'title': 'Test100',
            'slug': 'test100',
            'content': 'Content .100.'
        })

        # Move /test1 => /test0 (an already existing destination slug!)
        response = self.client.post(
            resolve_url('wiki:move', path='test1/'), {
                'destination': str(URLPath.root().article.current_revision.id),
                'slug': 'test0',
                'redirect': ''
            })
        self.assertContains(response, 'A slug named')
        self.assertContains(response, 'already exists.')

        # Move /test1 >= /test2 (valid slug), no redirect
        test0_id = URLPath.objects.get(
            slug='test0').article.current_revision.id
        response = self.client.post(resolve_url('wiki:move', path='test1/'), {
            'destination': str(test0_id),
            'slug': 'test2',
            'redirect': ''
        })
        self.assertRedirects(response,
                             resolve_url('wiki:get', path='test0/test2/'))

        # Check that there is no article displayed in this path anymore
        response = self.get_by_path('test1/')
        self.assertRedirects(response, '/_create/?slug=test1')

        # Create /test0/test2/test020
        response = self.client.post(
            resolve_url('wiki:create', path='test0/test2/'), {
                'title': 'Test020',
                'slug': 'test020',
                'content': 'Content .020.'
            })
        # Move /test0/test2 => /test1new + create redirect
        response = self.client.post(
            resolve_url('wiki:move', path='test0/test2/'), {
                'destination': str(URLPath.root().article.current_revision.id),
                'slug': 'test1new',
                'redirect': 'true'
            })
        self.assertRedirects(response, resolve_url('wiki:get',
                                                   path='test1new/'))

        # Check that /test1new is a valid path
        response = self.get_by_path('test1new/')
        self.assertContains(response, 'Content .1.')

        # Check that the child article test0/test2/test020 was also moved
        response = self.get_by_path('test1new/test020/')
        self.assertContains(response, 'Content .020.')

        response = self.get_by_path('test0/test2/')
        self.assertContains(response, 'Moved: Test1')
        self.assertContains(response, 'moved to <a>wiki:/test1new/')

        response = self.get_by_path('test0/test2/test020/')
        self.assertContains(response, 'Moved: Test020')
        self.assertContains(response, 'moved to <a>wiki:/test1new/test020')

        # Check that moved_to was correctly set
        urlsrc = URLPath.get_by_path('/test0/test2/')
        urldst = URLPath.get_by_path('/test1new/')
        self.assertEqual(urlsrc.moved_to, urldst)

        # Check that moved_to was correctly set on the child's previous path
        urlsrc = URLPath.get_by_path('/test0/test2/test020/')
        urldst = URLPath.get_by_path('/test1new/test020/')
        self.assertEqual(urlsrc.moved_to, urldst)
Beispiel #11
0
def course_wiki_redirect(request, course_id):  # pylint: disable=unused-argument
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    course_slug = course_wiki_slug(course)

    valid_slug = True
    if not course_slug:
        log.exception("This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match(r'^[-\w\.]+$', course_slug) is None:
        log.exception("This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens.")
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")

    # The wiki needs a Site object created. We make sure it exists here
    try:
        Site.objects.get_current()
    except Site.DoesNotExist:
        new_site = Site()
        new_site.domain = settings.SITE_NAME
        new_site.name = "edX"
        new_site.save()
        site_id = str(new_site.id)
        if site_id != str(settings.SITE_ID):
            msg = "No site object was created and the SITE_ID doesn't match the newly created one. {} != {}".format(
                site_id, settings.SITE_ID
            )
            raise ImproperlyConfigured(msg)

    try:
        urlpath = URLPath.get_by_path(course_slug, select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        content = cgi.escape(
            # Translators: this string includes wiki markup.  Leave the ** and the _ alone.
            _("This is the wiki for **{organization}**'s _{course_name}_.").format(
                organization=course.display_org_with_default,
                course_name=course.display_name_with_default_escaped,
            )
        )
        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course_slug,
            content=content,
            user_message=_("Course page automatically created."),
            user=None,
            ip_address=None,
            article_kwargs={'owner': None,
                            'group': None,
                            'group_read': True,
                            'group_write': True,
                            'other_read': True,
                            'other_write': True,
                            })

    return redirect("wiki:get", path=urlpath.path)
Beispiel #12
0
    def test_move(self):
        # Create a hierarchy of pages
        self.client.post(
            resolve_url("wiki:create", path=""),
            {
                "title": "Test",
                "slug": "test0",
                "content": "Content .0."
            },
        )
        self.client.post(
            resolve_url("wiki:create", path="test0/"),
            {
                "title": "Test00",
                "slug": "test00",
                "content": "Content .00."
            },
        )
        self.client.post(
            resolve_url("wiki:create", path=""),
            {
                "title": "Test1",
                "slug": "test1",
                "content": "Content .1."
            },
        )
        self.client.post(
            resolve_url("wiki:create", path="test1/"),
            {
                "title": "Tes10",
                "slug": "test10",
                "content": "Content .10."
            },
        )
        self.client.post(
            resolve_url("wiki:create", path="test1/test10/"),
            {
                "title": "Test100",
                "slug": "test100",
                "content": "Content .100."
            },
        )

        # Move /test1 => /test0 (an already existing destination slug!)
        response = self.client.post(
            resolve_url("wiki:move", path="test1/"),
            {
                "destination": str(URLPath.root().article.current_revision.id),
                "slug": "test0",
                "redirect": "",
            },
        )
        self.assertContains(response, "A slug named")
        self.assertContains(response, "already exists.")

        # Move /test1 >= /test2 (valid slug), no redirect
        test0_id = URLPath.objects.get(
            slug="test0").article.current_revision.id
        response = self.client.post(
            resolve_url("wiki:move", path="test1/"),
            {
                "destination": str(test0_id),
                "slug": "test2",
                "redirect": ""
            },
        )
        self.assertRedirects(response,
                             resolve_url("wiki:get", path="test0/test2/"))

        # Check that there is no article displayed in this path anymore
        response = self.get_by_path("test1/")
        self.assertRedirects(response, "/_create/?slug=test1")

        # Create /test0/test2/test020
        response = self.client.post(
            resolve_url("wiki:create", path="test0/test2/"),
            {
                "title": "Test020",
                "slug": "test020",
                "content": "Content .020."
            },
        )
        # Move /test0/test2 => /test1new + create redirect
        response = self.client.post(
            resolve_url("wiki:move", path="test0/test2/"),
            {
                "destination": str(URLPath.root().article.current_revision.id),
                "slug": "test1new",
                "redirect": "true",
            },
        )
        self.assertRedirects(response, resolve_url("wiki:get",
                                                   path="test1new/"))

        # Check that /test1new is a valid path
        response = self.get_by_path("test1new/")
        self.assertContains(response, "Content .1.")

        # Check that the child article test0/test2/test020 was also moved
        response = self.get_by_path("test1new/test020/")
        self.assertContains(response, "Content .020.")

        response = self.get_by_path("test0/test2/")
        self.assertContains(response, "Moved: Test1")
        self.assertRegex(response.rendered_content,
                         r"moved to <a[^>]*>wiki:/test1new/")

        response = self.get_by_path("test0/test2/test020/")
        self.assertContains(response, "Moved: Test020")
        self.assertRegex(response.rendered_content,
                         r"moved to <a[^>]*>wiki:/test1new/test020")

        # Check that moved_to was correctly set
        urlsrc = URLPath.get_by_path("/test0/test2/")
        urldst = URLPath.get_by_path("/test1new/")
        self.assertEqual(urlsrc.moved_to, urldst)

        # Check that moved_to was correctly set on the child's previous path
        urlsrc = URLPath.get_by_path("/test0/test2/test020/")
        urldst = URLPath.get_by_path("/test1new/test020/")
        self.assertEqual(urlsrc.moved_to, urldst)
Beispiel #13
0
    def get_context_data(self, tag, **kwargs):
        context = super(TagPageView, self).get_context_data(**kwargs)

        current_site = Site.objects.get_current()
        current_language_code = translation.get_language()

        tag_instance = get_tag(tag)
        if tag_instance is None:
            raise Http404(_('No Tag found matching "%s".') % tag)

        try:
            article = Article.get_for_object(tag_instance)
        except ArticleForObject.DoesNotExist:
            # Get or create root
            try:
                root_path = URLPath.root()
            except NoRootURL:
                root_path = URLPath.create_root(site=current_site)

            # Get current language namespace. E.g. "/fr"
            try:
                language_ns_path = URLPath.get_by_path("/%s" %
                                                       current_language_code)
            except URLPath.DoesNotExist:
                language_ns_path = URLPath.create_article(
                    parent=root_path,
                    slug=current_language_code,
                    site=current_site,
                    title=current_language_code)

            # Get or create the article
            from django.template.defaultfilters import slugify
            tag_slug = slugify(tag_instance.name)
            try:
                article_path = URLPath.get_by_path(
                    "/%s/%s" % (current_language_code, tag_slug))
            except URLPath.DoesNotExist:
                article_path = URLPath.create_article(parent=language_ns_path,
                                                      slug=tag_slug,
                                                      site=current_site,
                                                      title=tag_instance.name)

            # Get the wiki article itself
            article = article_path.article
            article.add_object_relation(tag_instance)

        context['article'] = article

        # XXX: site not taken in account
        context['tag'] = tag_instance
        context['related_tags'] = list(
            reversed(
                sorted(
                    Tag.objects.related_for_model(tag_instance,
                                                  I4pProject,
                                                  counts=True),
                    key=attrgetter('count'),
                )))[:15]

        # Get project sheets tagged with this tag XXX: site=site may
        # not be correct 4 Random projects with at least one picture.
        # It's not possible to mix distinct and order by random, so
        # use a trick
        hilighted_projects = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations().filter(
                language_code=current_language_code,
                master__site=current_site,
                master__pictures__isnull=False).distinct(),
            tag_instance).distinct()
        context['picture_projects'] = random.sample(
            hilighted_projects, min(4, len(hilighted_projects)))

        # Mature projects
        mature_projects = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations().filter(
                master__site=current_site,
                master__status__in=('WIP', 'END')).distinct(),
            tag_instance).distinct()
        context['num_mature_projects_projects_with_tag'] = len(mature_projects)
        context['mature_projects'] = random.sample(
            mature_projects, min(4, len(mature_projects)))

        # Starting projects
        starting_projects = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations().filter(
                master__site=current_site,
                master__status__in=('IDEA', 'BEGIN')).distinct(),
            tag_instance).distinct()
        context['num_starting_projects_projects_with_tag'] = len(
            starting_projects)
        context['starting_projects'] = random.sample(
            starting_projects, min(4, len(starting_projects)))

        # New projects
        context['new_projects'] = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations().filter(
                master__site=current_site, ).distinct(),
            tag_instance).order_by('-master__created')[:4]

        # Latest modifications
        context['modified_projects'] = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations().filter(
                master__site=current_site, ).distinct(),
            tag_instance).order_by('-modified')[:4]

        # Related people
        # List is to force evaluation to avoid a sql bug in queryset combining later (project__in=projects)
        projects = list(
            TaggedItem.objects.get_by_model(
                I4pProject.objects.using_translations().filter(
                    master__site=current_site, ).distinct(),
                tag_instance).all())
        # While we're at it, let's count them for free
        context['num_projects_with_tag'] = len(projects)

        context['people'] = ProjectMember.objects.filter(
            project__in=projects).order_by('?')[:6]

        return context
Beispiel #14
0
def course_wiki_redirect(request, course_id, wiki_path=""):  # pylint: disable=unused-argument
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(CourseKey.from_string(course_id))
    course_slug = course_wiki_slug(course)

    valid_slug = True
    if not course_slug:
        log.exception(
            "This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match(r'^[-\w\.]+$', course_slug) is None:
        log.exception(
            "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens."
        )
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")

    try:
        urlpath = URLPath.get_by_path(wiki_path or course_slug,
                                      select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        content = cgi.escape(
            # Translators: this string includes wiki markup.  Leave the ** and the _ alone.
            _("This is the wiki for **{organization}**'s _{course_name}_."
              ).format(
                  organization=course.display_org_with_default,
                  course_name=course.display_name_with_default_escaped,
              ))
        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course.display_name_with_default,
            content=content,
            user_message=_("Course page automatically created."),
            user=None,
            ip_address=None,
            article_kwargs={
                'owner': None,
                'group': None,
                'group_read': True,
                'group_write': True,
                'other_read': True,
                'other_write': True,
            })

    return redirect("wiki:get", path=urlpath.path)
Beispiel #15
0
    def wrapper(request, *args, **kwargs):

        #path = kwargs.pop('path', None)
        site = Site.objects.get_current()
        path = 'uga/'
        parent = URLPath.objects.get(slug='uga')

        article_id = kwargs.pop('article_id', None)

        #print('Request: ' + request)
        #print('Kwargs: ' + kwargs)

        urlpath = None
        #print('Path: ' + path)

        # fetch by urlpath.path
        if path is not None:
            try:
                urlpath = URLPath.get_by_path(path, select_related=True)
                #urlpath = URLPath.create_urlpath(parent,'/' )
                print(urlpath)
            except NoRootURL:
                return redirect('root_create')
            except URLPath.DoesNotExist:
                try:
                    print('Hello')
                    pathlist = list(
                        filter(
                            lambda x: x != "",
                            path.split("/"),
                        ))
                    path = "/".join(pathlist[:-1])
                    parent = URLPath.get_by_path(path)
                    return HttpResponseRedirect(
                        reverse(
                            "create", kwargs={'path': parent.path, }) +
                        "?slug=%s" % pathlist[-1].lower())
                except URLPath.DoesNotExist:
                    print('Hello 123123132')
                    return HttpResponseNotFound(
                        render_to_string(
                            "wiki/error.html",
                            context={
                                'error_type': 'ancestors_missing'
                            },
                            request=request))
            if urlpath.article:
                # urlpath is already smart about prefetching items on article
                # (like current_revision), so we don't have to
                print('test')
                article = urlpath.article
            else:
                # Be robust: Somehow article is gone but urlpath exists...
                # clean up
                print('Hello Jonathan and Ferhat')
                return_url = reverse(
                    'wiki:get',
                    kwargs={
                        'path': urlpath.parent.path})
                urlpath.delete()
                return HttpResponseRedirect(return_url)

        # fetch by article.id
        elif article_id:
            # TODO We should try to grab the article form URLPath so the
            # caching is good, and fall back to grabbing it from
            # Article.objects if not
            articles = Article.objects

            article = get_object_or_404(articles, id=article_id)
            try:
                urlpath = URLPath.objects.get(articles__article=article)
            except (URLPath.DoesNotExist, URLPath.MultipleObjectsReturned):
                urlpath = None

        else:
            raise TypeError('You should specify either article_id or path')

        if not deleted_contents:
            # If the article has been deleted, show a special page.
            if urlpath:
                if urlpath.is_deleted():  # This also checks all ancestors
                    return redirect('wiki:deleted', path=urlpath.path)
            else:
                if article.current_revision and article.current_revision.deleted:
                    return redirect('wiki:deleted', article_id=article.id)

        if article.current_revision.locked and not_locked:
            return response_forbidden(request, article, urlpath)

        if can_read and not article.can_read(request.user):
            return response_forbidden(request, article, urlpath)

        if (can_write or can_create) and not article.can_write(request.user):
            return response_forbidden(request, article, urlpath)

        if can_create and not (
                request.user.is_authenticated() or settings.ANONYMOUS_CREATE):
            return response_forbidden(request, article, urlpath)

        if can_delete and not article.can_delete(request.user):
            return response_forbidden(request, article, urlpath)

        if can_moderate and not article.can_moderate(request.user):
            return response_forbidden(request, article, urlpath)

        kwargs['urlpath'] = urlpath
        print('hello1')
        return func(request, article, *args, **kwargs)
Beispiel #16
0
def course_wiki_redirect(request, course_id):
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(course_id)

    course_slug = course.wiki_slug

    # cdodge: fix for cases where self.location.course can be interpreted as an number rather than
    # a string. We're seeing in Studio created courses that people often will enter in a stright number
    # for 'course' (e.g. 201). This Wiki library expects a string to "do the right thing". We haven't noticed this before
    # because - to now - 'course' has always had non-numeric characters in them
    try:
        float(course_slug)
        # if the float() doesn't throw an exception, that means it's a number
        course_slug = course_slug + "_"
    except:
        pass

    valid_slug = True
    if not course_slug:
        log.exception("This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match("^[-\w\.]+$", course_slug) is None:
        log.exception(
            "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens."
        )
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")

    # The wiki needs a Site object created. We make sure it exists here
    try:
        site = Site.objects.get_current()
    except Site.DoesNotExist:
        new_site = Site()
        new_site.domain = settings.SITE_NAME
        new_site.name = "edX"
        new_site.save()
        if str(new_site.id) != str(settings.SITE_ID):
            raise ImproperlyConfigured(
                "No site object was created and the SITE_ID doesn't match the newly created one. "
                + str(new_site.id)
                + "!="
                + str(settings.SITE_ID)
            )

    try:
        urlpath = URLPath.get_by_path(course_slug, select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course_slug,
            content="This is the wiki for **{0}**'s _{1}_.".format(course.org, course.display_name_with_default),
            user_message="Course page automatically created.",
            user=None,
            ip_address=None,
            article_kwargs={
                "owner": None,
                "group": None,
                "group_read": True,
                "group_write": True,
                "other_read": True,
                "other_write": True,
            },
        )

    return redirect("wiki:get", path=urlpath.path)
Beispiel #17
0
    def test_move(self):
        # Create a hierarchy of pages
        self.client.post(
            resolve_url('wiki:create', path=''),
            {'title': 'Test', 'slug': 'test0', 'content': 'Content .0.'}
        )
        self.client.post(
            resolve_url('wiki:create', path='test0/'),
            {'title': 'Test00', 'slug': 'test00', 'content': 'Content .00.'}
        )
        self.client.post(
            resolve_url('wiki:create', path=''),
            {'title': 'Test1', 'slug': 'test1', 'content': 'Content .1.'}
        )
        self.client.post(
            resolve_url('wiki:create', path='test1/'),
            {'title': 'Tes10', 'slug': 'test10', 'content': 'Content .10.'}
        )
        self.client.post(
            resolve_url('wiki:create', path='test1/test10/'),
            {'title': 'Test100', 'slug': 'test100', 'content': 'Content .100.'}
        )

        # Move /test1 => /test0 (an already existing destination slug!)
        response = self.client.post(
            resolve_url('wiki:move', path='test1/'),
            {
                'destination': str(URLPath.root().article.current_revision.id),
                'slug': 'test0',
                'redirect': ''
            }
        )
        self.assertContains(response, 'A slug named')
        self.assertContains(response, 'already exists.')

        # Move /test1 >= /test2 (valid slug), no redirect
        test0_id = URLPath.objects.get(slug='test0').article.current_revision.id
        response = self.client.post(
            resolve_url('wiki:move', path='test1/'),
            {'destination': str(test0_id), 'slug': 'test2', 'redirect': ''}
        )
        self.assertRedirects(
            response,
            resolve_url('wiki:get', path='test0/test2/')
        )

        # Check that there is no article displayed in this path anymore
        response = self.get_by_path('test1/')
        self.assertRedirects(response, '/_create/?slug=test1')

        # Create /test0/test2/test020
        response = self.client.post(
            resolve_url('wiki:create', path='test0/test2/'),
            {'title': 'Test020', 'slug': 'test020', 'content': 'Content .020.'}
        )
        # Move /test0/test2 => /test1new + create redirect
        response = self.client.post(
            resolve_url('wiki:move', path='test0/test2/'),
            {
                'destination': str(URLPath.root().article.current_revision.id),
                'slug': 'test1new', 'redirect': 'true'
            }
        )
        self.assertRedirects(
            response,
            resolve_url('wiki:get', path='test1new/')
        )

        # Check that /test1new is a valid path
        response = self.get_by_path('test1new/')
        self.assertContains(response, 'Content .1.')

        # Check that the child article test0/test2/test020 was also moved
        response = self.get_by_path('test1new/test020/')
        self.assertContains(response, 'Content .020.')

        response = self.get_by_path('test0/test2/')
        self.assertContains(response, 'Moved: Test1')
        self.assertRegex(response.rendered_content, r'moved to <a[^>]*>wiki:/test1new/')

        response = self.get_by_path('test0/test2/test020/')
        self.assertContains(response, 'Moved: Test020')
        self.assertRegex(response.rendered_content, r'moved to <a[^>]*>wiki:/test1new/test020')

        # Check that moved_to was correctly set
        urlsrc = URLPath.get_by_path('/test0/test2/')
        urldst = URLPath.get_by_path('/test1new/')
        self.assertEqual(urlsrc.moved_to, urldst)

        # Check that moved_to was correctly set on the child's previous path
        urlsrc = URLPath.get_by_path('/test0/test2/test020/')
        urldst = URLPath.get_by_path('/test1new/test020/')
        self.assertEqual(urlsrc.moved_to, urldst)
Beispiel #18
0
def db_get_article(path):
    try:
        return URLPath.get_by_path(str(path)).article
    except Exception:
        return None
    def get_context_data(self, tag, **kwargs):
        context = super(TagPageView, self).get_context_data(**kwargs)

        current_site = Site.objects.get_current()
        current_language_code = translation.get_language()

        tag_instance = get_tag(tag)
        if tag_instance is None:
            raise Http404(_('No Tag found matching "%s".') % tag)

        try:
            article = Article.get_for_object(tag_instance)
        except ArticleForObject.DoesNotExist:
            # Get or create root
            try:
                root_path = URLPath.root()
            except NoRootURL:
                root_path = URLPath.create_root(site=current_site)

            # Get current language namespace. E.g. "/fr"
            try:
                language_ns_path = URLPath.get_by_path("/%s" % current_language_code)
            except URLPath.DoesNotExist:
                language_ns_path = URLPath.create_article(
                    parent=root_path, slug=current_language_code, site=current_site, title=current_language_code
                )

            # Get or create the article
            from django.template.defaultfilters import slugify

            tag_slug = slugify(tag_instance.name)
            try:
                article_path = URLPath.get_by_path("/%s/%s" % (current_language_code, tag_slug))
            except URLPath.DoesNotExist:
                article_path = URLPath.create_article(
                    parent=language_ns_path, slug=tag_slug, site=current_site, title=tag_instance.name
                )

            # Get the wiki article itself
            article = article_path.article
            article.add_object_relation(tag_instance)

        context["article"] = article

        # XXX: site not taken in account
        context["tag"] = tag_instance
        context["related_tags"] = list(
            reversed(
                sorted(Tag.objects.related_for_model(tag_instance, I4pProject, counts=True), key=attrgetter("count"))
            )
        )[:15]

        # Get project sheets tagged with this tag XXX: site=site may
        # not be correct 4 Random projects with at least one picture.
        # It's not possible to mix distinct and order by random, so
        # use a trick
        hilighted_projects = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations()
            .filter(language_code=current_language_code, master__site=current_site, master__pictures__isnull=False)
            .distinct(),
            tag_instance,
        ).distinct()
        context["picture_projects"] = random.sample(hilighted_projects, min(4, len(hilighted_projects)))

        # Mature projects
        mature_projects = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations()
            .filter(master__site=current_site, master__status__in=("WIP", "END"))
            .distinct(),
            tag_instance,
        ).distinct()
        context["num_mature_projects_projects_with_tag"] = len(mature_projects)
        context["mature_projects"] = random.sample(mature_projects, min(4, len(mature_projects)))

        # Starting projects
        starting_projects = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations()
            .filter(master__site=current_site, master__status__in=("IDEA", "BEGIN"))
            .distinct(),
            tag_instance,
        ).distinct()
        context["num_starting_projects_projects_with_tag"] = len(starting_projects)
        context["starting_projects"] = random.sample(starting_projects, min(4, len(starting_projects)))

        # New projects
        context["new_projects"] = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations().filter(master__site=current_site).distinct(), tag_instance
        ).order_by("-master__created")[:4]

        # Latest modifications
        context["modified_projects"] = TaggedItem.objects.get_by_model(
            I4pProject.objects.using_translations().filter(master__site=current_site).distinct(), tag_instance
        ).order_by("-modified")[:4]

        # Related people
        # List is to force evaluation to avoid a sql bug in queryset combining later (project__in=projects)
        projects = list(
            TaggedItem.objects.get_by_model(
                I4pProject.objects.using_translations().filter(master__site=current_site).distinct(), tag_instance
            ).all()
        )
        # While we're at it, let's count them for free
        context["num_projects_with_tag"] = len(projects)

        context["people"] = ProjectMember.objects.filter(project__in=projects).order_by("?")[:6]

        return context
Beispiel #20
0
def course_wiki_redirect(request, course_id, wiki_path=""):  # pylint: disable=unused-argument
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(CourseKey.from_string(course_id))
    course_slug = course_wiki_slug(course)

    valid_slug = True
    if not course_slug:
        log.exception("This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match(r'^[-\w\.]+$', course_slug) is None:
        log.exception("This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens.")
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")

    try:
        urlpath = URLPath.get_by_path(wiki_path or course_slug, select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        content = Text(
            # Translators: this string includes wiki markup.  Leave the ** and the _ alone.
            _(u"This is the wiki for **{organization}**'s _{course_name}_.")
        ).format(
            organization=course.display_org_with_default,
            course_name=course.display_name_with_default,
        )
        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course.display_name_with_default,
            content=content,
            user_message=_("Course page automatically created."),
            user=None,
            ip_address=None,
            article_kwargs={'owner': None,
                            'group': None,
                            'group_read': True,
                            'group_write': True,
                            'other_read': True,
                            'other_write': True,
                            })

    return redirect("wiki:get", path=urlpath.path)
Beispiel #21
0
def course_wiki_redirect(request, course_id):
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(course_id)

    course_slug = course.wiki_slug

    # cdodge: fix for cases where self.location.course can be interpreted as an number rather than
    # a string. We're seeing in Studio created courses that people often will enter in a stright number
    # for 'course' (e.g. 201). This Wiki library expects a string to "do the right thing". We haven't noticed this before
    # because - to now - 'course' has always had non-numeric characters in them
    try:
        float(course_slug)
        # if the float() doesn't throw an exception, that means it's a number
        course_slug = course_slug + "_"
    except:
        pass

    valid_slug = True
    if not course_slug:
        log.exception(
            "This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match(r'^[-\w\.]+$', course_slug) is None:
        log.exception(
            "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens."
        )
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")

    # The wiki needs a Site object created. We make sure it exists here
    try:
        site = Site.objects.get_current()
    except Site.DoesNotExist:
        new_site = Site()
        new_site.domain = settings.SITE_NAME
        new_site.name = "edX"
        new_site.save()
        if str(new_site.id) != str(settings.SITE_ID):
            raise ImproperlyConfigured(
                "No site object was created and the SITE_ID doesn't match the newly created one. "
                + str(new_site.id) + "!=" + str(settings.SITE_ID))

    try:
        urlpath = URLPath.get_by_path(course_slug, select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course_slug,
            content="This is the wiki for **{0}**'s _{1}_.".format(
                course.org, course.display_name_with_default),
            user_message="Course page automatically created.",
            user=None,
            ip_address=None,
            article_kwargs={
                'owner': None,
                'group': None,
                'group_read': True,
                'group_write': True,
                'other_read': True,
                'other_write': True,
            })

    return redirect("wiki:get", path=urlpath.path)
Beispiel #22
0
    def get_context_data(self, tag, **kwargs):
        context = super(TagPageView, self).get_context_data(**kwargs)

        current_site = Site.objects.get_current()
        current_language_code = translation.get_language()

        tag_instance = get_tag(tag)
        if tag_instance is None:
            raise Http404(_('No Tag found matching "%s".') % tag)

        try:
            article = Article.get_for_object(tag_instance)
        except ArticleForObject.DoesNotExist:
            # Get or create root
            try:
                root_path = URLPath.root()
            except NoRootURL:
                root_path = URLPath.create_root(site=current_site)

            # Get current language namespace. E.g. "/fr"
            try:
                language_ns_path = URLPath.get_by_path("/%s" % current_language_code)
            except URLPath.DoesNotExist:
                language_ns_path = URLPath.create_article(
                    parent=root_path,
                    slug=current_language_code,
                    site=current_site,
                    title=current_language_code
                )

            # Get or create the article
            from django.template.defaultfilters import slugify                
            tag_slug = slugify(tag_instance.name)
            try:
                article_path = URLPath.get_by_path("/%s/%s" % (current_language_code,
                                                               tag_slug)
                                                   )
            except URLPath.DoesNotExist:
                article_path = URLPath.create_article(
                    parent=language_ns_path,
                    slug=tag_slug,
                    site=current_site,
                    title=tag_instance.name
                )

            # Get the wiki article itself
            article = article_path.article
            article.add_object_relation(tag_instance)

        context['article'] = article

        # XXX: site not taken in account        
        context['tag'] = tag_instance
        context['related_tags'] = list(
            reversed(
                sorted(Tag.objects.related_for_model(tag_instance, 
                                                     I4pProjectTranslation,
                                                     counts=True),
                       key=attrgetter('count'),
                   )
            )
        )[:15]

        # Get project sheets tagged with this tag XXX: site=site may
        # not be correct 4 Random projects with at least one picture.
        # It's not possible to mix distinct and order by random, so
        # use a trick
        hilighted_projects= TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter(
            language_code=current_language_code,            
            project__site=current_site,
            project__pictures__isnull=False
        ).distinct(), tag_instance).distinct()
        context['picture_project_translations'] = random.sample(hilighted_projects, min(4, len(hilighted_projects)))


        # Mature projects
        mature_project_translations = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter(
            language_code=current_language_code,
            project__site=current_site,
            project__status__in=('WIP', 'END')
        ).distinct(), tag_instance).distinct()
        context['mature_project_translations'] = random.sample(mature_project_translations, min(4, len(mature_project_translations)))

        # Starting projects
        starting_project_translations = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter(
            language_code=current_language_code,            
            project__site=current_site,
            project__status__in=('IDEA', 'BEGIN')
        ).distinct(), tag_instance).distinct()
        context['starting_project_translations'] = random.sample(starting_project_translations, min(4, len(starting_project_translations)))
         
        # New projects
        context['new_project_translations'] = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter(
            language_code=current_language_code,            
            project__site=current_site,
        ).distinct(), tag_instance).order_by('-project__created')[:4]
        
        # Latest modifications
        context['modified_project_translations'] = TaggedItem.objects.get_by_model(I4pProjectTranslation.objects.filter(
            language_code=current_language_code,            
            project__site=current_site,
        ).distinct(), tag_instance).order_by('-modified')[:4]

        # Related people
        project_translations = ModelTaggedItemManager().with_any([tag_instance.name],
                                                                 I4pProjectTranslation.objects.filter(
                                                                     language_code=current_language_code,
                                                                     project__site=current_site,
                                                                 )
                                                             ).distinct()
        projects = [p.project for p in project_translations]
        
        context['people'] = ProjectMember.objects.filter(
            project__in=projects
        ).order_by('?')[:6]

        return context
Beispiel #23
0
def course_wiki_redirect(request, course_id):  # pylint: disable=W0613
    """
    This redirects to whatever page on the wiki that the course designates
    as it's home page. A course's wiki must be an article on the root (for
    example, "/6.002x") to keep things simple.
    """
    course = get_course_by_id(
        SlashSeparatedCourseKey.from_deprecated_string(course_id))
    course_slug = course_wiki_slug(course)

    valid_slug = True
    if not course_slug:
        log.exception(
            "This course is improperly configured. The slug cannot be empty.")
        valid_slug = False
    if re.match(r'^[-\w\.]+$', course_slug) is None:
        log.exception(
            "This course is improperly configured. The slug can only contain letters, numbers, periods or hyphens."
        )
        valid_slug = False

    if not valid_slug:
        return redirect("wiki:get", path="")

    # The wiki needs a Site object created. We make sure it exists here
    try:
        Site.objects.get_current()
    except Site.DoesNotExist:
        new_site = Site()
        new_site.domain = settings.SITE_NAME
        new_site.name = "edX"
        new_site.save()
        site_id = str(new_site.id)  # pylint: disable=E1101
        if site_id != str(settings.SITE_ID):
            raise ImproperlyConfigured(
                "No site object was created and the SITE_ID doesn't match the newly created one. {} != {}"
                .format(site_id, settings.SITE_ID))

    try:
        urlpath = URLPath.get_by_path(course_slug, select_related=True)

        results = list(Article.objects.filter(id=urlpath.article.id))
        if results:
            article = results[0]
        else:
            article = None

    except (NoRootURL, URLPath.DoesNotExist):
        # We will create it in the next block
        urlpath = None
        article = None

    if not article:
        # create it
        root = get_or_create_root()

        if urlpath:
            # Somehow we got a urlpath without an article. Just delete it and
            # recerate it.
            urlpath.delete()

        content = cgi.escape(
            # Translators: this string includes wiki markup.  Leave the ** and the _ alone.
            _("This is the wiki for **{organization}**'s _{course_name}_."
              ).format(
                  organization=course.display_org_with_default,
                  course_name=course.display_name_with_default,
              ))
        urlpath = URLPath.create_article(
            root,
            course_slug,
            title=course_slug,
            content=content,
            user_message=_("Course page automatically created."),
            user=None,
            ip_address=None,
            article_kwargs={
                'owner': None,
                'group': None,
                'group_read': True,
                'group_write': True,
                'other_read': True,
                'other_write': True,
            })

    return redirect("wiki:get", path=urlpath.path)