Example #1
0
    def process_request(self, req):
        """Processes requests to the '/watchlist' path."""
        user = to_unicode(req.authname)

        # Reject anonymous users
        if not user or user == 'anonymous':
            # TRANSLATOR: Link part of
            # "Please %(log_in)s to view or change your watchlist"
            log_in = tag.a(_("log in"), href=req.href('login'))
            if tag_ == None:
                # For Trac 0.11
                raise HTTPNotFound(
                    tag("Please ", log_in,
                        " to view or change your watchlist"))
            else:
                # For Trac 0.12
                raise HTTPNotFound(
                    tag_("Please %(log_in)s to view or change your watchlist",
                         log_in=log_in))

        # Get and format request arguments
        realm = to_unicode(req.args.get('realm', u''))
        resid = ensure_string(req.args.get('resid', u'')).strip()
        action = req.args.get('action', 'view')
        async = req.args.get('async', 'false') == 'true'

        # Handle AJAX search early to speed up things
        if action == "search":
            """AJAX search request. At the moment only used to get list
               of all not watched resources."""
            handler = self.realm_handler[realm]
            query = to_unicode(req.args.get('q', u'')).strip()
            group = to_unicode(req.args.get('group', u'notwatched'))
            if not query:
                req.send('', 'text/plain', 200)
            if group == 'notwatched':
                result = list(
                    handler.unwatched_resources(realm,
                                                query,
                                                user,
                                                self,
                                                fuzzy=1))
            else:
                result = list(
                    handler.watched_resources(realm,
                                              query,
                                              user,
                                              self,
                                              fuzzy=1))
            result.sort(cmp=handler.get_sort_cmp(realm),
                        key=handler.get_sort_key(realm))
            req.send(
                unicode(u'\n'.join(result) + u'\n').encode("utf-8"),
                'text/plain', 200)

        # DB cursor
        db = self.env.get_db_cnx()
        cursor = db.cursor()

        wldict = dict()
        for k, v in req.args.iteritems():
            try:
                wldict[str(k)] = v
            except:
                pass

        wldict['action'] = action

        onwatchlistpage = req.environ.get('HTTP_REFERER', '').find(
            req.href.watchlist()) != -1

        settings = self.get_settings(user)
        options = settings['booloptions']
        self.options = options
        # Needed here to get updated settings
        if action == "save":
            newoptions = req.args.get('booloptions', [])
            for k in settings['booloptions'].keys():
                settings['booloptions'][k] = k in newoptions
            for realm in self.realms:
                settings[realm + '_fields'] = req.args.get(
                    realm + '_fields', '').split(',')
            for l in settings['listoptions']:
                if l in req.args:
                    settings['listoptions'][l] = [
                        e.strip() for e in req.args.get(l).split(',')
                    ]
            self._save_user_settings(req.authname, settings)

            # Clear session cache for nav items
            try:
                # Clear session cache for nav items, so that the post processor
                # rereads the settings
                del req.session['watchlist_display_notify_navitems']
            except:
                pass
            req.redirect(req.href('watchlist'))
        elif action == "defaultsettings":
            # Only execute if sent using the watchlist preferences form
            if onwatchlistpage and req.method == 'POST':
                self._delete_user_settings(req.authname)
            req.redirect(req.href('watchlist'))

        redirectback_notify = options['stay_at_resource_notify'] and not \
                              onwatchlistpage and not async
Example #2
0
    def process_request(self, req):
        """Processes requests to the '/watchlist' path."""
        user  = to_unicode( req.authname )

        # Reject anonymous users
        if not user or user == 'anonymous':
            # TRANSLATOR: Link part of
            # "Please %(log_in)s to view or change your watchlist"
            log_in=tag.a(_("log in"), href=req.href('login'))
            if tag_ == None:
                # For Trac 0.11
                raise HTTPNotFound(
                        tag("Please ", log_in, " to view or change your watchlist"))
            else:
                # For Trac 0.12
                raise HTTPNotFound(
                        tag_("Please %(log_in)s to view or change your watchlist",
                            log_in=log_in))

        # Get and format request arguments
        realm = to_unicode( req.args.get('realm', u'') )
        resid = ensure_string( req.args.get('resid', u'') ).strip()
        action = req.args.get('action','view')
        async = req.args.get('async', 'false') == 'true'

        # Handle AJAX search early to speed up things
        if action == "search":
            """AJAX search request. At the moment only used to get list
               of all not watched resources."""
            handler = self.realm_handler[realm]
            query = to_unicode( req.args.get('q', u'') ).strip()
            group = to_unicode( req.args.get('group', u'notwatched') )
            if not query:
                req.send('', 'text/plain', 200 )
            if group == 'notwatched':
                result = list(handler.unwatched_resources(realm, query, user, self, fuzzy=1))
            else:
                result = list(handler.watched_resources(realm, query, user, self, fuzzy=1))
            result.sort(cmp=handler.get_sort_cmp(realm),
                        key=handler.get_sort_key(realm))
            req.send( unicode(u'\n'.join(result) + u'\n').encode("utf-8"),
                'text/plain', 200 )

        # DB cursor
        db = self.env.get_db_cnx()
        cursor = db.cursor()

        wldict = dict()
        for k,v in req.args.iteritems():
            try:
                wldict[str(k)] = v
            except:
                pass

        wldict['action'] = action

        onwatchlistpage = req.environ.get('HTTP_REFERER','').find(
                          req.href.watchlist()) != -1

        settings = self.get_settings( user )
        options = settings['booloptions']
        self.options = options
        # Needed here to get updated settings
        if action == "save":
            newoptions = req.args.get('booloptions',[])
            for k in settings['booloptions'].keys():
                settings['booloptions'][k] = k in newoptions
            for realm in self.realms:
                settings[realm + '_fields'] = req.args.get(realm + '_fields', '').split(',')
            for l in settings['listoptions']:
                if l in req.args:
                    settings['listoptions'][l] = [ e.strip() for e in req.args.get(l).split(',')]
            self._save_user_settings(req.authname, settings)

            # Clear session cache for nav items
            try:
                # Clear session cache for nav items, so that the post processor
                # rereads the settings
                del req.session['watchlist_display_notify_navitems']
            except:
                pass
            req.redirect(req.href('watchlist'))
        elif action == "defaultsettings":
            # Only execute if sent using the watchlist preferences form
            if onwatchlistpage and req.method == 'POST':
                self._delete_user_settings(req.authname)
            req.redirect(req.href('watchlist'))

        redirectback_notify = options['stay_at_resource_notify'] and not \
                              onwatchlistpage and not async
Example #3
0
    def get_list(self, realm, wl, req, fields=None):
        db = self.env.get_db_cnx()
        cursor = db.cursor()
        user = req.authname
        locale = getattr( req, 'locale', LC_TIME)
        context = Context.from_request(req)
        wikilist = []
        extradict = {}
        if not fields:
            fields = set(self.default_fields['wiki'])
        else:
            fields = set(fields)

        if 'changetime' in fields:
            max_changetime = datetime(1970,1,1,tzinfo=utc)
            min_changetime = datetime.now(utc)

        for name, last_visit in wl.get_watched_resources( 'wiki', req.authname ):
            wikipage = WikiPage(self.env, name, db=db)
            wikidict = {}

            if not wikipage.exists:
                wikidict['deleted'] = True
                if 'name' in fields:
                    wikidict['name'] = name
                if 'author' in fields:
                    wikidict['author'] = '?'
                if 'changetime' in fields:
                    wikidict['changedsincelastvisit'] = 1
                    wikidict['changetime'] = '?'
                    wikidict['ichangetime'] = 0
                if 'comment' in fields:
                    wikidict['comment'] = tag.strong(t_("deleted"), class_='deleted')
                if 'notify' in fields:
                    wikidict['notify'] =  wl.is_notify(req, 'wiki', name)
                wikilist.append(wikidict)
                continue

            comment = wikipage.comment
            changetime = wikipage.time
            author = wikipage.author
            if wl.options['attachment_changes']:
                latest_attachment = None
                for attachment in Attachment.select(self.env, 'wiki', name, db):
                    if attachment.date > changetime:
                        latest_attachment = attachment
                if latest_attachment:
                    changetime = latest_attachment.date
                    author = latest_attachment.author
                    if 'comment' in fields:
                        wikitext = '[attachment:"' + ':'.join([latest_attachment.filename,'wiki',name]) + \
                                   '" ' + latest_attachment.filename  + ']'
                        desc = latest_attachment.description
                        comment = tag(tag_("Attachment %(attachment)s added",\
                                attachment=format_to_oneliner(self.env, context, wikitext, shorten=False)),
                                desc and ': ' or '.', moreless(desc,10))
            if 'attachment' in fields:
                attachments = []
                for attachment in Attachment.select(self.env, 'wiki', name, db):
                    wikitext = '[attachment:"' + ':'.join([attachment.filename,'wiki',name]) + '" ' + attachment.filename  + ']'
                    attachments.extend([tag(', '), format_to_oneliner(self.env, context, wikitext, shorten=False)])
                if attachments:
                    attachments.reverse()
                    attachments.pop()
                ticketdict['attachment'] = moreless(attachments, 5)
            if 'name' in fields:
                wikidict['name'] = name
            if 'author' in fields:
                if not (Chrome(self.env).show_email_addresses or
                        'EMAIL_VIEW' in req.perm(wikipage.resource)):
                    wikidict['author'] = obfuscate_email_address(author)
                else:
                    wikidict['author'] = author
            if 'version' in fields:
                wikidict['version'] = unicode(wikipage.version)
            if 'changetime' in fields:
                wikidict['changetime'] = format_datetime( changetime, locale=locale, tzinfo=req.tz )
                wikidict['ichangetime'] = to_timestamp( changetime )
                wikidict['changedsincelastvisit'] = last_visit < wikidict['ichangetime'] and 1 or 0
                wikidict['timedelta'] = pretty_timedelta( changetime )
                wikidict['timeline_link'] = req.href.timeline(precision='seconds',
                    from_=trac_format_datetime ( changetime, 'iso8601', tzinfo=req.tz))
                if changetime > max_changetime:
                    max_changetime = changetime
                if changetime < min_changetime:
                    min_changetime = changetime
            if 'comment' in fields:
                comment = moreless(comment or "", 200)
                wikidict['comment'] = comment
            if 'notify' in fields:
                wikidict['notify']   = wl.is_notify(req, 'wiki', name)
            if 'readonly' in fields:
                wikidict['readonly'] = wikipage.readonly and t_("yes") or t_("no")
            if 'tags' in fields and self.tagsystem:
                tags = []
                for t in self.tagsystem.get_tags(req, Resource('wiki', name)):
                    tags.extend([tag.a(t,href=req.href('tags',q=t)), tag(', ')])
                if tags:
                    tags.pop()
                wikidict['tags'] = moreless(tags, 10)
            #if 'ipnr' in fields:
            #    wikidict['ipnr'] = wikipage.ipnr,  # Note: Not supported by Trac 0.12
            wikilist.append(wikidict)

        if 'changetime' in fields:
            extradict['max_changetime'] = format_datetime( max_changetime, locale=locale, tzinfo=req.tz )
            extradict['min_changetime'] = format_datetime( min_changetime, locale=locale, tzinfo=req.tz )

        return wikilist, extradict