Exemplo n.º 1
0
    def render_admin_panel(self, req, cat, page, path_info):
        req.perm(Resource('blog')).require('BLOG_ADMIN')

        blog_admin = {}
        blog_core = FullBlogCore(self.env)

        if req.method == 'POST':
            self.config.set('fullblog', 'num_items_front',
                            req.args.getint('numpostsfront'))
            self.config.set('fullblog', 'default_postname',
                            req.args.get('defaultpostname'))
            self.config.save()
            blog_core.set_bloginfotext(req.args.get('bloginfotext'))
            req.redirect(
                req.href.admin(req.args['cat_id'], req.args['panel_id']))

        blog_admin['bloginfotext'] = blog_core.get_bloginfotext()
        blog_admin['numpostsfront'] = \
                self.config.getint('fullblog', 'num_items_front')
        blog_admin['defaultpostname'] = \
                self.config.get('fullblog', 'default_postname')

        chrome = Chrome(self.env)
        chrome.add_auto_preview(req)
        chrome.add_wiki_toolbars(req)

        return 'fullblog_admin.html', {'blog_admin': blog_admin}
Exemplo n.º 2
0
    def render_admin_panel(self, req, cat, page, path_info):     
        req.perm(Resource('blog', None)).require('BLOG_ADMIN')

        blog_admin = {}
        blog_core = FullBlogCore(self.env)
        
        if req.method == "POST":
            if req.args.get('savesettings'):
                self.env.config.set('fullblog', 'num_items_front',
                    int(req.args.get('numpostsfront')))
                self.env.config.set('fullblog', 'default_postname',
                    req.args.get('defaultpostname'))
                self.env.config.save()
            elif req.args.get('savebloginfotext'):
                self.env.log.debug("New blog info text = %r" % req.args.get('bloginfotext'))
                is_ok = blog_core.set_bloginfotext(
                        req.args.get('bloginfotext'))
                if is_ok:
                    req.redirect(req.href.admin(req.args['cat_id'],
                            req.args['panel_id']))
                else:
                    add_warning(req, "Error storing text in database. Not saved.")
            else:
                self.log.warning('Unknown POST request: %s', req.args)
        
        blog_admin['bloginfotext'] = blog_core.get_bloginfotext()
        blog_admin['numpostsfront'] = self.env.config.getint(
                                            'fullblog', 'num_items_front')
        blog_admin['defaultpostname'] = self.env.config.get(
                                            'fullblog', 'default_postname')
        
        if hasattr(Chrome(self.env), 'jenv'):       # jinja2
            return ('fullblog_admin.html', {'blog_admin': blog_admin}, None)
        else:                                       # genshi
            return ('fullblog_admin.html', {'blog_admin': blog_admin})
Exemplo n.º 3
0
    def render_admin_panel(self, req, cat, page, path_info):     
        req.perm(Resource('blog', None)).require('BLOG_ADMIN')

        blog_admin = {}
        blog_core = FullBlogCore(self.env)
        
        if req.method == "POST":
            if req.args.get('savesettings'):
                self.env.config.set('fullblog', 'num_items_front',
                    int(req.args.get('numpostsfront')))
                self.env.config.set('fullblog', 'default_postname',
                    req.args.get('defaultpostname'))
                self.env.config.save()
            elif req.args.get('savebloginfotext'):
                self.env.log.debug("New blog info text = %r" % req.args.get('bloginfotext'))
                is_ok = blog_core.set_bloginfotext(
                        req.args.get('bloginfotext'))
                if is_ok:
                    req.redirect(req.href.admin(req.args['cat_id'],
                            req.args['panel_id']))
                else:
                    add_warning(req, "Error storing text in database. Not saved.")
            else:
                self.log.warning('Unknown POST request: %s', req.args)
        
        blog_admin['bloginfotext'] = blog_core.get_bloginfotext()
        blog_admin['numpostsfront'] = self.env.config.getint(
                                            'fullblog', 'num_items_front')
        blog_admin['defaultpostname'] = self.env.config.get(
                                            'fullblog', 'default_postname')
        
        return ('fullblog_admin.html', {'blog_admin': blog_admin})
Exemplo n.º 4
0
    def process_request(self, req):
        """ Processing the request. """

        req.perm('blog').assert_permission('BLOG_VIEW')

        blog_core = FullBlogCore(self.env)
        format = req.args.get('format', '').lower()

        command, pagename, path_items, listing_data = self._parse_path(req)
        action = req.args.get('action', 'view').lower()
        try:
            version = int(req.args.get('version', 0))
        except:
            version = 0

        data = {}
        template = 'fullblog_view.html'
        data['blog_about'] = BlogPost(self.env, 'about')
        data['blog_infotext'] = blog_core.get_bloginfotext()
        blog_month_names = map_month_names(
            self.env.config.getlist('fullblog', 'month_names'))
        data['blog_month_names'] = blog_month_names
        self.env.log.debug(
            "Blog debug: command=%r, pagename=%r, path_items=%r" %
            (command, pagename, path_items))

        if not command:
            # Request for just root (display latest)
            data['blog_post_list'] = []
            count = 0
            maxcount = self.num_items
            blog_posts = get_blog_posts(self.env)
            for post in blog_posts:
                bp = BlogPost(self.env, post[0], post[1])
                if 'BLOG_VIEW' in req.perm(bp.resource):
                    data['blog_post_list'].append(bp)
                    count += 1
                if maxcount and count == maxcount:
                    # Only display a certain number on front page (from config)
                    break
            data['blog_list_title'] = "Recent posts" + \
                    (len(blog_posts) > maxcount and \
                        " (max %d) - Browse or Archive for more" % (maxcount,) \
                    or '')
            add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed',
                     'application/rss+xml', 'rss')

        elif command == 'archive':
            # Requesting the archive page
            template = 'fullblog_archive.html'
            data['blog_archive'] = []
            for period, period_posts in group_posts_by_month(
                    get_blog_posts(self.env)):
                allowed_posts = []
                for post in period_posts:
                    bp = BlogPost(self.env, post[0], post[1])
                    if 'BLOG_VIEW' in req.perm(bp.resource):
                        allowed_posts.append(post)
                if allowed_posts:
                    data['blog_archive'].append((period, allowed_posts))
            add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed',
                     'application/rss+xml', 'rss')

        elif command == 'view' and pagename:
            # Requesting a specific blog post
            the_post = BlogPost(self.env, pagename, version)
            req.perm(the_post.resource).require('BLOG_VIEW')
            if not the_post.version:
                raise HTTPNotFound("No blog post named '%s'." % pagename)
            if req.method == 'POST':  # Adding/Previewing a comment
                # Permission?
                req.perm(the_post.resource).require('BLOG_COMMENT')
                comment = BlogComment(self.env, pagename)
                comment.comment = req.args.get('comment', '')
                comment.author = (req.authname != 'anonymous' and req.authname) \
                            or req.args.get('author')
                comment.time = datetime.datetime.now(utc)
                warnings = []
                if 'cancelcomment' in req.args:
                    req.redirect(req.href.blog(pagename))
                elif 'previewcomment' in req.args:
                    warnings.extend(
                        blog_core.create_comment(req,
                                                 comment,
                                                 verify_only=True))
                elif 'submitcomment' in req.args and not warnings:
                    warnings.extend(blog_core.create_comment(req, comment))
                    if not warnings:
                        req.redirect(
                            req.href.blog(pagename) + '#comment-' +
                            str(comment.number))
                data['blog_comment'] = comment
                # Push all warnings out to the user.
                for field, reason in warnings:
                    if field:
                        add_warning(req, "Field '%s': %s" % (field, reason))
                    else:
                        add_warning(req, reason)
            data['blog_post'] = the_post
            context = web_context(req,
                                  the_post.resource,
                                  absurls=format == 'rss' and True or False)
            data['context'] = context
            if format == 'rss':
                return 'fullblog_post.rss', data, 'application/rss+xml'
            # Regular web response
            context = web_context(req, the_post.resource)

            data['blog_attachments'] = AttachmentModule(
                self.env).attachment_data(context)
            # Previous and Next ctxtnav
            prev, next = blog_core.get_prev_next_posts(req.perm, the_post.name)
            if prev:
                add_link(req, 'prev', req.href.blog(prev), prev)
            if next:
                add_link(req, 'next', req.href.blog(next), next)
            if arity(prevnext_nav) == 4:
                # 0.12 compat following trac:changeset:8597
                prevnext_nav(req, 'Previous Post', 'Next Post')
            else:
                prevnext_nav(req, 'Post')
            # RSS feed for post and comments
            add_link(req, 'alternate', req.href.blog(pagename, format='rss'),
                     'RSS Feed', 'application/rss+xml', 'rss')

        elif command in ['create', 'edit']:
            template = 'fullblog_edit.html'
            default_pagename = blog_core._get_default_postname(req.authname)
            the_post = BlogPost(self.env, pagename or default_pagename)
            warnings = []

            if command == 'create' and req.method == 'GET' and not the_post.version:
                # Support appending query arguments for populating intial fields
                the_post.update_fields(req.args)
            if command == 'create' and the_post.version:
                # Post with name or suggested name already exists
                if 'BLOG_CREATE' in req.perm and the_post.name == default_pagename \
                                    and not req.method == 'POST':
                    if default_pagename:
                        add_notice(
                            req, "Suggestion for new name already exists "
                            "('%s'). Please make a new name." % the_post.name)
                elif pagename:
                    warnings.append(
                        ('',
                         "A post named '%s' already exists. Enter new name." %
                         the_post.name))
                the_post = BlogPost(self.env, '')
            if command == 'edit':
                req.perm(the_post.resource).require(
                    'BLOG_VIEW')  # Starting point
            if req.method == 'POST':
                # Create or edit a blog post
                if 'blog-cancel' in req.args:
                    if req.args.get('action', '') == 'edit':
                        req.redirect(req.href.blog(pagename))
                    else:
                        req.redirect(req.href.blog())
                # Assert permissions
                if command == 'create':
                    req.perm(Resource('blog', None)).require('BLOG_CREATE')
                elif command == 'edit':
                    if the_post.author == req.authname:
                        req.perm(the_post.resource).require('BLOG_MODIFY_OWN')
                    else:
                        req.perm(the_post.resource).require('BLOG_MODIFY_ALL')

                # Check input
                orig_author = the_post.author
                if not the_post.update_fields(req.args):
                    warnings.append(('', "None of the fields have changed."))
                version_comment = req.args.get('new_version_comment', '')
                if 'blog-preview' in req.args:
                    warnings.extend(
                        blog_core.create_post(req,
                                              the_post,
                                              req.authname,
                                              version_comment,
                                              verify_only=True))
                elif 'blog-save' in req.args and not warnings:
                    warnings.extend(
                        blog_core.create_post(req, the_post, req.authname,
                                              version_comment))
                    if not warnings:
                        req.redirect(req.href.blog(the_post.name))
                context = web_context(req, the_post.resource)
                data['context'] = context
                data['blog_attachments'] = AttachmentModule(
                    self.env).attachment_data(context)
                data['blog_action'] = 'preview'
                data['blog_version_comment'] = version_comment
                if (orig_author and orig_author != the_post.author) and (
                        not 'BLOG_MODIFY_ALL' in req.perm(the_post.resource)):
                    add_notice(req, "If you change the author you cannot " \
                        "edit the post again due to restricted permissions.")
                    data['blog_orig_author'] = orig_author
            for field, reason in warnings:
                if field:
                    add_warning(req, "Field '%s': %s" % (field, reason))
                else:
                    add_warning(req, reason)
            data['blog_edit'] = the_post

        elif command == 'delete':
            bp = BlogPost(self.env, pagename)
            req.perm(bp.resource).require('BLOG_DELETE')
            if 'blog-cancel' in req.args:
                req.redirect(req.href.blog(pagename))
            comment = int(req.args.get('comment', '0'))
            warnings = []
            if comment:
                # Deleting a specific comment
                bc = BlogComment(self.env, pagename, comment)
                if not bc.number:
                    raise TracError(
                        "Cannot delete. Blog post name and/or comment number missing."
                    )
                if req.method == 'POST' and comment and pagename:
                    warnings.extend(blog_core.delete_comment(bc))
                    if not warnings:
                        add_notice(req, "Blog comment %d deleted." % comment)
                        req.redirect(req.href.blog(pagename))
                template = 'fullblog_delete.html'
                data['blog_comment'] = bc
            else:
                # Delete a version of a blog post or all versions
                # with comments and attachments if only version.
                if not bp.version:
                    raise TracError(
                        "Cannot delete. Blog post '%s' does not exist." %
                        (bp.name))
                version = int(req.args.get('version', '0'))
                if req.method == 'POST':
                    if 'blog-version-delete' in req.args:
                        if bp.version != version:
                            raise TracError(
                                "Cannot delete. Can only delete most recent version."
                            )
                        warnings.extend(
                            blog_core.delete_post(bp, version=bp.versions[-1]))
                    elif 'blog-delete' in req.args:
                        version = 0
                        warnings.extend(
                            blog_core.delete_post(bp, version=version))
                    if not warnings:
                        if version > 1:
                            add_notice(
                                req, "Blog post '%s' version %d deleted." %
                                (pagename, version))
                            req.redirect(req.href.blog(pagename))
                        else:
                            add_notice(req,
                                       "Blog post '%s' deleted." % pagename)
                            req.redirect(req.href.blog())
                template = 'fullblog_delete.html'
                data['blog_post'] = bp
            for field, reason in warnings:
                if field:
                    add_warning(req, "Field '%s': %s" % (field, reason))
                else:
                    add_warning(req, reason)

        elif command.startswith('listing-'):
            # 2007/10 or category/something or author/theuser
            title = category = author = ''
            from_dt = to_dt = None
            if command == 'listing-month':
                from_dt = listing_data['from_dt']
                to_dt = listing_data['to_dt']
                title = "Posts for the month of %s %d" % (
                    blog_month_names[from_dt.month - 1], from_dt.year)
                add_link(req, 'alternate', req.href.blog(format='rss'),
                         'RSS Feed', 'application/rss+xml', 'rss')

            elif command == 'listing-category':
                category = listing_data['category']
                if category:
                    title = "Posts in category %s" % category
                    add_link(req, 'alternate',
                             req.href.blog('category', category, format='rss'),
                             'RSS Feed', 'application/rss+xml', 'rss')
            elif command == 'listing-author':
                author = listing_data['author']
                if author:
                    title = "Posts by author %s" % author
                    add_link(req, 'alternate',
                             req.href.blog('author', author, format='rss'),
                             'RSS Feed', 'application/rss+xml', 'rss')
            if not (author or category or (from_dt and to_dt)):
                raise HTTPNotFound("Not a valid path for viewing blog posts.")
            blog_posts = []
            for post in get_blog_posts(self.env,
                                       category=category,
                                       author=author,
                                       from_dt=from_dt,
                                       to_dt=to_dt):
                bp = BlogPost(self.env, post[0], post[1])
                if 'BLOG_VIEW' in req.perm(bp.resource):
                    blog_posts.append(bp)
            data['blog_post_list'] = blog_posts
            data['blog_list_title'] = title
        else:
            raise HTTPNotFound("Not a valid blog path.")

        if (not command or command.startswith('listing-')) and format == 'rss':
            data['context'] = web_context(req, absurls=True)
            data['blog_num_items'] = self.num_items
            return 'fullblog.rss', data, 'application/rss+xml'

        data['blog_months'], data['blog_authors'], data['blog_categories'], \
                data['blog_total'] = \
                    blog_core.get_months_authors_categories(
                        user=req.authname, perm=req.perm)
        if 'BLOG_CREATE' in req.perm('blog'):
            add_ctxtnav(req,
                        'New Post',
                        href=req.href.blog('create'),
                        title="Create new Blog Post")
        add_stylesheet(req, 'tracfullblog/css/fullblog.css')
        add_stylesheet(req, 'common/css/code.css')
        data['blog_personal_blog'] = self.env.config.getbool(
            'fullblog', 'personal_blog')
        data['blog_archive_rss_icon'] = self.all_rss_icons \
                                        or self.archive_rss_icon
        data['blog_all_rss_icons'] = self.all_rss_icons
        return (template, data, None)
Exemplo n.º 5
0
    def process_request(self, req):
        """ Processing the request. """

        req.perm("blog").assert_permission("BLOG_VIEW")

        blog_core = FullBlogCore(self.env)
        format = req.args.get("format", "").lower()

        command, pagename, path_items, listing_data = self._parse_path(req)
        action = req.args.get("action", "view").lower()
        try:
            version = int(req.args.get("version", 0))
        except:
            version = 0

        data = {}
        template = "fullblog_view.html"
        data["blog_about"] = BlogPost(self.env, "about")
        data["blog_infotext"] = blog_core.get_bloginfotext()
        blog_month_names = map_month_names(self.env.config.getlist("fullblog", "month_names"))
        data["blog_month_names"] = blog_month_names
        self.env.log.debug("Blog debug: command=%r, pagename=%r, path_items=%r" % (command, pagename, path_items))

        if has_UserPictureModule and self.avatar_size > 0:
            data["avatars"] = avatars = {}
        else:
            avatars = None

        page = int(req.args.get("page", 1))

        if not command:
            # Request for just root (display latest)
            data["blog_post_list"] = []
            count = 0
            mincount = (page - 1) * self.num_items
            maxcount = mincount + self.num_items
            blog_posts = get_blog_posts(self.env)
            for post in blog_posts:
                bp = BlogPost(self.env, post[0], post[1])
                if "BLOG_VIEW" in req.perm(bp.resource):
                    count += 1
                    if count <= mincount:
                        continue
                    data["blog_post_list"].append(bp)
                    if avatars != None and bp.author not in avatars:
                        avatars[bp.author] = self._get_avatar(req, bp.author)
                if maxcount and count == maxcount:
                    # Only display a certain number on front page (from config)
                    break
            data["blog_list_title"] = _("Recent posts")
            if len(blog_posts) > maxcount:
                data["blog_list_title"] += _(" (max %d) - Browse or Archive for") % (self.num_items,)
                data["blog_list_title_more"] = _("more")
                data["blog_list_title_href"] = req.href.blog(page=page + 1)
            add_link(req, "alternate", req.href.blog(format="rss"), "RSS Feed", "application/rss+xml", "rss")

        elif command == "archive":
            # Requesting the archive page
            template = "fullblog_archive.html"
            data["blog_archive"] = []
            for period, period_posts in group_posts_by_month(get_blog_posts(self.env)):
                allowed_posts = []
                for post in period_posts:
                    bp = BlogPost(self.env, post[0], post[1])
                    if "BLOG_VIEW" in req.perm(bp.resource):
                        allowed_posts.append(post)
                if allowed_posts:
                    data["blog_archive"].append((period, allowed_posts))
            add_link(req, "alternate", req.href.blog(format="rss"), "RSS Feed", "application/rss+xml", "rss")

        elif command == "view" and pagename:
            # Requesting a specific blog post
            the_post = BlogPost(self.env, pagename, version)
            req.perm(the_post.resource).require("BLOG_VIEW")
            if not the_post.version:
                raise HTTPNotFound("No blog post named '%s'." % pagename)
            if req.method == "POST":  # Adding/Previewing a comment
                # Permission?
                req.perm(the_post.resource).require("BLOG_COMMENT")
                comment = BlogComment(self.env, pagename)
                comment.comment = req.args.get("comment", "")
                comment.author = (req.authname != "anonymous" and req.authname) or req.args.get("author")
                comment.time = datetime.datetime.now(utc)
                warnings = []
                if "cancelcomment" in req.args:
                    req.redirect(req.href.blog(pagename))
                elif "previewcomment" in req.args:
                    warnings.extend(blog_core.create_comment(req, comment, verify_only=True))
                elif "submitcomment" in req.args and not warnings:
                    warnings.extend(blog_core.create_comment(req, comment))
                    if not warnings:
                        req.redirect(req.href.blog(pagename) + "#comment-" + str(comment.number))
                data["blog_comment"] = comment
                # Push all warnings out to the user.
                for field, reason in warnings:
                    if field:
                        add_warning(req, "Field '%s': %s" % (field, reason))
                    else:
                        add_warning(req, reason)
            data["blog_post"] = the_post
            if avatars != None:
                avatars[the_post.author] = self._get_avatar(req, the_post.author)
            context = Context.from_request(req, the_post.resource, absurls=format == "rss" and True or False)
            data["context"] = context
            if format == "rss":
                return "fullblog_post.rss", data, "application/rss+xml"
            # Regular web response
            context = Context.from_request(req, the_post.resource)

            data["blog_attachments"] = AttachmentModule(self.env).attachment_data(context)
            # Previous and Next ctxtnav
            prev, next = blog_core.get_prev_next_posts(req.perm, the_post.name)
            if prev:
                add_link(req, "prev", req.href.blog(prev), prev)
            if next:
                add_link(req, "next", req.href.blog(next), next)
            if arity(prevnext_nav) == 4:
                # 0.12 compat following trac:changeset:8597
                prevnext_nav(req, "Previous Post", "Next Post")
            else:
                prevnext_nav(req, "Post")
            # RSS feed for post and comments
            add_link(req, "alternate", req.href.blog(pagename, format="rss"), "RSS Feed", "application/rss+xml", "rss")

        elif command in ["create", "edit"]:
            template = "fullblog_edit.html"
            default_pagename = blog_core._get_default_postname(req.authname)
            the_post = BlogPost(self.env, pagename or default_pagename)
            warnings = []

            if command == "create" and req.method == "GET" and not the_post.version:
                # Support appending query arguments for populating intial fields
                the_post.update_fields(req.args)
                if self.use_authname:
                    the_post.update_fields({"author": req.authname})
            if command == "create" and the_post.version:
                # Post with name or suggested name already exists
                if "BLOG_CREATE" in req.perm and the_post.name == default_pagename and not req.method == "POST":
                    if default_pagename:
                        add_notice(
                            req,
                            "Suggestion for new name already exists " "('%s'). Please make a new name." % the_post.name,
                        )
                elif pagename:
                    warnings.append(("", "A post named '%s' already exists. Enter new name." % the_post.name))
                the_post = BlogPost(self.env, "")
                if self.use_authname:
                    the_post.update_fields({"author": req.authname})
            if command == "edit":
                req.perm(the_post.resource).require("BLOG_VIEW")  # Starting point
            if req.method == "POST":
                # Create or edit a blog post
                if "blog-cancel" in req.args:
                    if req.args.get("action", "") == "edit":
                        req.redirect(req.href.blog(pagename))
                    else:
                        req.redirect(req.href.blog())
                # Assert permissions
                if command == "create":
                    req.perm(Resource("blog", None)).require("BLOG_CREATE")
                elif command == "edit":
                    if the_post.author == req.authname:
                        req.perm(the_post.resource).require("BLOG_MODIFY_OWN")
                    else:
                        req.perm(the_post.resource).require("BLOG_MODIFY_ALL")

                # Check input
                orig_author = the_post.author
                if not the_post.update_fields(req.args):
                    warnings.append(("", "None of the fields have changed."))
                version_comment = req.args.get("new_version_comment", "")
                if "blog-preview" in req.args:
                    warnings.extend(
                        blog_core.create_post(req, the_post, req.authname, version_comment, verify_only=True)
                    )
                elif "blog-save" in req.args and not warnings:
                    warnings.extend(blog_core.create_post(req, the_post, req.authname, version_comment))
                    if not warnings:
                        req.redirect(req.href.blog(the_post.name))
                context = Context.from_request(req, the_post.resource)
                data["context"] = context
                data["blog_attachments"] = AttachmentModule(self.env).attachment_data(context)
                data["blog_action"] = "preview"
                data["blog_version_comment"] = version_comment
                if (orig_author and orig_author != the_post.author) and (
                    not "BLOG_MODIFY_ALL" in req.perm(the_post.resource)
                ):
                    add_notice(
                        req, "If you change the author you cannot " "edit the post again due to restricted permissions."
                    )
                    data["blog_orig_author"] = orig_author
            for field, reason in warnings:
                if field:
                    add_warning(req, "Field '%s': %s" % (field, reason))
                else:
                    add_warning(req, reason)
            data["blog_edit"] = the_post

        elif command == "delete":
            bp = BlogPost(self.env, pagename)
            req.perm(bp.resource).require("BLOG_DELETE")
            if "blog-cancel" in req.args:
                req.redirect(req.href.blog(pagename))
            comment = int(req.args.get("comment", "0"))
            warnings = []
            if comment:
                # Deleting a specific comment
                bc = BlogComment(self.env, pagename, comment)
                if not bc.number:
                    raise TracError("Cannot delete. Blog post name and/or comment number missing.")
                if req.method == "POST" and comment and pagename:
                    warnings.extend(blog_core.delete_comment(bc))
                    if not warnings:
                        add_notice(req, "Blog comment %d deleted." % comment)
                        req.redirect(req.href.blog(pagename))
                template = "fullblog_delete.html"
                data["blog_comment"] = bc
            else:
                # Delete a version of a blog post or all versions
                # with comments and attachments if only version.
                if not bp.version:
                    raise TracError("Cannot delete. Blog post '%s' does not exist." % (bp.name))
                version = int(req.args.get("version", "0"))
                if req.method == "POST":
                    if "blog-version-delete" in req.args:
                        if bp.version != version:
                            raise TracError("Cannot delete. Can only delete most recent version.")
                        warnings.extend(blog_core.delete_post(bp, version=bp.versions[-1]))
                    elif "blog-delete" in req.args:
                        version = 0
                        warnings.extend(blog_core.delete_post(bp, version=version))
                    if not warnings:
                        if version > 1:
                            add_notice(req, "Blog post '%s' version %d deleted." % (pagename, version))
                            req.redirect(req.href.blog(pagename))
                        else:
                            add_notice(req, "Blog post '%s' deleted." % pagename)
                            req.redirect(req.href.blog())
                template = "fullblog_delete.html"
                data["blog_post"] = bp
            for field, reason in warnings:
                if field:
                    add_warning(req, "Field '%s': %s" % (field, reason))
                else:
                    add_warning(req, reason)

        elif command.startswith("listing-"):
            # 2007/10 or category/something or author/theuser
            title = category = author = ""
            from_dt = to_dt = None
            mincount = maxcount = 0
            if command == "listing-month":
                from_dt = listing_data["from_dt"]
                to_dt = listing_data["to_dt"]
                title = _("Posts for the month of %s %d") % (blog_month_names[from_dt.month - 1], from_dt.year)
                add_link(req, "alternate", req.href.blog(format="rss"), "RSS Feed", "application/rss+xml", "rss")

            elif command == "listing-category":
                category = listing_data["category"]
                mincount = (page - 1) * self.num_items_category
                maxcount = mincount + self.num_items_category
                if category:
                    title = _("Posts in category %s") % category
                    add_link(
                        req,
                        "alternate",
                        req.href.blog("category", category, format="rss"),
                        "RSS Feed",
                        "application/rss+xml",
                        "rss",
                    )
            elif command == "listing-author":
                author = listing_data["author"]
                mincount = (page - 1) * self.num_items_category
                maxcount = mincount + self.num_items_author
                if author:
                    title = _("Posts by author %s") % author
                    add_link(
                        req,
                        "alternate",
                        req.href.blog("author", author, format="rss"),
                        "RSS Feed",
                        "application/rss+xml",
                        "rss",
                    )
            if not (author or category or (from_dt and to_dt)):
                raise HTTPNotFound("Not a valid path for viewing blog posts.")
            blog_posts = []
            count = 0
            for post in get_blog_posts(self.env, category=category, author=author, from_dt=from_dt, to_dt=to_dt):
                bp = BlogPost(self.env, post[0], post[1])
                if "BLOG_VIEW" in req.perm(bp.resource):
                    count += 1
                    if count <= mincount:
                        continue
                    blog_posts.append(bp)
                    if avatars != None and bp.author not in avatars:
                        avatars[bp.author] = self._get_avatar(req, bp.author)
                if maxcount and count == maxcount:
                    break

            if maxcount and count == maxcount:
                title += _(" (max %d) - Browse or Archive for") % (maxcount - mincount)
                data["blog_list_title_more"] = _("more")
                if category:
                    rs = u"category/" + category
                else:
                    rs = u"author/" + author
                data["blog_list_title_href"] = req.href.blog(rs, page=page + 1)

            data["blog_post_list"] = blog_posts
            data["blog_list_title"] = title
        else:
            raise HTTPNotFound("Not a valid blog path.")

        if (not command or command.startswith("listing-")) and format == "rss":
            data["context"] = Context.from_request(req, absurls=True)
            data["blog_num_items"] = self.num_items
            return "fullblog.rss", data, "application/rss+xml"

        data["blog_months"], data["blog_authors"], data["blog_categories"], data[
            "blog_total"
        ] = blog_core.get_months_authors_categories(user=req.authname, perm=req.perm)
        if "BLOG_CREATE" in req.perm("blog"):
            add_ctxtnav(req, _("New Post"), href=req.href.blog("create"), title=_("Create new Blog Post"))
        add_stylesheet(req, "tracfullblog/css/fullblog.css")
        add_stylesheet(req, "common/css/code.css")
        data["blog_personal_blog"] = self.env.config.getbool("fullblog", "personal_blog")
        data["blog_archive_rss_icon"] = self.all_rss_icons or self.archive_rss_icon
        data["blog_all_rss_icons"] = self.all_rss_icons
        return (template, data, None)
Exemplo n.º 6
0
    def process_request(self, req):
        """ Processing the request. """

        req.perm('blog').assert_permission('BLOG_VIEW')

        blog_core = FullBlogCore(self.env)
        format = req.args.get('format', '').lower()

        command, pagename, path_items, listing_data = self._parse_path(req)
        action = req.args.get('action', 'view').lower()
        try:
            version = int(req.args.get('version', 0))
        except:
            version = 0

        data = {}
        template = 'fullblog_view.html'
        data['blog_about'] = BlogPost(self.env, 'about')
        data['blog_infotext'] = blog_core.get_bloginfotext()
        blog_month_names = map_month_names(
                    self.env.config.getlist('fullblog', 'month_names'))
        data['blog_month_names'] = blog_month_names

        user_recent_post = get_blog_posts(self.env,author=req.authname, per_num='3' ,current_num='0') 
        if user_recent_post:   
            data['user_recent_post'] = user_recent_post

            # data['user_recent_post']['url']= user_recent_post[0][0]
            # data['user_recent_post']['title']= user_recent_post[0][4]

        self.env.log.debug(
            "Blog debug: command=%r, pagename=%r, path_items=%r" % (
                command, pagename, path_items))
        
        
        if not command:
            # Request for just root (display latest)
            try:
                page=req.args.get('page') 
                print page                                
            except:
                pass
            try:
                page=int(page)               
            except:
                page=1 
                
            if page>1:               
                data['page'] =  int(page)                
            else:
                page = 1
                data['page'] =  1
                
            
            if data['page'] > 1 :
                data['page_pre4'] = data['page'] - 1
                data['page_pre'] = data['page'] -1
            if data['page'] > 2 :
                data['page_pre3'] = data['page'] - 2                
            if data['page'] > 3 :
                data['page_pre2'] = data['page'] - 3                
            if data['page'] > 4 :
                data['page_pre1'] = data['page'] - 4

            data['page_next1'] = data['page'] + 1
            data['page_next2'] = data['page'] + 2
            data['page_next3'] = data['page'] + 3
            data['page_next4'] = data['page'] + 4
            data['page_next'] = data['page_next1']

                
            data['blog_post_list'] = []
            count = 0
            maxcount = self.num_items
            if page:  
                blog_posts = get_blog_posts(self.env,per_num=maxcount, current_num=(page-1))
            else:
                blog_posts = get_blog_posts(self.env,per_num=maxcount)
            if not blog_posts:
                del data['page_next1'],data['page_next2'],data['page_next3'],data['page_next4'],data['page_next']
#                data['page_next1'] = data['page_next2'] =  data['page_next3'] = data['page_next4'] = data['page_next'] = ''
                
            for post in blog_posts:
                bp = BlogPost(self.env, post[0], post[1])
                if 'BLOG_VIEW' in req.perm(bp.resource):
                    data['blog_post_list'].append(bp)
                    count += 1
                if maxcount and count == maxcount:
                    # Only display a certain number on front page (from config)
                    break
            data['blog_list_title'] = "Recent posts" + \
                    (len(blog_posts) > maxcount and \
                        " (max %d) - Browse or Archive for more" % (maxcount,) \
                    or '')
            add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed',
                     'application/rss+xml', 'rss')

        


        elif command == 'archive':
            # Requesting the archive page
            template = 'fullblog_archive.html'
            data['blog_archive'] = []
            for period, period_posts in group_posts_by_month(get_all_blog_posts(self.env)):
                allowed_posts = []
                for post in period_posts:
                    bp = BlogPost(self.env, post[0], post[1])
                    if 'BLOG_VIEW' in req.perm(bp.resource):
                        allowed_posts.append(post)
                if allowed_posts:
                    data['blog_archive'].append((period, allowed_posts))
            add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed',
                     'application/rss+xml', 'rss')

        elif command == 'view' and pagename:
            # Requesting a specific blog post
            the_post = BlogPost(self.env, pagename, version)
            req.perm(the_post.resource).require('BLOG_VIEW')
            if not the_post.version:
                raise HTTPNotFound("No blog post named '%s'." % pagename)
            if req.method == 'POST':   # Adding/Previewing a comment
                # Permission?
                req.perm(the_post.resource).require('BLOG_COMMENT')
                comment = BlogComment(self.env, pagename)
                comment.comment = req.args.get('comment', '')
                comment.author = (req.authname != 'anonymous' and req.authname) \
                            or req.args.get('author')
                comment.time = datetime.datetime.now(utc)
                warnings = []
                if 'cancelcomment' in req.args:
                    req.redirect(req.href.blog(pagename))
                elif 'previewcomment' in req.args:
                    warnings.extend(blog_core.create_comment(req, comment, verify_only=True))
                elif 'submitcomment' in req.args and not warnings:
                    warnings.extend(blog_core.create_comment(req, comment))
                    if not warnings:
                        req.redirect(req.href.blog(pagename
                                )+'#comment-'+str(comment.number))
                data['blog_comment'] = comment
                # Push all warnings out to the user.
                for field, reason in warnings:
                    if field:
                        add_warning(req, "Field '%s': %s" % (field, reason))
                    else:
                        add_warning(req, reason)
            data['blog_post'] = the_post
            context = Context.from_request(req, the_post.resource)
            data['context'] = context
            data['blog_attachments'] = AttachmentModule(self.env).attachment_data(context)
            # Previous and Next ctxtnav
            prev, next = blog_core.get_prev_next_posts(req.perm, the_post.name)
            if prev:
                add_link(req, 'prev', req.href.blog(prev), prev)
            if next:
                add_link(req, 'next', req.href.blog(next), next)
            if arity(prevnext_nav) == 4:
                # 0.12 compat following trac:changeset:8597
                prevnext_nav(req, 'Previous Post', 'Next Post')
            else:
                prevnext_nav(req, 'Post')

        elif command in ['create', 'edit']:
            template = 'fullblog_edit.html'
            default_pagename = blog_core._get_default_postname(req.authname)
            the_post = BlogPost(self.env, pagename or default_pagename)
            warnings = []

            if command == 'create' and req.method == 'GET' and not the_post.version:
                # Support appending query arguments for populating intial fields
                the_post.update_fields(req.args)
            if command == 'create' and the_post.version:
                # Post with name or suggested name already exists
                if 'BLOG_CREATE' in req.perm and the_post.name == default_pagename \
                                    and not req.method == 'POST':
                    if default_pagename:
                        add_notice(req, "Suggestion for new name already exists "
                            "('%s'). Please make a new name." % the_post.name)
                elif pagename:
                    warnings.append(
                        ('', "A post named '%s' already exists. Enter new name."
                                            % the_post.name))
                the_post = BlogPost(self.env, '')
            if command == 'edit':
                req.perm(the_post.resource).require('BLOG_VIEW') # Starting point
            if req.method == 'POST':
                # Create or edit a blog post
                if 'blog-cancel' in req.args:
                    if req.args.get('action','') == 'edit':
                        req.redirect(req.href.blog(pagename))
                    else:
                        req.redirect(req.href.blog())
                # Assert permissions
                if command == 'create':
                    req.perm(Resource('blog', None)).require('BLOG_CREATE')
                elif command == 'edit':
                    if the_post.author == req.authname:
                        req.perm(the_post.resource).require('BLOG_MODIFY_OWN')
                    else:
                        req.perm(the_post.resource).require('BLOG_MODIFY_ALL')

                # Check input
                orig_author = the_post.author
                if not the_post.update_fields(req.args):
                    warnings.append(('', "None of the fields have changed."))
                version_comment = req.args.get('new_version_comment', '')
                if 'blog-preview' in req.args:
                    warnings.extend(blog_core.create_post(
                            req, the_post, req.authname, version_comment, verify_only=True))
                elif 'blog-save' in req.args and not warnings:
                    warnings.extend(blog_core.create_post(
                            req, the_post, req.authname, version_comment))
                    if not warnings:
                        req.redirect(req.href.blog(the_post.name))
                context = Context.from_request(req, the_post.resource)
                data['context'] = context
                data['blog_attachments'] = AttachmentModule(self.env).attachment_data(context)
                data['blog_action'] = 'preview'
                data['blog_version_comment'] = version_comment
                if (orig_author and orig_author != the_post.author) and (
                        not 'BLOG_MODIFY_ALL' in req.perm(the_post.resource)):
                    add_notice(req, "If you change the author you cannot " \
                        "edit the post again due to restricted permissions.")
                    data['blog_orig_author'] = orig_author
            for field, reason in warnings:
                if field:
                    add_warning(req, "Field '%s': %s" % (field, reason))
                else:
                    add_warning(req, reason)
            data['blog_edit'] = the_post

        elif command == 'delete':
            bp = BlogPost(self.env, pagename)
            req.perm(bp.resource).require('BLOG_ADMIN')
            if 'blog-cancel' in req.args:
                req.redirect(req.href.blog(pagename))
            comment = int(req.args.get('comment', '0'))
            warnings = []
            if comment:
                # Deleting a specific comment
                bc = BlogComment(self.env, pagename, comment)
                if not bc.number:
                    raise TracError(
                            "Cannot delete. Blog post name and/or comment number missing.")
                if req.method == 'POST' and comment and pagename:
                    warnings.extend(blog_core.delete_comment(bc))
                    if not warnings:
                        add_notice(req, "Blog comment %d deleted." % comment)
                        req.redirect(req.href.blog(pagename))
                template = 'fullblog_delete.html'
                data['blog_comment'] = bc
            else:
                # Delete a version of a blog post or all versions
                # with comments and attachments if only version.
                if not bp.version:
                    raise TracError(
                            "Cannot delete. Blog post '%s' does not exist." % (
                                    bp.name))
                version = int(req.args.get('version', '0'))
                if req.method == 'POST':
                    if 'blog-version-delete' in req.args:
                        if bp.version != version:
                            raise TracError(
                                "Cannot delete. Can only delete most recent version.")
                        warnings.extend(blog_core.delete_post(bp, version=bp.versions[-1]))
                    elif 'blog-delete' in req.args:
                        version = 0
                        warnings.extend(blog_core.delete_post(bp, version=version))
                    if not warnings:
                        if version > 1:
                            add_notice(req, "Blog post '%s' version %d deleted." % (
                                                pagename, version))
                            req.redirect(req.href.blog(pagename))
                        else:
                            add_notice(req, "Blog post '%s' deleted." % pagename)
                            req.redirect(req.href.blog())
                template = 'fullblog_delete.html'
                data['blog_post'] = bp
            for field, reason in warnings:
                if field:
                    add_warning(req, "Field '%s': %s" % (field, reason))
                else:
                    add_warning(req, reason)                        

        elif command.startswith('listing-'):
            # 2007/10 or category/something or author/theuser
            title = category = author = ''
            from_dt = to_dt = None
            if command == 'listing-month':
                from_dt = listing_data['from_dt']
                to_dt = listing_data['to_dt']
                title = "Posts for the month of %s %d" % (
                        blog_month_names[from_dt.month -1], from_dt.year)
                add_link(req, 'alternate', req.href.blog(format='rss'), 'RSS Feed',
                        'application/rss+xml', 'rss')

            elif command == 'listing-category':
                category = listing_data['category']
                if category:
                    title = "Posts in category %s" % category
                    add_link(req, 'alternate', req.href.blog('category', category,
                        format='rss'), 'RSS Feed', 'application/rss+xml', 'rss')
            elif command == 'listing-author':
                author = listing_data['author']
                if author:
                    title = "Posts by author %s" % author
                    add_link(req, 'alternate', req.href.blog('author', author,
                        format='rss'), 'RSS Feed', 'application/rss+xml', 'rss')
            if not (author or category or (from_dt and to_dt)):
                raise HTTPNotFound("Not a valid path for viewing blog posts.")
            blog_posts = []
            for post in get_blog_posts(self.env, category=category,
                        author=author, from_dt=from_dt, to_dt=to_dt):
                bp = BlogPost(self.env, post[0], post[1])
                if 'BLOG_VIEW' in req.perm(bp.resource):
                    blog_posts.append(bp)
            data['blog_post_list'] = blog_posts
            data['blog_list_title'] = title
        else:
            raise HTTPNotFound("Not a valid blog path.")

        if (not command or command.startswith('listing-')) and format == 'rss':
            data['context'] = Context.from_request(req, absurls=True)
            data['blog_num_items'] = self.num_items
            return 'fullblog.rss', data, 'application/rss+xml'

        data['blog_months'], data['blog_authors'], data['blog_categories'], \
                data['blog_total'] = \
                    blog_core.get_months_authors_categories(
                        user=req.authname, perm=req.perm)
        if 'BLOG_CREATE' in req.perm('blog'):
            add_ctxtnav(req, 'New Post', href=req.href.blog('create'),
                    title="Create new Blog Post")
        add_stylesheet(req, 'tracfullblog/css/fullblog.css')
        add_stylesheet(req, 'common/css/code.css')
        data['blog_personal_blog'] = self.env.config.getbool('fullblog',
                                                'personal_blog')
        b=data['blog_categories']
        data['blog_categories']=sorted(b, key =lambda b:b[1],reverse=True)
        return (template, data, None)