Beispiel #1
0
 def testExist(self):
     """Tests if Page().exists() is working correctly."""
     from Sycamore.Page import Page
     cannot_possibly_exist = make_impossible_pages(self.request, 200)
     for pagename in cannot_possibly_exist:
         page = Page(pagename, self.request)
         self.assertFalse(page.exists())
Beispiel #2
0
def execute(macro, args, formatter):
    if not formatter:
        formatter = macro.formatter
    # get number of wanted links        
    try:
        links = max(int(args), 1)
    except StandardError:
        links = 1

    # select the pages from the page list
    random_list = wikiutil.getRandomPages(macro.request)
    pages = []
    while len(pages) < links and random_list:
        pagename = random.choice(random_list)
        page = Page(pagename, macro.request)
        if macro.request.user.may.read(page) and page.exists():
            pages.append(page)

    # return a single page link
    if links == 1:
        return pages[0].link_to()

    # return a list of page links
    pages.sort()
    result = [macro.formatter.bullet_list(1)]
    for page in pages:
        result.append("%s%s%s" %
                      (macro.formatter.listitem(1), page.link_to(),
                       macro.formatter.listitem(0)))
    result.append(macro.formatter.bullet_list(0))

    return ''.join(result)
Beispiel #3
0
def execute(macro, args, formatter=None):
    if not formatter:
        formatter = macro.formatter
    _ = macro.request.getText

    pagename = args or 'Fortune Cookies'
    page = Page(pagename, macro.request)
    raw = page.get_raw_body(fresh=macro.request.set_cache)
    if not macro.request.user.may.read(page):
        raw = ""

    # this selects lines looking like a list item
    # !!! TODO: make multi-line quotes possible
    # (optionally split by "----" or something)
    quotes = raw.splitlines()
    quotes = [quote.strip() for quote in quotes]
    quotes = [quote[2:] for quote in quotes if quote.startswith('* ')]
    
    if not quotes:
        return (macro.formatter.highlight(1) +
                _('No quotes on %(pagename)s.') % {'pagename': pagename} +
                macro.formatter.highlight(0))
                
    quote = random.choice(quotes)

    if quote.lower().find("randomquote") == -1:
        quote = wikiutil.wikifyString(quote, macro.request, page, strong=True)
        quote = wikiutil.stripOuterParagraph(quote)

    return quote
Beispiel #4
0
def execute(pagename, request):
    _ = request.getText
    request.formatter = Formatter(request)
    page = Page(pagename, request)
    if not page.page_name.startswith(config.user_page_prefix.lower()):
        return page.send_page(msg="Not a user page.")
    username = pagename[len(config.user_page_prefix):]

    request.http_headers()

    wikiutil.simple_send_title(request, pagename,
                               strict_title="User %s's information" % username)


    request.write('<div id="content" class="content">\n\n')
    InfoBar(request, page).render()
    request.write('<div id="tabPage">')

    if config.wiki_farm:
    	request.write('<h3>Watched Wikis</h3>')
	display_watched_wikis(request, username)

    request.write('<h3>Bookmarks</h3>\n')
    display_bookmarks(request, username)

    request.write('<h3>Edits</h3>\n')
    display_edits(request, username, pagename)

    request.write('</div></div>')
    wikiutil.send_footer(request, pagename, showpage=1, noedit=True)
Beispiel #5
0
def get_group_members(groupname, request):
  members = {}
  page_text = Page(groupname, request).get_raw_body(fresh=True)
  for line in page_text.split('\n'):
    if line.startswith(' *'):
      username = line[len(' *'):].strip()
      members[username.lower()] = None
  return members
Beispiel #6
0
def execute(pagename, request):
    page = Page(pagename, request)
    msg = None
    form = request.form

    if form.has_key('id'):
        id = request.form['id'][0]
        return send_human_readable(id, request)
    return page.send_page(msg=msg)
Beispiel #7
0
def execute(pagename, request):
    page = Page(pagename, request)
    msg = None
    form = request.form

    if form.has_key("id"):
        id = request.form["id"][0]
        return send_human_readable(id, request)
    return page.send_page(msg=msg)
Beispiel #8
0
        def process(self):
            if not self.query:
                return
            # processes the search
            enquire = xapian.Enquire(self.text_database)
            enquire.set_query(self.query)
            t0 = time.time()

            matches = self._get_matchset(enquire, self.text_database,
                                         self.p_start_loc, self.num_results+1)
            
            self.estimated_results = matches.get_matches_estimated()
            t1 = time.time()
            for match in matches:
                id = match[xapian.MSET_DOCUMENT].get_value(0)
                wiki_name = self.request.config.wiki_name
                if config.wiki_farm:
                    title, wiki_name = get_id(id)
                    # xapian uses utf-8
                    title = title.decode('utf-8')
                    wiki_name = wiki_name.decode('utf-8')
                else:
                    title = get_id(id).decode('utf-8')
                page = Page(title, self.request, wiki_name=wiki_name)
                if not page.exists():
                    continue
                percentage = match[xapian.MSET_PERCENT]
                data = page.get_raw_body()
                search_item = searchResult(title, data, percentage,
                                           page.page_name, wiki_name)
                self.text_results.append(search_item)
    
            enquire = xapian.Enquire(self.title_database)
            enquire.set_query(self.query)
            matches = self._get_matchset(enquire, self.text_database,
                                         self.t_start_loc, self.num_results+1)

            self.estimated_results += matches.get_matches_estimated()
            for match in matches:
                id = match[xapian.MSET_DOCUMENT].get_value(0)
                wiki_name = self.request.config.wiki_name
                if config.wiki_farm:
                    title, wiki_name = get_id(id)
                    # xapian uses utf-8
                    title = title.decode('utf-8')
                    wiki_name = wiki_name.decode('utf-8')
                else:
                    title = get_id(id).decode('utf-8')
                page = Page(title, self.request, wiki_name=wiki_name)
                if not page.exists():
                    continue
                percentage = match[xapian.MSET_PERCENT]
                data = page.page_name
                search_item = searchResult(title, data, percentage,
                                           page.page_name, wiki_name)
                self.title_results.append(search_item)
Beispiel #9
0
 def rebuild_page_cache():
     """
     Rebuilds the page cache.
     """
     if not request.generating_cache and not request.previewing_page:
         from Sycamore import caching
         from Sycamore.Page import Page
         page = Page(dict['pagename'], request)
         if page.exists():
             page.buildCache()
Beispiel #10
0
def execute(pagename, request):
    _ = request.getText
    page = Page(pagename, request.cursor)
    if request.user.may.read(pagename):
        badwords, badwords_re, msg = checkSpelling(page, request)
    else:
        badwords = []
        msg = _("You can't check spelling on a page you can't read.")

    if badwords:
        page.send_page(request, msg=msg, hilite_re=badwords_re)
    else:
        page.send_page(request, msg=msg)
Beispiel #11
0
    def __init__(self, page_name, request, **keywords):
        """
        Create page editor object.
        
        @param page_name: name of the page
        @param request: the request object
        @keyword do_revision_backup: if 0, suppress making a page backup
                                     per revision
        """
        self.request = request
        self._ = request.getText
        Page.__init__(self, page_name, request, **keywords)

        self.do_revision_backup = keywords.get('do_revision_backup', 1)
Beispiel #12
0
    def __init__(self, page_name, request, **keywords):
        """
        Create page editor object.
        
        @param page_name: name of the page
        @param request: the request object
        @keyword do_revision_backup: if 0, suppress making a page backup
                                     per revision
        """
        self.request = request
        self._ = request.getText
        Page.__init__(self, page_name, request, **keywords)

        self.do_revision_backup = keywords.get('do_revision_backup', 1)
Beispiel #13
0
def get_versions(page, file):
    """
    Write the text for all the versions of the page.
    """
    page.request.cursor.execute(
        """SELECT propercased_name, editTime, userEdited, editType,
                comment, userIP
         from allPages
         where name=%(pagename)s and wiki_id=%(wiki_id)s
         order by editTime desc""", {
            'pagename': page.page_name,
            'wiki_id': page.wiki_id
        })

    for result in page.request.cursor.fetchall():
        d = {
            'propercased_name': result[0],
            'edit_time': result[1],
            'user_edited': get_username(result[2], page.request),
            'edit_type': result[3].strip(),
            'comment': result[4],
            'user_ip': result[5]
        }
        file.write('<version %s>\n' % generate_attributes(d))
        version = Page(page.page_name, page.request, prev_date=d['edit_time'])
        get_page_text(version, file)
        file.write('</version>\n')
Beispiel #14
0
def events(request, file):
    """
    Export all of the events data.
    """
    events_page = Page('Events Board', request)
    if (not command_line and not request.user.may.read(events_page)):
        return
    start_events(request, file)
    request.cursor.execute(
        """SELECT event_time, posted_by, location, event_name,
                  posted_by_ip, posted_time, text
           FROM events WHERE wiki_id=%(wiki_id)s""",
        {'wiki_id': request.config.wiki_id})
    for result in request.cursor.fetchall():
        d = {
            'event_time': result[0],
            'posted_by': result[1],
            'location': result[2],
            'event_name': result[3],
            'posted_by_ip': result[4],
            'posted_time': result[5]
        }
        text = result[6]

        file.write('<event %s>' % generate_attributes(d))
        file.write(text.encode(config.charset))
        file.write('</event>\n')

    end_events(request, file)
Beispiel #15
0
def build(wiki_name, pname, doprint=False, req=None, super=False):
    given_req = True
    if not req:
        req = request.RequestDummy(wiki_name=wiki_name)
        given_req = False

    page = Page(pname, req)
    page.buildCache()
    if super:
        wikiutil.macro_delete_checks(page)

    if not given_req:
        req.db_disconnect()

    if doprint:
        print "  -->", pname.encode(config.charset)
Beispiel #16
0
    def _consider_talk_link(self, links):
        if not self.request.config.talk_pages:
            return links
        lower_links = [ link.lower() for link in links ]
        from Sycamore.Page import Page
        pagename = self.key
        page = Page(pagename, self.request)
        linkto_name = None
        if page.isTalkPage():
            article_page = Page(wikiutil.talk_to_article_pagename(pagename),
                                self.request)
            article_pagename = article_page.proper_name()
            if article_pagename.lower() not in lower_links:
                links.append(article_pagename)
        else:
            talk_pagename = wikiutil.article_to_talk_pagename(pagename)
            talk_page = Page(talk_pagename, self.request)

            # add dependency so that editing/creating the talk page
            # has an affect on the article page's links
            dependency(pagename, talk_pagename.lower(), self.request)

            if talk_page.exists():
                talk_pagename = talk_page.proper_name()
                if talk_pagename.lower() not in lower_links:
                    links.append(talk_pagename)

        return links
Beispiel #17
0
def do_user_browser(request):
    """ Browser for SystemAdmin macro. """
    from Sycamore.util.dataset import TupleDataset, Column
    from Sycamore.Page import Page
    _ = request.getText

    data = TupleDataset()
    data.columns = [
        Column('id', label=('ID'), align='right'),
        Column('name', label=('Username')),
        Column('email', label=('Email')),
        Column('action', label=_('Action')),
    ]

    # Iterate over users
    for uid in user.getUserList(self.request.cursor):
        account = user.User(request, uid)

        userhomepage = Page(account.name, self.request)
        if userhomepage.exists():
            namelink = userhomepage.link_to()
        else:
            namelink = account.name

        data.addRow((
            request.formatter.code(1) + uid + request.formatter.code(0),
            request.formatter.rawHTML(namelink),
            request.formatter.url('mailto:' + account.email, account.email,
                                  'external', pretty_url=1, unescaped=1),
            '',
        ))

    if data:
        from Sycamore.widget.browser import DataBrowserWidget

        browser = DataBrowserWidget(request)
        browser.setData(data)
        return browser.toHTML()

    # No data
    return ''
Beispiel #18
0
    def sendCancel(self, newtext, datestamp):
        """
        User clicked on Cancel button.
        
        @param newtext: the edited text (which has been cancelled)
        @param datestamp: ...
        """
        _ = self._

        backto = self.request.form.get('backto', [None])[0]
        page = backto and Page(backto, self.request) or self
        page.send_page(msg=_('Edit was cancelled.'))
Beispiel #19
0
def execute(macro, args, formatter=None):
    formatter = macro.formatter
    if not args:
        page = macro.formatter.page
    else:
        page = Page(args, macro.request)
    links_here = page.getPageLinksTo()
    pages_deco = [(pagename.lower(), pagename) for pagename in links_here]
    pages_deco.sort()
    links_here = [word for lower_word, word in pages_deco]

    text = []
    if links_here:
        text.append(formatter.bullet_list(1))
        for link in links_here:
            text.append(
                "%s%s%s" % (formatter.listitem(1), formatter.pagelink(link, generated=True), formatter.listitem(0))
            )
        text.append(formatter.bullet_list(0))

    return "".join(text)
Beispiel #20
0
def execute(macro, args, formatter=None):
    if not formatter:
        formatter = macro.formatter

    cursor = macro.request.cursor
    cursor.execute("""
        SELECT c.propercased_name, count(c.source_pagename) as cnt
        FROM (
            SELECT curPages.propercased_name, links.source_pagename
            FROM curPages LEFT JOIN links on
                (links.source_pagename=curPages.name and
                 links.wiki_id=%(wiki_id)s and
                 curPages.wiki_id=%(wiki_id)s)
            WHERE curPages.wiki_id=%(wiki_id)s
        ) as c
        GROUP BY c.propercased_name ORDER BY cnt""",
        {'wiki_id': macro.request.config.wiki_id})
    results = cursor.fetchall()
   
    old_count = -1
    for entry in results:
        name = entry[0] 
        lower_name = name.lower()
        if skip_page(name):
            continue
        
        new_count = entry[1]
        page = Page(name, macro.request)
        if new_count == 0 and page.isRedirect():
            continue

        if new_count != old_count:
            old_count = new_count
            macro.request.write(macro.formatter.heading(2, str(new_count)))
        else:
            macro.request.write(", ")
        macro.request.write(page.link_to(know_status=True,
                                         know_status_exists=True))

    return ''
Beispiel #21
0
    def talkicon(self, d):
        if not self.request.config.talk_pages:
            return ''

        if d['page'].isTalkPage():
           article_name = wikiutil.talk_to_article_pagename(d['page_name'])

           icon = self.get_editable_icon('articleicon.png', 'Article')
           
           return ('<td class="pageIcon"><span id="articleIcon">'
                   '%s</span></td>' %
                   (wikiutil.link_tag_explicit(
                       'style="text-decoration: none;"', self.request,
                       wikiutil.quoteWikiname(article_name), icon,
                       script_name=d['script_name'])))
        else:
            talk_page = Page(wikiutil.article_to_talk_pagename(d['page_name']),
                             self.request)

            icon = self.get_editable_icon('talkicon.png', 'Talk')

            if talk_page.exists():
                return ('<td class="pageIcon"><span id="talkIcon">'
                        '%s</span></td>' %
                        (wikiutil.link_tag_explicit(
                            'style="text-decoration: none;"', self.request,
                            wikiutil.quoteWikiname(d['page_name'])+'/Talk',
                            icon, script_name=d['script_name'])))
            else:
                # if the viewer can't edit the talk page, let's spare them
                # from looking at a useless link to an empty page:
                if not self.request.user.may.edit(talk_page):
                    return ''
                return ('<td class="pageIcon"><span id="talkIcon">'
                        '%s</span></td>' %
                        (wikiutil.link_tag_explicit(
                            'class="tinyNonexistent"', self.request,
                            wikiutil.quoteWikiname(d['page_name'])+'/Talk',
                            icon, script_name=d['script_name'])))
Beispiel #22
0
def rename_old_user_pages(request):
    from Sycamore import user
    for wikiname in wikiutil.getWikiList(request):
        request.switch_wiki(wikiname)
        user_pages = _get_user_pages(request) 
        num_user_pages = len(user_pages)
        n = 0
        for page in user_pages:
            new_user_pagename = config.user_page_prefix + page.proper_name()
            new_user_page = Page(new_user_pagename, request)
            if new_user_page.exists():
                # something crazzzzy is going on
                continue 
            old_pagename_propercased = page.proper_name()
            d = {'new_name': new_user_pagename.lower(), 'new_propercased_name': new_user_pagename,
                'old_pagename': page.page_name, 'wiki_id': request.config.wiki_id,
                'wiki_name': request.config.wiki_name, 'latest_ed_time': page.mtime(),
                'old_propercased_name': page.proper_name()}

            print page.page_name, '->', new_user_pagename
            _user_page_move(request, copy(d))
            _user_page_redirect(request, d)
            n += 1
Beispiel #23
0
    def _subpages(self):
        possible_subpages = self.pagename.split('/') 
        max_number_possible = len(possible_subpages)
        n = 1
        pagelinks = []
        pagenames_queue = []
        while n <= max_number_possible:
            pagename = possible_subpages[-n]
            parent_pagename = '/'.join(possible_subpages[:-n])
            parent_page = Page(parent_pagename, self.request)
            pagenames_queue.append(pagename)
            if parent_page.exists() or parent_page.page_name == 'users':
                pagenames_queue.reverse()
                display_name = '/'.join(pagenames_queue)
                pagelinks.append(
                    ('%s/%s' % (parent_pagename, display_name), display_name))
                pagenames_queue = []

            n += 1

        pagenames_queue.reverse()
        pagelinks.append(('/'.join(pagenames_queue), '/'.join(pagenames_queue)))
        pagelinks.reverse()
        return pagelinks
Beispiel #24
0
def execute(pagename, request):
    page = Page(pagename, request)
    gmaps_api_key = request.config.gmaps_api_key or config.gmaps_api_key
    script_loc = (
        '<script src="http://maps.google.com/maps?file=api&v=2&key=%s" '
        'type="text/javascript"></script>' % gmaps_api_key)
    script_loc += ('<script src="%s/wiki/gmap.js" type="text/javascript">'
                   '</script>' % config.web_dir)
    wiki_name, page_locs, nearby_locs = get_map_info(request)
    map_html = mapJS(wiki_name, page_locs, nearby_locs, request)
    html = ('<html><head>%s</head>'
            '<body onLoad="loadMap();" style="padding:0;margin:0;">'
            '<div id="map" style="width: 450px; height: 300px; margin:0; '
            'padding:0; border:none;">'
            '</div>%s</body></html>' % (script_loc, map_html))
    request.http_headers()
    request.write(html)
Beispiel #25
0
def getPageList(request, objects=True):
    """
    Generate a "master" pagelist of all pages that have
    ever existed!
    """
    request.cursor.execute(
        """SELECT name FROM allPages
           WHERE wiki_id=%(wiki_id)s
           GROUP BY name""", {'wiki_id': request.config.wiki_id})
    page_list = []
    for result in request.cursor.fetchall():
        page_name = result[0]
        if objects:
            page_list.append(Page(page_name, request))
        else:
            page_list.append(page_name)
    return page_list
Beispiel #26
0
def execute(pagename, request):
    _ = request.getText
    page = Page(pagename, request.cursor)
    if request.user.may.read(pagename):
        badwords, badwords_re, msg = checkSpelling(page, request)
    else:
        badwords = []
        msg = _("You can't check spelling on a page you can't read.")

    if badwords:
        page.send_page(request, msg=msg, hilite_re=badwords_re)
    else:
        page.send_page(request, msg=msg)
Beispiel #27
0
def writeEvent(request, event_text, event_name, event_location,
               event_time_unix, posted_by):
    posted_time = time.time()
    if config.db_type == 'mysql':
        request.cursor.execute(
            """INSERT into events
               (uid, event_time, posted_by, text, location, event_name,
                posted_time, posted_by_ip, wiki_id)
               values (NULL, %(event_time_unix)s, %(posted_by)s,
                       %(event_text)s, %(event_location)s, %(event_name)s,
                       %(posted_time)s, %(userip)s, %(wiki_id)s)""",
            {'id':id, 'event_time_unix':event_time_unix, 'posted_by':posted_by,
             'event_text':event_text, 'event_location':event_location,
             'event_name':event_name, 'posted_time':posted_time,
             'userip':request.remote_addr, 'wiki_id':request.config.wiki_id},
            isWrite=True)
    else:
        request.cursor.execute(
            """INSERT into events
               (uid, event_time, posted_by, text, location, event_name,
                posted_time, posted_by_ip, wiki_id)
               values (NEXTVAL('events_seq'), %(event_time_unix)s,
                       %(posted_by)s, %(event_text)s, %(event_location)s,
                       %(event_name)s, %(posted_time)s, %(userip)s,
                       %(wiki_id)s)""",
            {'id':id, 'event_time_unix':event_time_unix, 'posted_by':posted_by,
             'event_text':event_text, 'event_location':event_location,
             'event_name':event_name, 'posted_time':posted_time,
             'userip':request.remote_addr,
             'wiki_id':request.config.wiki_id}, isWrite=True)
    
    if config.memcache:
        # clear out today's events cache if the event is for today
        event_time_struct = time.gmtime(event_time_unix +
                                        request.config.tz_offset)
        event_day_unix = calendar.timegm(
            list(event_time_struct[0:3]) + [0,0,0,0,0,0])

        today_struct = time.gmtime(posted_time+request.config.tz_offset)
        today = list(today_struct[0:3]) + [0,0,0,0,0,0]
        today_unix = calendar.timegm(today)
        if event_day_unix == today_unix:
            request.mc.delete("today_events")
        caching.updateRecentChanges(Page("Events Board", request))
Beispiel #28
0
def execute(pagename, request):
    _ = request.getText
    page = Page(pagename, request)
    actname = __name__.split('.')[-1]
    if not request.user.may.admin(page):
        msg = _("You don't have admin permissions on this page, "
                "so you cannot change security settings.")
        return page.send_page(msg)

    if request.form.has_key('button'):
        # process save
        groups = []
        groups_dict = {}
        for key in request.form:
            if key.endswith('_groupname'):
                groups.append(unquoteWikiname(key[:-10]))
            else:
                if key.endswith('_may_read'):
                    dowhat = 'read'
                    groupname = unquoteWikiname(key[:-9])
                elif key.endswith('_may_edit'):
                    dowhat = 'edit'
                    groupname = unquoteWikiname(key[:-9])
                elif key.endswith('_may_delete'):
                    dowhat = 'delete'
                    groupname = unquoteWikiname(key[:-11])
                elif key.endswith('_may_admin'):
                    dowhat = 'admin'
                    groupname = unquoteWikiname(key[:-10])
                else:
                    continue

                if not groups_dict.has_key(groupname):
                    groups_dict[groupname] = [False, False, False, False]

                groups_dict[groupname][ACL_RIGHTS_TABLE[dowhat]] = True

        # set groups we weren't sent any checkboxes for to
        # all false (nothing checked)
        groups_no_checks = filter(
            lambda (groupname): (groupname not in groups_dict), groups)
        for groupname in groups_no_checks:
            groups_dict[groupname] = [False, False, False, False]

        wikiacl.setACL(pagename, groups_dict, request)
        return page.send_page(msg=_("Security settings sucessfully changed!"))

    formhtml = ['<h3>Security settings for "%s":</h3>' % pagename]

    button = _("Save")
    url = page.url()
    d = {'url': url, 'actname': actname, 'button': button}
    formhtml.append(
        '<form method="POST" action="%(url)s">\n'
        '<input type="hidden" name="action" value="%(actname)s">\n' % d)

    custom_groups = user.getGroupList(request, exclude_special_groups=True)
    grouplist = ['All', 'Known'] + custom_groups
    for groupname in grouplist:
        # "All" and "Known" are a bit condense
        if groupname == 'All':
            written_groupname = 'Everybody'
        elif groupname == 'Known':
            written_groupname = 'Logged in people'
        else:
            written_groupname = groupname

        group = wikiacl.Group(groupname, request, fresh=True)

        # we want to show the 'change security' option only if
        # it makes some sense
        show_admin = groupname in custom_groups

        formhtml.append('<h6>%s</h6>' % written_groupname)
        formhtml.append('<input type="hidden" name="%s_groupname" '
                        'value="1">' % quoteWikiname(groupname))
        if group.may(page, 'read'):
            formhtml.append('<input type="checkbox" checked '
                            'name="%s_may_read" value="1">' %
                            quoteWikiname(groupname))
        else:
            formhtml.append('<input type="checkbox" name="%s_may_read" '
                            'value="1">' % quoteWikiname(groupname))
        formhtml.append(' read ')

        if group.may(page, 'edit'):
            formhtml.append('<input type="checkbox" checked '
                            'name="%s_may_edit" value="1">' %
                            quoteWikiname(groupname))
        else:
            formhtml.append('<input type="checkbox" name="%s_may_edit" '
                            'value="1">' % quoteWikiname(groupname))
        formhtml.append(' edit ')

        if group.may(page, 'delete'):
            formhtml.append('<input type="checkbox" checked '
                            'name="%s_may_delete" value="1">' %
                            quoteWikiname(groupname))
        else:
            formhtml.append('<input type="checkbox" name="%s_may_delete" '
                            'value="1">' % quoteWikiname(groupname))
        formhtml.append(' delete ')

        if show_admin:
            if group.may(page, 'admin'):
                formhtml.append('<input type="checkbox" checked '
                                'name="%s_may_admin" value="1">' %
                                quoteWikiname(groupname))
            else:
                formhtml.append('<input type="checkbox" name="%s_may_admin" '
                                'value="1">' % quoteWikiname(groupname))
            formhtml.append(' change security ')

    formhtml.append(
        '<p><input type="submit" name="button" value="%(button)s">\n'
        '</p>\n'
        '</form>' % d)

    page.send_page(msg=''.join(formhtml))
Beispiel #29
0
def execute(macro, args, formatter=None):
    if not formatter:
        formatter = macro.formatter
    request = macro.request

    if args:
       # personalized stats
       htmltext = []
       theuser = user.User(macro.request, name=args.lower())
       wiki_info = theuser.getWikiInfo()
       if not wiki_info.first_edit_date:
            first_edit_date = "<em>unknown</em>"
       else:
            first_edit_date = request.user.getFormattedDateTime(
                wiki_info.first_edit_date)
       created_count = wiki_info.created_count
       edit_count = wiki_info.edit_count
       file_count = wiki_info.file_count
       last_page_edited = wiki_info.last_page_edited
       last_edit_date = wiki_info.last_edit_date
       if not last_edit_date:
            last_edit_date = "<em>unknown</em>"
       else:
            last_edit_date = request.user.getFormattedDateTime(last_edit_date)

       if last_page_edited:
            htmltext.append(
                '<p><h2>%s\'s Statistics</h2></p>'
                '<table width=100%% border=0><tr>'
                '<td><b>Edits&nbsp;&nbsp;</b></td>'
                '<td><b>Pages Created&nbsp;&nbsp;</b></td>'
                '<td><b>Files Contributed&nbsp;&nbsp;</b></td>'
                '<td><b>First Edit Date&nbsp;&nbsp;</b></td>'
                '<td><b>Last Edit&nbsp;&nbsp;</b></td>'
                '<td><b>Last Page Edited&nbsp;&nbsp;</b></td></tr>' % args)
            htmltext.append('<tr>'
                            '<td>%s</td><td>%s</td><td>%s</td><td>%s</td>'
                            '<td>%s</td><td>%s</td>'
                            '</tr></table>' %
                            (edit_count, created_count, file_count,
                             first_edit_date, last_edit_date,
                             Page(last_page_edited, request).link_to()))
       elif edit_count or wiki_info.first_edit_date:
            htmltext.append('<p><h2>%s\'s Statistics</h2></p>'
                            '<table width=100%% border=0><tr>'
                            '<td><b>Edits&nbsp;&nbsp;</b></td>'
                            '<td><b>Pages Created&nbsp;&nbsp;</b></td>'
                            '<td><b>Files Contributed&nbsp;&nbsp;</b></td>'
                            '<td><b>First Edit Date&nbsp;&nbsp;</b></td>'
                            '<td><b>Last Edit&nbsp;&nbsp;</b></td>'
                            '<td><b>Last Page Edited&nbsp;&nbsp;</b></td>'
                            '</tr>' % args)
            htmltext.append('<tr>'
                            '<td>%s</td><td>%s</td><td>%s</td><td>%s</td>'
                            '<td>%s</td><td>&nbsp;</td>'
                            '</tr></table>' %
                            (edit_count, created_count, file_count,
                             first_edit_date, last_edit_date))
       else:
            htmltext.append('<p>' + macro.formatter.highlight(1) +
                            'The user "%s" has not edited this wiki.' % args +
                            macro.formatter.highlight(0) + '</p>')

    else:
        htmltext = []
        sort_by = 'edit_count'
        if macro.request.form.has_key('sort_by'):
            sort_by = macro.request.form['sort_by'][0]
            # this is to prevent SQL exploits
            if sort_by not in ['edit_count', 'created_count',
                               'first_edit_date', 'file_count',
                               'last_edit_date']:
                sort_by = 'edit_count'
        list = []
        cursor = macro.request.cursor
        if sort_by == 'first_edit_date':
            cursor.execute(
                """SELECT users.propercased_name, userWikiInfo.first_edit_date,
                          userWikiInfo.created_count, userWikiInfo.edit_count,
                          userWikiInfo.file_count,
                          userWikiInfo.last_page_edited,
                          userWikiInfo.last_edit_date,
                          userWikiInfo.first_edit_date IS NULL AS join_isnull
                   FROM userWikiInfo, users
                   WHERE users.name !='' and userWikiInfo.edit_count > 0 and
                         users.name=userWikiInfo.user_name and
                         userWikiInfo.wiki_id=%%(wiki_id)s
                   ORDER BY join_isnull ASC, %s DESC""" % sort_by,
                {'wiki_id':macro.request.config.wiki_id})
        elif sort_by == 'last_edit_date':
            cursor.execute(
                """SELECT users.propercased_name, userWikiInfo.first_edit_date,
                          userWikiInfo.created_count, userWikiInfo.edit_count,
                          userWikiInfo.file_count,
                          userWikiInfo.last_page_edited,
                          userWikiInfo.last_edit_date,
                          userWikiInfo.last_edit_date IS NULL AS edit_isnull
                   FROM users, userWikiInfo
                   WHERE users.name !='' and userWikiInfo.edit_count > 0 and
                         users.name=userWikiInfo.user_name and
                         userWikiInfo.wiki_id=%%(wiki_id)s
                   ORDER BY edit_isnull ASC, %s DESC""" % sort_by,
                {'wiki_id':macro.request.config.wiki_id})
        else:
            cursor.execute(
                """SELECT users.propercased_name, userWikiInfo.first_edit_date,
                          userWikiInfo.created_count, userWikiInfo.edit_count,
                          userWikiInfo.file_count,
                          userWikiInfo.last_page_edited,
                          userWikiInfo.last_edit_date
                   FROM users, userWikiInfo
                   WHERE users.name !='' and userWikiInfo.edit_count > 0 and
                         users.name=userWikiInfo.user_name and
                         userWikiInfo.wiki_id=%%(wiki_id)s
                   ORDER BY %s DESC""" % sort_by,
                {'wiki_id':macro.request.config.wiki_id})

        user_stats = cursor.fetchall()
        page = Page("User Statistics", request)

        htmltext.append('<p><h2>User Statistics</h2></p>'
                        '<table width=100%% border=0><tr>'
                        '<td><b>User</b></td><td><b>%s&nbsp;&nbsp;</b></td>'
                        '<td><b>%s&nbsp;&nbsp;</b></td>'
                        '<td><b>%s&nbsp;&nbsp;</b></td>'
                        '<td><b>%s&nbsp;&nbsp;</b></td>'
                        '<td><b>%s&nbsp;&nbsp;</b></td>'
                        '<td><b>Last Page Edited&nbsp;&nbsp;</b></td>'
                        '</tr>' %
                        (page.link_to(know_status=True,
                                      know_status_exists=True,
                                      querystr="sort_by=edit_count",
                                      text="Edits"),
                         page.link_to(know_status=True,
                                      know_status_exists=True,
                                      querystr="sort_by=created_count",
                                      text="Pages Created"),
                         page.link_to(know_status=True,
                                      know_status_exists=True,
                                      querystr="sort_by=file_count",
                                      text="Files Contributed"),
                         page.link_to(know_status=True,
                                      know_status_exists=True,
                                      querystr="sort_by=first_edit_date",
                                      text="First Edit Date"),
                         page.link_to(know_status=True,
                                      know_status_exists=True,
                                      querystr="sort_by=last_edit_date",
                                      text="Last Edit")))
        toggle = -1
        for result in user_stats:
            toggle = toggle*(-1)
            name = result[0]
            first_edit_date = result[1]
            # older system sometimes didn't log this/hard to tell
            if not first_edit_date:
                first_edit_date = '<em>unknown</em>' 
            else:
                first_edit_date = request.user.getFormattedDateTime(
                    first_edit_date)
            created_count = result[2]
            edit_count = result[3]
            file_count = result[4]
            last_page_edited = result[5]
            last_edit_date = result[6]
            if not last_edit_date:
                last_edit_date = '<em>unknown</em>' 
            else:
                last_edit_date = request.user.getFormattedDateTime(
                    last_edit_date)

            # we don't user User objects here because there's a hell of a
            # lot of users, potentally
            if toggle < 0: 
                if last_page_edited:
                    htmltext.append('<tr bgcolor="#E5E5E5">'
                                    '<td>%s</td><td>%s</td><td>%s</td>'
                                    '<td>%s</td><td>%s</td><td>%s</td>'
                                    '<td>%s</td></tr>' %
                                    (Page(config.user_page_prefix + name,
                                          request).link_to(
                                            know_status=True,
                                            know_status_exists=True,
                                            text=name),
                                      edit_count, created_count, file_count,
                                      first_edit_date, last_edit_date,
                                      Page(last_page_edited,
                                           request).link_to()))
                else:
                    htmltext.append('<tr bgcolor="#E5E5E5">'
                                    '<td>%s</td><td>%s</td><td>%s</td>'
                                    '<td>%s</td><td>%s</td><td>%s</td>'
                                    '<td>&nbsp;</td>'
                                    '</tr>' %
                                    (Page(config.user_page_prefix + name,
                                          request).link_to(
                                            know_status=True,
                                            know_status_exists=True,
                                            text=name),
                                     edit_count, created_count, file_count,
                                     first_edit_date, last_edit_date))
            else:
                if last_page_edited:
                    htmltext.append('<tr bgcolor="#E0FFFF">'
                                    '<td>%s</a></td><td>%s</td><td>%s</td>'
                                    '<td>%s</td><td>%s</td><td>%s</td>'
                                    '<td>%s</td></tr>' %
                                    (Page(config.user_page_prefix + name,
                                          request).link_to(
                                            know_status=True,
                                            know_status_exists=True,
                                            text=name),
                                     edit_count, created_count, file_count,
                                     first_edit_date, last_edit_date,
                                     Page(last_page_edited,
                                          request).link_to()))
                else:
                    htmltext.append('<tr bgcolor="#E0FFFF"><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>&nbsp;</td></tr>' % (Page(config.user_page_prefix + name, request).link_to(know_status=True, know_status_exists=True, text=name),edit_count,created_count,file_count,first_edit_date,last_edit_date))

        htmltext.append('</table>') 

    return macro.formatter.rawHTML(u''.join(htmltext))
Beispiel #30
0
def loadLanguage(request, lang):
    """
    Load text dictionary for a specific language.

    Note that while ISO language coded use a dash, like 'en-us', our
    languages files use '_' like 'en_us' because they are saved as
    Python source files.

    """
    from Sycamore.util import pysupport
    lang_module = "Sycamore.i18n." + filename(lang)
    texts = pysupport.importName(lang_module, "text") 
    meta = pysupport.importName(lang_module, "meta") 

    # FIXME this doesnt work, leads to &amp;amp;amp;...
    # maybe parser.wiki._do_ent_repl is the problem?
    
    # please help finding this bug. I want to get rid of html in i18n texts
    # and a nice way to do is to replace them by wiki markup. so we wont have
    # to change them every time we go to a new html standard (like html 4.01
    # now and soon maybe xhtml).
    
    # use the wiki parser now to replace some wiki markup with html
    # maybe this is the better implementation, less overhead
    if 0:
        from Sycamore.Page import Page
        from Sycamore.parser.wiki import Parser
        from Sycamore.formatter.text_html import Formatter
        import cStringIO
        for key in texts:
            text = texts[key]
            out = cStringIO.StringIO()
            request.redirect(out)
            print "making parser ..."
            parser = Parser(text, request)
            formatter = Formatter(request)
            p = Page("$$$$i18n$$$$")
            formatter.setPage(p)
            print "formatting ..."
            parser.format(formatter)
            print "formatting finished ..."
            text = out.getvalue()
            request.redirect()
            #if text.startswith("<p>\n"):
            #    text = text[4:]
            #if text.endswith("</p>\n"):
            #    text = text[:-5]
            #print text
            
            # XXX catch problem early:
            if "&amp;amp;" in text:
                raise str(key)+str(text)
            
            texts[key] = text
        
    #alternative implementation, also doesnt work:
    if 0:
        import cStringIO
        from Sycamore.Page import Page
        page = Page("$$$i18n$$$")
        #key = "xxx"
        for key in texts:
            text = texts[key]
            page.set_raw_body(text, 1)
            out = cStringIO.StringIO()
            request.redirect(out)
            page.send_page(request, content_only=1)
            text = out.getvalue()
            if text.startswith("<p>\n"):
                text = text[4:]
            if text.endswith("</p>\n"):
                text = text[:-5]
            #print text
            request.redirect()
            texts[key] = text
        
    # TODO caching for CGI or performance will suck
    # pickle texts dict to caching area

    # XXX UNICODE
    # convert to unicode
    #encoding = meta['encoding']
    #for t in texts:
    #    texts[t] = texts[t].decode(encoding)
    return texts
Beispiel #31
0
    def saveText(self, newtext, datestamp, **kw):
        """
        Save new text for a page.

        @param newtext: text to save for this page
        @param datestamp: ...
        @keyword stripspaces: strip whitespace from line ends (default: 0)
        @keyword notify: send email notice tp subscribers (default: 0)
        @keyword comment: comment field (when preview is true)
        @keyword action: action for log (default: SAVE)
        @keyword proper_name: properly-cased pagename (for renames)
        @keyword ignore_edit_conflicts: force a save regardless of status
                                        (boolean)
        @keyword force_save: ignore "page content the same" error
        @rtype: string
        @return: error msg
        """
        self.page_name = self.page_name.strip()  # to ensure consistency
        _ = self._
        newtext = self._normalize_text(newtext, **kw)

        # for inline editing we want things to be as smooth as we can
        no_save_msg = False
        if (self.request.form.has_key('no_save_msg')
                and self.request.form['no_save_msg'][0]):
            no_save_msg = True

        msg = ""
        merged_changes = False
        ignore_edit_conflicts = kw.get('ignore_edit_conflicts', False)
        if not self.request.user.may.save(self, newtext, datestamp, **kw):
            msg = _('You are not allowed to edit this page!')
            raise self.AccessDenied, msg
        elif not newtext.strip():
            msg = _('You cannot save empty pages.')
            raise self.EmptyPage, msg
        elif (not ignore_edit_conflicts and datestamp != '0'
              and (datestamp < self.mtime()) and self.exists()):
            from Sycamore.util import diff3
            savetext = newtext
            original_text = Page(self.page_name,
                                 self.request,
                                 prev_date=datestamp).get_raw_body()
            saved_text = self.get_raw_body()
            verynewtext, had_conflict = diff3.text_merge(
                original_text,
                saved_text,
                savetext,
                marker1='----- /!\ Edit conflict! Your version: -----\n',
                marker2='----- /!\ Edit conflict! Other version: -----\n',
                marker3='----- /!\ End of edit conflict -----\n')
            msg = _("Someone else changed this page while you were editing.")

            if (had_conflict and self.request.user.valid
                    and (self.request.user.id == self.last_edit_info()[1])):
                # user pressed back button or did something weird
                had_conflict = False
                msg = None
            else:
                # we did some sort of merging or we had a conflict,
                # so let them know
                if had_conflict:
                    raise self.EditConflict, (msg, verynewtext)
                merged_changes = True
                msg = _("""%s Your changes were successfully merged! """ % msg)
                newtext = verynewtext
        elif (newtext == self.get_raw_body()
              and not self._rename_lowercase_condition()
              and kw.get('action') != 'SAVE/REVERT'
              and not kw.get('force_save')):
            # check to see if they're saving the page with the same content
            # it had before
            msg = _('You did not change the page content, not saved!')
            raise self.Unchanged, msg
        elif (config.max_page_size and len(newtext.encode(config.charset)) >
              (config.max_page_size * 1024)):
            msg = _('This page is too big!  Pages can be, at most, %sK.  '
                    'Consider splitting the page up into multiple pages '
                    'instead!' % config.max_page_size)
            raise self.TooBig, msg

        # save only if no error occured (msg is empty)
        if not msg or merged_changes:
            # set success msg
            if not merged_changes and not no_save_msg:
                msg = _("Thank you for your changes. "
                        "Your attention to detail is appreciated. ")

            # determine action for edit logging
            action = kw.get('action', 'SAVE')
            if action == 'SAVE' and not self.exists():
                action = 'SAVENEW'

            # write the page file
            mtime = self._write_to_db(newtext, action, kw.get('comment', ''),
                                      self.request.remote_addr,
                                      kw.get('proper_name', None))
            # deal with the case of macros / other items that change state by
            # /not/ being in the page
            wikiutil.macro_delete_checks(self)

            # we'll try to change the stats early-on
            if self.request.user.name:
                self.userStatAdd(self.request.user, action, self.page_name)

            # add the page to the search index or update its index
            if action != 'DELETE':
                search.add_to_index(self)

            # note the change in recent changes.  this explicit call is needed
            # because of the way we cache our change information
            caching.updateRecentChanges(self)

            return msg
Beispiel #32
0
def execute(pagename, request):
    from Sycamore.PageEditor import PageEditor
    _ = request.getText
    actname = __name__.split('.')[-1]
    page = Page(pagename, request)
    permanent = False
    showrc = True
    if not request.user.may.edit(page):
        return page.send_page(
            msg = _('You are not allowed to revert this page!'))

    # check whether the user clicked the delete button
    if request.form.has_key('button') and request.form.has_key('ticket'):
        # check whether this is a valid deletion request (make outside
        # attacks harder by requiring two full HTTP transactions)
        if not _checkTicket(request.form['ticket'][0]):
            return page.send_page(
                msg = _('Please use the interactive user interface to '
                        'revert pages!'))
        # revert the page
        if request.form.has_key('version'):
            version = int(request.form['version'][0])
            oldpg = Page(pagename, request, version=version)
            date = oldpg.prev_date
            if request.form.has_key('comment'):
                entered_comment = request.form['comment'][0]
            else:
                entered_comment = ''
            if len(entered_comment) > wikiaction.MAX_COMMENT_LENGTH:
                return page.send_page(msg = _(
                    'Comments must be less than %s characters long.' %
                    wikiaction.MAX_COMMENT_LENGTH))
            else:
                comment = 'v%s' % str(version)

            comment = "%sc%s" % (comment, entered_comment)
        else:
            return

        if (request.form.has_key('permanent') and
            request.form['permanent'][0] and request.user.may.admin(page)):
            permanent = True
            if (request.form.has_key('noshowrc') and
                request.form['noshowrc'][0]):
                showrc = False

        pg = PageEditor(pagename, request)
        savemsg = revert_to_page(oldpg, request, pg, comment=comment,
                                 permanent=permanent, showrc=showrc)
        return pg.send_page(msg=savemsg,
                            force_regenerate_content=(permanent and not
                                                      showrc))

    # get version
    if request.form.has_key('version'):
        version = request.form['version'][0]
    else:
        return page.send_page(msg= _(
            'Please use the interactive user interface to revert pages!'))

    oldpg = Page(pagename, request, version=version)
    # send revert form
    url = page.url()
    ticket = _createTicket()
    button = _('Revert')
    comment_label = _("Reason for the revert:")
    if request.user.may.admin(page):
        admin_label = (
            '<p>Permanently remove newer versions: '
            '<input id="noshowrctoggle" type="checkbox" name="permanent" '
                   'value="1"><span id="noshowrc">'
            "Don't log on Recent Changes: "
            '<input type="checkbox" name="noshowrc" value="1"></span></p>\n'
            '<script type="text/javascript">\n'
            "document.getElementById('noshowrc').style.visibility = "
                "'hidden';\n"
            "document.getElementById('noshowrc').style.paddingLeft = "
                "'1em';\n"
            "document.getElementById('noshowrctoggle').onclick = "
                "function () {\n"
            "document.getElementById('noshowrc').style.visibility = "
                "document.getElementById('noshowrctoggle').checked ? "
                    "'visible' : 'hidden'; \n"
            "}\n"
            "</script>\n"
        )
    else:
        admin_label = ''

    formhtml = (
        '<form method="GET" action="%(url)s">'
        '<input type="hidden" name="action" value="%(actname)s">'
        '<input type="hidden" name="ticket" value="%(ticket)s">'
        '<input type="hidden" name="version" value="%(version)s">'
        '<p>'
        '%(comment_label)s'
        '</p>'
        '<input type="text" name="comment" size="60" maxlength="80">'
        '<input type="submit" name="button" value="%(button)s">'
        '%(admin_label)s'
        '</form>' % {
            'url': url,
            'actname': actname,
            'ticket': ticket,
            'button': button,
            'comment_label': comment_label,
            'version': version,
            'admin_label': admin_label,
    })

    return oldpg.send_page(msg=formhtml)
Beispiel #33
0
def execute(pagename, request):
    from Sycamore.PageEditor import PageEditor
    _ = request.getText
    actname = __name__.split('.')[-1]
    page = Page(pagename, request)
    msg = None
    form = request.form
    wikiname = None
    
    if not config.wiki_farm or not config.allow_web_based_wiki_creation:
        return page.send_page(msg='You are not allowed to create new wikis.')
    if not request.user.valid:
        return page.send_page(msg='You must be logged in to create new wikis.')

    if do_email_auth:
        if request.form.has_key('send_email') and request.form['send_email'][0]:
            if (not request.form.has_key('wikiname') or not
                request.form['wikiname'][0]):
                return page.send_page(msg='Missing wiki name.')
            wikiname = request.form['wikiname'][0].lower()
            if not farm.isValidWikiName(wikiname):
                msg = ('Wiki creation failed because the wiki name "%s" is '
                       'invalid.  You may only use the numbers 0-9, the '
                       'letters a-z, and the dash "-" in a wiki name.' %
                       wikiname)
            elif wikiutil.isInFarm(wikiname, request):
                msg = 'Wiki "%s" already exists!' % wikiname 
            else:
                msg = send_validation_email(wikiname, request)
            return page.send_page(msg=msg)
        email_code = has_valid_email_link(request)
        if not email_code:
            return page.send_page(msg=("Invalid email link. "
                                       "To create a wiki you must follow the link send to your email account."))
        
    if form.has_key('wikiname') and form['wikiname'][0]:
        can_create_wiki = False
        wikiname = form['wikiname'][0].lower()
        if do_email_auth:
            if not config.captcha_support:
                can_create_wiki = True
            elif form.has_key('captcha_id') and form.has_key('captcha_code'):
                this_captcha = captcha.Captcha(page, id=form['captcha_id'][0])
                if this_captcha.check(form['captcha_code'][0]):
                    can_create_wiki = True
                else:
                    msg = ('Human verification was incorrect.  '
                           'Please try again!')
            else:
                if form.has_key('audio'):
                    type = 'wav'
                else:
                    type = 'png'
                captcha.send_captcha(page, wikiname, actname, email_code, type)
                return
        else:
            can_create_wiki = True

        if can_create_wiki:
            msg = farm.create_wiki(wikiname, request.user.name, request)
            if do_email_auth:
                _clearAuthCode(request, wikiname, email_code)
            if msg:
                # there was a problem
                return page.send_page(msg=msg)

            farm.add_wiki_to_watch(wikiname, request) 

            formatter = Formatter(request)
            wiki_location = farm.link_to_wiki(wikiname, formatter)
            msg = (
                'Wiki "%s" created successfully! '
                'Follow this link to get to your wiki:\n'
                '<p>\n'
                '%s\n'
                '</p>\n'
                '<p>\n'
                'The wiki was added to your list of watched wikis '
                '(change in '
                    '<a href="%sUser_Settings">your account settings</a>).\n'
                '</p>' %
                (wikiname, wiki_location, farm.getBaseFarmURL(request)))

    return page.send_page(msg=msg)
Beispiel #34
0
def copy_files(oldpagename, newpagename, request):
    """
    copies files from oldpagename to newpagename.
    keeps the files on oldpagename for manual deletion.
    if there is an file on the page newpagename that has the same name as a
    file on oldpagename, then the file from newpagename superseeds the old
    file, and the old file is deleted (but kept as a deleted file as per usual
    delete file/is accessable via the info tab)
    """
    from Sycamore.action.Files import get_filelist
    old_page_files = get_filelist(request, oldpagename)
    new_page_files = get_filelist(request, newpagename)
    for filename in old_page_files:
        is_image = wikiutil.isImage(filename)
        request.cursor.execute(
            """SELECT file, uploaded_time, uploaded_by, uploaded_by_ip,
                      attached_to_pagename_propercased from files
                      where name=%(filename)s and
                            attached_to_pagename=%(oldpagename)s and
                            wiki_id=%(wiki_id)s""", {
                'filename': filename,
                'oldpagename': oldpagename.lower(),
                'wiki_id': request.config.wiki_id
            })
        result = request.cursor.fetchone()

        if result:
            old_page_file_dict = {
                'filename': filename,
                'uploaded_time': result[1],
                'uploaded_by': result[2],
                'attached_to_pagename_propercased': result[4],
                'oldpagename': oldpagename.lower(),
                'uploaded_by_ip': result[3],
                'newpagename': newpagename.lower(),
                'newpagename_propercased': Page(newpagename,
                                                request).proper_name(),
                'timenow': time.time(),
                'userid': request.user.id,
                'userip': request.remote_addr,
                'wiki_id': request.config.wiki_id
            }
            if is_image:
                request.cursor.execute(
                    """SELECT xsize, ysize from imageInfo
                       where name=%(filename)s and
                             attached_to_pagename=%(oldpagename)s and
                             wiki_id=%(wiki_id)s""", {
                        'filename': filename,
                        'oldpagename': oldpagename.lower(),
                        'wiki_id': request.config.wiki_id
                    })
                result = request.cursor.fetchone()
                if result:
                    old_page_file_dict['xsize'] = result[0]
                    old_page_file_dict['ysize'] = result[1]

            if filename not in new_page_files:
                request.cursor.execute("""INSERT into files
                       (name, file, uploaded_time, uploaded_by, uploaded_by_ip,
                        attached_to_pagename, attached_to_pagename_propercased,
                        wiki_id)
                       values (%(filename)s,
                               (select file from files
                                where name=%(filename)s and
                                      attached_to_pagename=%(oldpagename)s and
                                      wiki_id=%(wiki_id)s
                               ),
                               %(uploaded_time)s, %(uploaded_by)s,
                               %(uploaded_by_ip)s, %(newpagename)s,
                               %(newpagename_propercased)s, %(wiki_id)s
                              )""",
                                       old_page_file_dict,
                                       isWrite=True)
                if is_image:
                    if old_page_file_dict.has_key('xsize'):
                        request.cursor.execute("""INSERT into imageInfo
                               (name, attached_to_pagename, xsize, ysize,
                                wiki_id)
                               values (%(filename)s, %(newpagename)s,
                                       %(xsize)s, %(ysize)s, %(wiki_id)s) """,
                                               old_page_file_dict,
                                               isWrite=True)

            else:
                request.cursor.execute("""INSERT into oldFiles
                       (name, file, uploaded_time, uploaded_by, uploaded_by_ip,
                        attached_to_pagename, attached_to_pagename_propercased,
                        deleted_by, deleted_by_ip, deleted_time, wiki_id)
                       values (%(filename)s,
                               (SELECT file from files
                                where name=%(filename)s and
                                      attached_to_pagename=%(newpagename)s and
                                      wiki_id=%(wiki_id)s
                               ),
                               (SELECT uploaded_time from files
                                where name=%(filename)s and
                                      attached_to_pagename=%(newpagename)s and
                                      wiki_id=%(wiki_id)s
                               ),
                               (SELECT uploaded_by from files
                                where name=%(filename)s and
                                      attached_to_pagename=%(newpagename)s and
                                      wiki_id=%(wiki_id)s
                               ),
                               (SELECT uploaded_by_ip from files
                                where name=%(filename)s and
                                      attached_to_pagename=%(newpagename)s and
                                      wiki_id=%(wiki_id)s
                               ),
                               %(newpagename)s, %(newpagename_propercased)s,
                               %(userid)s, %(userip)s, %(timenow)s,
                               %(wiki_id)s)""",
                                       old_page_file_dict,
                                       isWrite=True)

                # clear out cached version of image
                if config.memcache:
                    request.mc.delete("files:%s,%s" %
                                      (wikiutil.mc_quote(filename),
                                       wikiutil.mc_quote(newpagename.lower())))

                if is_image:
                    request.cursor.execute("""INSERT into oldImageInfo
                           (name, attached_to_pagename, xsize, ysize,
                            uploaded_time, wiki_id)
                           values
                           (%(filename)s, %(newpagename)s,
                            (SELECT xsize from imageInfo
                             where name=%(filename)s and
                                   attached_to_pagename=%(newpagename)s and
                                   wiki_id=%(wiki_id)s
                            ),
                            (SELECT ysize from imageInfo
                             where name=%(filename)s and
                                   attached_to_pagename=%(newpagename)s and
                                   wiki_id=%(wiki_id)s
                            ),
                            (SELECT uploaded_time from files
                             where name=%(filename)s and
                                   attached_to_pagename=%(newpagename)s and
                                   wiki_id=%(wiki_id)s
                            ),
                            %(wiki_id)s)""",
                                           old_page_file_dict,
                                           isWrite=True)
                    request.cursor.execute("""DELETE from thumbnails
                           where name=%(filename)s and
                                 attached_to_pagename=%(newpagename)s and
                                 wiki_id=%(wiki_id)s""",
                                           old_page_file_dict,
                                           isWrite=True)

                request.cursor.execute(
                    """SELECT name from files
                       where name=%(filename)s and
                             attached_to_pagename=%(newpagename)s and
                             wiki_id=%(wiki_id)s""", old_page_file_dict)
                result = request.cursor.fetchone()
                if result:
                    request.cursor.execute("""UPDATE files set
                           file=(select file from files
                                 where name=%(filename)s and
                                       attached_to_pagename=%(oldpagename)s and
                                       wiki_id=%(wiki_id)s
                                ),
                           uploaded_time=%(timenow)s, uploaded_by=%(userid)s,
                           uploaded_by_ip=%(userip)s
                           where name=%(filename)s and
                                 attached_to_pagename=%(newpagename)s and
                                 wiki_id=%(wiki_id)s""",
                                           old_page_file_dict,
                                           isWrite=True)
                    if is_image and old_page_file_dict.has_key('xsize'):
                        request.cursor.execute("""UPDATE imageInfo set
                               xsize=%(xsize)s, ysize=%(ysize)s
                               where name=%(filename)s and
                                     attached_to_pagename=%(newpagename)s and
                                     wiki_id=%(wiki_id)s""",
                                               old_page_file_dict,
                                               isWrite=True)
                else:
                    request.cursor.execute("""INSERT into files
                           (name, file, uploaded_time, uploaded_by,
                            uploaded_by_ip, xsize, ysize, attached_to_pagename,
                            attached_to_pagename_propercased, wiki_id)
                           values
                           (%(filename)s,
                            (select file from files
                             where name=%(filename)s and
                                   attached_to_pagename=%(oldpagename)s and
                                   wiki_id=%(wiki_id)s
                            ),
                            %(uploaded_time)s, %(uploaded_by)s,
                            %(uploaded_by_ip)s, %(xsize)s, %(ysize)s,
                            %(newpagename)s, %(newpagename_propercased)s,
                            %(wiki_id)s)""",
                                           old_page_file_dict,
                                           isWrite=True)
                    if is_image and old_page_file_dict.has_key('xsize'):
                        request.cursor.execute("""INSERT into imageInfo
                               (name, attached_to_pagename, xsize, ysize,
                                wiki_id) values
                               (%(filename)s, %(newpagename)s, %(xsize)s,
                                %(ysize)s, %(wiki_id)s)""",
                                               old_page_file_dict,
                                               isWrite=True)
Beispiel #35
0
def execute(macro, args, formatter=None):
    formatter = macro.formatter
    pages = []
    debug = []
    if not args:
        # use the current page
        pages.append(macro.formatter.page)
    else:
        pagenames = args.split(',')
        do_union = False
        if pagenames[0] == 'or':
            do_union = True
            del(pagenames[0])
        elif pagenames[0] == 'and':
            del(pagenames[0])

        lastpage = []
        for pagename in pagenames:
            curpage = Page(pagename, macro.request)
            if not curpage.exists():
                # The page doesn't exist.  Either someone's making
                # stuff up, or there's a comma in the page name.
                debug.append('<!-- "%s" does not exist -->' % curpage.page_name)
                if lastpage:
                    # We have something to try from last time.
                    lastpage.append(pagename)
                    debug.append('<!-- trying "%s" -->' % ','.join(lastpage))
                    curpage = Page(','.join(lastpage), macro.request)
                    if curpage.exists():
                        # awesome!
                        debug.append('<!-- "%s" does exist -->' % curpage.page_name)
                        lastpage = []
                        pages.append(curpage)
                else:
                    debug.append('<!-- "%s" appended to rescanner -->' % pagename)
                    lastpage.append(pagename)
            else:
                debug.append('<!-- "%s" does exist -->' % curpage.page_name)
                lastpage = []
                pages.append(curpage)

    # iterate through the pages, find links
    linkset = None
    for page in pages:
        links_here = page.getPageLinksTo()
        pages_deco = [(pagename.lower(), pagename) for pagename in links_here]
        links_here = set([word for lower_word, word in pages_deco])
        if not linkset:
            # first time through
            linkset = links_here.copy()
        elif do_union:
            # OR the list
            linkset = linkset.union(links_here)
        else:
            # AND the list
            linkset = linkset.intersection(links_here)
        debug.append('<!-- DEBUG: "%s" yielded %i links -->' % (page.page_name, len(links_here)))

    text = []
    if linkset:
        text.append(formatter.bullet_list(1))
        for link in sorted(linkset):
            text.append('%s%s%s' % (formatter.listitem(1),
                                    formatter.pagelink(link, generated=True),
                                    formatter.listitem(0)))
        text.append(formatter.bullet_list(0))

    text.extend(debug)
    
    return ''.join(text)
Beispiel #36
0
    def process(self):
        # processes the search
        wiki_name = self.request.config.wiki_name
        if not self.wiki_global:
            wikis = [wiki_name]
        else:
            wikis = wikiutil.getWikiList(self.request)

        for wiki_name in wikis: 
            pagelist = wikiutil.getPageList(self.request)
            matches = []
            for pagename in pagelist:
                page = Page(pagename, self.request, wiki_name=wiki_name)
                text = page.get_raw_body()
                text_matches = find_num_matches(self.regexp, text)
                if text_matches:
                    percentage = (text_matches*1.0/len(text.split()))*100
                    self.text_results.append(searchResult(page.page_name, text,
                                                          percentage,
                                                          page.page_name,
                                                          wiki_name)) 
              
                title = page.page_name
                title_matches = find_num_matches(self.regexp, title)
                if title_matches:
                      percentage = (title_matches*1.0/len(title.split()))*100
                      self.title_results.append(searchResult(title, title,
                                                             percentage,
                                                             page.page_name,
                                                           wiki_name))
            # sort the title and text results by relevancy
            self.title_results.sort(lambda x,y: cmp(y.percentage,
                                                    x.percentage))
            self.text_results.sort(lambda x,y: cmp(y.percentage,
                                                   x.percentage))

            # normalize the percentages.
            # still gives shit, but what can you expect from regexp?
            # install xapian!
            if self.title_results:
                i = 0
                max_title_percentage = self.title_results[0].percentage
                self.title_results = self.title_results[
                    self.t_start_loc:self.t_start_loc+self.num_results+1]
                for title in self.title_results:
                    if i > self.num_results:
                        break
                    title.percentage = title.percentage/max_title_percentage
                    title.percentage = title.percentage*100
                    i += 1

            if self.text_results: 
                i = 0 
                max_text_percentage = self.text_results[0].percentage
                self.text_results = self.text_results[
                    self.p_start_loc:self.p_start_loc+self.num_results+1]
                for text in self.text_results:
                    if i > self.num_results:
                        break
                    text.percentage = text.percentage/max_text_percentage
                    text.percentage = text.percentage*100
                    i += 1
Beispiel #37
0
def execute(macro, args, formatter=None):
    if not formatter:
        formatter = macro.formatter
    _ = macro.request.getText

    # prevent recursive calls
    global _guard
    if _guard:
        return ""

    # flush the request output because orphaned may take time to generate
    macro.request.flush()

    # delete all linked pages from a dict of all pages
    _guard = 1
    cursor = macro.request.cursor
    cursor.execute(
        """
        SELECT curPages.propercased_name
        FROM curPages LEFT JOIN links on
            (links.destination_pagename=curPages.name and
             links.wiki_id=%(wiki_id)s and curPages.wiki_id=%(wiki_id)s
            )
        WHERE curPages.wiki_id=%(wiki_id)s and
              links.destination_pagename is NULL""",
        {"wiki_id": macro.request.config.wiki_id},
    )

    orphanednames_result = cursor.fetchall()
    _guard = 0

    # check for the extreme case
    if not orphanednames_result:
        return "<p>%s</p>" % _("No orphaned pages in this wiki.")

    # return a list of page links
    from Sycamore.Page import Page

    redirects = []
    pages = []
    show_users = showUsers(macro.request)
    for entry in orphanednames_result:
        name = entry[0]
        if name.startswith(config.user_page_prefix) and not show_users:
            continue
        page = Page(name, macro.request)
        is_redirect = False
        # if not macro.request.user.may.read(name): continue
        if page.isRedirect():
            redirects.append(page)
        else:
            pages.append(page)

    # usually 'Orphaned Pages' or something such
    pagename = macro.request.getPathinfo()[1:]
    if not show_users:
        macro.request.write(
            '<div style="float: right;">'
            '<div class="actionBoxes"><span>'
            "%s"
            "</span></div></div>" % wikiutil.link_tag(macro.request, pagename + "?show_users=true", "show users")
        )
    else:
        macro.request.write(
            '<div style="float: right;">'
            '<div class="actionBoxes"><span>'
            "%s"
            "</span></div></div>" % wikiutil.link_tag(macro.request, pagename, "hide users")
        )

    macro.request.write(macro.formatter.heading(2, "Orphans"))
    macro.request.write(macro.formatter.bullet_list(1))
    for page in pages:
        macro.request.write(macro.formatter.listitem(1))
        macro.request.write(page.link_to(know_status=True, know_status_exists=True))
        macro.request.write(macro.formatter.listitem(0))
    macro.request.write(macro.formatter.bullet_list(0))

    macro.request.write(macro.formatter.heading(2, "Orphaned Redirects"))
    macro.request.write(macro.formatter.bullet_list(1))
    for page in redirects:
        macro.request.write(macro.formatter.listitem(1))
        macro.request.write(page.link_to(know_status=True, know_status_exists=True))
        macro.request.write(macro.formatter.listitem(0))
    macro.request.write(macro.formatter.bullet_list(0))

    return ""  # macros must return strings
Beispiel #38
0
def execute(pagename, request):
    _ = request.getText
    actname = __name__.split('.')[-1]
    page = PageEditor(pagename, request)
    msg = ''
    oldtext = page.get_raw_body().lower()

    events_page = Page("Events Board", request) 

    # Do we want an RSS feed?
    if (request.form.has_key('rss') and request.form.get("rss")[0] == '1' and
        request.user.may.read(events_page)):
        request.http_headers()
        request.write(doRSS(request))
        raise util.SycamoreNoFooter
        return

    # be extra paranoid
    elif (actname in config.excluded_actions or
          not request.user.valid or not request.user.may.edit(events_page) or
          not request.user.may.edit(page)):
        msg = _('You are not allowed to edit this page. '
                '(You need an account in most cases)')
    # check to make sure the events macro is in the page
    elif string.find(oldtext,"[[events]]") == -1:
        msg = _('Not allowed to add an event')

    # check whether page exists at all
    elif not page.exists():
        msg = _('This page does not exist.')

    # check whether the user filled out the form
    elif request.form.has_key('uid') and request.form.has_key('del'):
        if (request.form.get('del')[0] == "1" and
            request.user.may.admin(Page("Events Board", request))):
            # let's try and delete the event!
            uid = request.form.get('uid')[0]
            request.cursor.execute(
                "SELECT event_name from events where uid=%(uid)s", {'uid':uid})
            name = request.cursor.fetchone()[0]
            request.cursor.execute(
                "DELETE from events where uid=%(uid)s", {'uid':uid},
                isWrite=True)
            msg = 'Event "%s" <b>deleted</b>!' % name

        elif request.form.get('del')[0] == "1":
            uid = request.form.get('uid')[0]
            request.cursor.execute(
                "SELECT event_name from events where uid=%(uid)s", {'uid':uid})
            name = request.cursor.fetchone()[0]
            request.cursor.execute(
                """DELETE from events where uid=%(uid)s and
                             posted_by=%(username)s""",
                {'uid':uid, 'username':request.user.propercased_name},
                isWrite=True)
            msg = 'Event "%s" <b>deleted</b>!' % name
    
        if config.memcache:
            request.mc.set("today_events", None)
            caching.updateRecentChanges(Page("Events Board", request))

    elif (request.form.has_key('button') and 
          request.form.has_key('event_text') and
          request.form.has_key('event_name') and
          request.form.has_key('event_location') and
          request.form.has_key('month') and
          request.form.has_key('day') and
          request.form.has_key('hour') and
          request.form.has_key('minute') and
          request.form.has_key('ticket')):
        # check whether this is a valid renaming request (make outside
        # attacks harder by requiring two full HTTP transactions)
        if not _checkTicket(request.form['ticket'][0]):
            msg = _('Please use the web interface to change the page!')
        else:
            event_text = request.form.get('event_text')[0]
            event_name = request.form.get('event_name')[0]
            event_location = request.form.get('event_location')[0]
            month = int(request.form.get('month')[0])
            day = int(request.form.get('day')[0])
            hour = int(request.form.get('hour')[0])
            minute = int(request.form.get('minute')[0])
            year = int(request.form.get('year')[0])
            posted_by = request.user.propercased_name
            now = request.user.getFormattedDateTime(time.time(),
                                                    global_time=True)
    
            # WE NEED TO VALIDATE THE TEXT AND THE OTHER FIELDS
            if (isValid(event_text, event_name, event_location, month, day,
                       hour, minute, year) and not
               hasPassed(month, day, hour,minute, year, request)):
                event_time_unix = wikiutil.timeInTzToUTC(
                    request.config.tz,
                    (year, month, day, hour, minute, 0, 0))
                writeEvent(request, event_text, event_name,
                           event_location, event_time_unix, posted_by)
                msg = _('Your event has been added!')
            elif hasPassed(month,day,hour,minute,year,request):
                msg = _('Event time is in the past!  '
                        'Please choose a time in the future.')
            else:
                msg = _('Event <b>NOT</b> posted. '
                        'You entered some invalid text into the form.  '
                        'No HTML is allowed.')
   
    else:
        msg = _('Please fill out all fields of the form.')
        
    return page.send_page(msg)
Beispiel #39
0
def doRSS(request):
    """
    set up the RSS file
    """
    rss_init_text = (
        '<?xml version="1.0" ?>\n'
        '<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">\n'
        '<channel><title>%s Events Board</title><link>%s</link>'
            '<description>'
            'Events occuring soon, taken from the %s Events Board.'
            '</description><language>en-us</language>\n'
        '</channel>\n'
        '</rss>\n' % (request.config.sitename,
                      Page("Events Board", request).link_to(),
                      request.config.sitename))

    creator_text = 'The %s Robot' % request.config.sitename

    rss_dom = xml.dom.minidom.parseString(rss_init_text)
    channel = rss_dom.getElementsByTagName("channel")[0]

    # Check to see if the event has already passed
    import string, re
    current_time = request.user.getFormattedDateTime(time.time(),
                                                     global_time=True)
    year_cut = string.split(current_time," ")[0]
    current_year = string.split(year_cut, "-")[0]
    month_cut = string.split(current_time," ")[0]
    current_month = string.split(month_cut,"-")[1]
    day_cut = string.split(current_time," ")[0]
    current_day = string.split(day_cut,"-")[2]
    hour_cut = string.split(current_time," ")[1]
    current_hour = string.split(hour_cut,":")[0]
    string_month = findMonth(current_month)
     
    rss_text = []
    events = []
    timenow = time.time()
    today_struct = time.gmtime(timenow+request.config.tz_offset)
    today = list(today_struct[0:3]) + [0,0,0,0,0,0]
    today = calendar.timegm(today) - request.config.tz_offset
    tomorrow_struct = time.gmtime(timenow+60*60*24+request.config.tz_offset)
    tomorrow = list(tomorrow_struct[0:3]) + [0,0,0,0,0,0]
    tomorrow = calendar.timegm(tomorrow) - request.config.tz_offset

    request.cursor.execute(
        """SELECT uid, event_time, posted_by, text, location, event_name
           from events where event_time >= %(today)s and
                             event_time < %(tomorrow)s and
                             wiki_id=%(wiki_id)s""",
        {'today':today, 'tomorrow':tomorrow, 'wiki_id':request.config.wiki_id})
    result = request.cursor.fetchone()
    while result:
        events.append(result)
        result = request.cursor.fetchone()
    
    for event in events:
        event_time_unix = event[1]

        # stupid date stuff
        time_struct = time.gmtime(event_time_unix+request.config.tz_offset)
        year = time_struct[0]
        month = time_struct[1]
        day = time_struct[2]
        hour = time_struct[3]
        minute = time_struct[4]

        posted_by = event[2]
        event_location = event[4]
        event_name = event[5]

        id = event[0]
        text = event[3]
        if event_name:
            processed_name = wikiutil.simpleStrip(request,event_name)
        else:
            processed_name = ''
        processed_text = doParse(text,request)
        processed_location = doParse(event_location,request)
        if int(hour) > 12 :
            read_hour = int(hour) - 12
            if not int(minute) == 0:
                ptime = str(read_hour) + ":" + str(minute) + " PM"
            else:
                ptime = str(read_hour) + ":00" + " PM"
        elif int(hour) == 0: 
            if not int(minute) == 0:
                ptime = "12:" + str(minute) + " AM"
            else:
                ptime = "12:00 AM"
        elif int(hour) == 12:
            if not int(minute) == 0:
                ptime = "12:" + str(minute) + " PM"
            else:
                ptime = "12:00 PM"
        else:
            if not int(minute) == 0:
                ptime = str(hour) + ":" + str(minute) + " AM"
            else:
                ptime = str(hour) + ":00 AM"
    
        total_date = "%s, %s %s" % (
            datetoday(int(day), int(month), int(year)), findMonth(month), day)
        item = rss_dom.createElement("item")
        rss_text = []

        rss_text.append('<b>Date:</b> %s<br>\n'
                    '<b>Time:</b> %s<br>\n'
                    '<b>Location:</b> %s<br><br>\n'
                    '%s&nbsp;&nbsp;(Posted by %s)\n' %
                    (total_date, ptime, processed_location, processed_text,
                     user.getUserLink(request,
                                      user.User(request, name=posted_by),
                                      absolute=True)))
        item_guid = rss_dom.createElement("guid")
        item_guid.setAttribute("isPermaLink","false")
        item_guid.appendChild(rss_dom.createTextNode(''.join(str(id))))
        item.appendChild(item_guid)
        item_description = rss_dom.createElement("description")
        item_description.appendChild(rss_dom.createTextNode(''.join(rss_text)))
        item_title = rss_dom.createElement("title")
        item_title.appendChild(rss_dom.createTextNode(processed_name))
        item.appendChild(item_title)
        item_link = rss_dom.createElement("link")
        item_link.appendChild(rss_dom.createTextNode(
            Page("Events Board", request).url(relative=False)))
        item.appendChild(item_link)
        item_date = rss_dom.createElement("dc:date")
        item_date.appendChild(rss_dom.createTextNode(
            "%s-%s-%s" % (current_year,current_month,current_day)))
        item.appendChild(item_date)
        creator = rss_dom.createElement("dc:creator")
        creator.appendChild(rss_dom.createTextNode(creator_text))
        item.appendChild(creator)
        item.appendChild(item_description)
        channel.appendChild(item)

    the_xml = rss_dom.toxml()

    return the_xml
Beispiel #40
0
    def sendEditor(self, **kw):
        """
        Send the editor form page.

        @keyword preview: if given, show this text in preview mode
        @keyword staytop: don't go to #preview
        @keyword comment: comment field (when preview is true)
        @keyword had_conflict: we had an edit conflict on a save.
        """
        import re

        try:
            from Sycamore.action import SpellCheck
        except ImportError:
            SpellCheck = None

        form = self.request.form
        _ = self._
        self.request.http_headers([("Content-Type",
            "text/html; charset=%s" % config.charset)] + self.request.nocache)
        msg = None
        preview = kw.get('preview', None)
        emit_anchor = not kw.get('staytop', 0)
        proper_name = self.proper_name()

        from Sycamore.formatter.text_html import Formatter
        self.request.formatter = Formatter(self.request, store_pagelinks=1,
                                           preview=preview)

        base_uri = "%s/%s?action=edit" % (self.request.getScriptname(),
                                          wikiutil.quoteWikiname(
                                            self.proper_name()))
        backto = form.get('backto', [None])[0]
        if backto:
            base_uri += '&amp;' + util.web.makeQueryString(backto=backto)

        # check edit permissions
        if not self.request.user.may.edit(self):
            msg = _('You are not allowed to edit this page.')
        elif self.prev_date:
            # Trying to edit an old version, this is not possible via
            # the web interface, but catch it just in case...
            msg = _('Cannot edit old revisions!')

        # Is the IP address a Tor exit note?
        if config.block_tor_edits:
            tor = torcheck.torcheck()
            if tor.query(self.request.remote_addr): msg = _('You are not allowed to edit this page, %s.' % self.request.remote_addr)

        # Test against a number of DNSBLs
        if config.block_dnsbl_edits:
            # Test: is this an IP address?
            re1='((?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?![\\d])'
            rg = re.compile(re1,re.IGNORECASE|re.DOTALL)
            m = rg.search(self.request.remote_addr)
            if m:
                # this is an IP address
                # reverse IP address octets
                dq = self.request.remote_addr.split('.')
                dq.reverse()
                
                for dnsbl in config.block_dnsbl_edits:
                    querystring = '.'.join(dq)
                    querystring += '.' + dnsbl + '.'

                    try:
                        result = socket.gethostbyname(querystring)
                    except socket.gaierror:
                        # probably nxdomain
                        result = '0.0.0.0'

                    if result.startswith('127.0.0'):
                        # utoh
                        msg = _('You are not allowed to edit this page: %s listed on %s' % (self.request.remote_addr, dnsbl))

        # Did one of the prechecks fail?
        if msg and not kw.get('had_conflict', None):
            self.send_page(msg=msg)
            return

        # check for preview submit
        if preview is None:
            title = _('Edit "%(pagename)s"')
        else:
            title = _('Preview of "%(pagename)s"')
            self.set_raw_body(preview.replace("\r", ""), 1)

        page_needle = self.page_name
        if config.allow_subpages and page_needle.count('/'):
            page_needle = '/' + page_needle.split('/')[-1]

        wikiutil.send_title(self.request,
            self.proper_name(),
            pagename=self.proper_name(),
            has_link=True,
            strict_title='Editing "%s"' % self.proper_name(),
            body_onload = "sizeForIE('savetext', 100, 'editorComment', 99);"
        )

        # start content div
        self.request.write('<div id="content" class="content">\n')
        
        # get request parameters
        text_rows = None
        if form.has_key('rows'):
            text_rows = int(form['rows'][0])
            if self.request.user.valid:
                # possibly update user's pref
                if text_rows != self.request.user.edit_rows:
                    self.request.user.edit_rows = text_rows
                    self.request.user.save()
        else:
            text_rows = config.edit_rows
            if self.request.user.valid:
                text_rows = int(self.request.user.edit_rows)

        if form.has_key('cols'):
            text_cols = int(form['cols'][0])
            if self.request.user.valid:
                # possibly update user's pref
                if text_rows != self.request.user.edit_rows:
                    self.request.user.edit_rows = text_rows
                    self.request.user.save()
        else:
            text_cols = 80
            if self.request.user.valid:
                text_cols = int(self.request.user.edit_cols)

        # check datestamp (version) of the page our edit is based on
        if preview is not None:
            # propagate original datestamp
            mtime = float(form['datestamp'][0])

            # did someone else change the page while we were editing?
            conflict_msg = None
            if not self.exists():
                # page does not exist, are we creating it?
                if mtime:
                    conflict_msg = _('<p>Someone else <b>deleted</b> this '
                                     'page while you were editing!')
            elif mtime != self.mtime():
                conflict_msg = _('<p>Someone else changed this page while '
                                 'you were editing.')
                # merge conflicting versions
                allow_conflicts = 1
                from Sycamore.util import diff3
                savetext = self.get_raw_body()
                oldpg = Page(self.page_name, self.request, prev_date=mtime)
                original_text = oldpg.get_raw_body()
                saved_text = Page(self.page_name, self.request).get_raw_body()
                verynewtext, had_conflict = diff3.text_merge(
                    original_text, saved_text, savetext,
                    marker1='----- /!\ Edit conflict! Your version: -----\n',
                    marker2='----- /!\ Edit conflict! Other version: -----\n',
                    marker3='----- /!\ End of edit conflict -----\n')
                if had_conflict and self.request.user.valid and (
                   self.request.user.id == self.last_edit_info()[1]):
                    # user pressed back button or did something weird
                    conflict_msg =None
                elif had_conflict:
                    conflict_msg = _(conflict_msg + 
                                     'There was an <b>edit conflict between '
                                     'your changes!</b></p>'
                                     '<p>Please review the conflicts and '
                                     'merge the changes.</p>')
                    mtime = self.mtime()
                    self.set_raw_body(verynewtext, 1)
                else:
                   conflict_msg = _(conflict_msg + 
                                    'Your changes were sucessfully merged!')
                   mtime = self.mtime()
                   self.set_raw_body(verynewtext)

            if conflict_msg:
                self.request.write('<div id="message"><div>%s'
                                   '</div></div>'% conflict_msg)
                emit_anchor = 0 # make this msg visible!
        elif self.exists():
            # datestamp of existing page
            mtime = self.mtime()
        else:
            # page creation
            mtime = 0

        # output message
        message = kw.get('msg', '')
        if message:
            self.request.write('<div id="message">%s</div>' % (message))

        # get the text body for the editor field
        if form.has_key('template'):
            # "template" parameter contains the name of the template page
            template_page = wikiutil.unquoteWikiname(form['template'][0])
            raw_body = Page(template_page, self.request).get_raw_body()
        else:
            raw_body = self.get_raw_body()

        # send text above text area
        
        # button toolbar
        self.request.write('<div id="editArea">')
        self.request.write("<script type=\"text/javascript\">"
                           "var buttonRoot = '%s';</script>" % (
                            os.path.join(config.url_prefix,
                                         self.request.theme.name,
                                         'img', 'buttons')))
        if self.request.user.name:
          if config.user_page_prefix:
            self.request.write("<script type=\"text/javascript\">"
                               "var userPageLink = '[\"%s%s\"]';</script>" % (
                                config.user_page_prefix,
                                self.request.user.propercased_name))
          else: 
            self.request.write("<script type=\"text/javascript\">"
                               "var userPageLink = '[\"%s\"]';</script>" % (
                                config.user_page_prefix,
                                self.request.user.propercased_name))
        else:
          self.request.write("<script type=\"text/javascript\">"
                             "var userPageLink = '%s';</script>" % (
                             self.request.remote_addr))
          
        if config.wiki_farm:
            self.request.write("<script type=\"text/javascript\" "
                               "src=\"http://%s%s%s/edit.js\"></script>\n" % (
                                config.wiki_base_domain, config.web_dir,
                                config.url_prefix))
        else:
            self.request.write("<script type=\"text/javascript\" "
                               "src=\"%s%s/edit.js\"></script>\n" % (
                                config.web_dir, config.url_prefix))

        # send form
        self.request.write('<form name="editform" id="editform" '
                           'method="post" action="%s/%s#preview">' % (
                            self.request.getScriptname(),
                            wikiutil.quoteWikiname(proper_name)))

        self.request.write(str(html.INPUT(type="hidden", name="action",
                                          value="savepage")))
        if backto:
            self.request.write(str(html.INPUT(type="hidden",
                                              name="backto", value=backto)))

        # generate default content
        if not raw_body:
            if self.isTalkPage():
                raw_body = _('This page is for discussing the '
                             'contents of ["%s"].') % self.proper_name()[:-5]
            else:
                raw_body = _('Describe %s here.') % (self.proper_name(),)

        # replace CRLF with LF
        raw_body = self._normalize_text(raw_body)

        # send datestamp (version) of the page our edit is based on
        self.request.write('<input type="hidden" name="datestamp" '
                           'value="%s">' % repr(mtime))

        # Print the editor textarea and the save button
        self.request.write('<textarea id="savetext" name="savetext" '
                           'rows="%d" cols="%d" style="width:100%%;">%s'
                           '</textarea>' % (text_rows, text_cols,
                                            wikiutil.escape(raw_body)))

       # make sure we keep the template notice on a resize of the editor
        template_param = ''
        if form.has_key('template'):
            template_param = '&amp;template=' + form['template'][0]
       # draw edit size links
        self.request.write(_('<div class="pageEditInfo" id="editorSize">'
                             'editor size:'))
        self.request.write('<a href="#" onclick="return sizeEditor(\'bigger\','
                           '\'%s&amp;preview=1&amp;cols=60%s\')">%s'
                           '</a>' % (base_uri, template_param, '+'))
        self.request.write(',<a href="#" onclick="return sizeEditor(\'smaller\','
                           '\'%s&amp;preview=1&amp;cols=60%s\')">%s'
                           '</a>' % (base_uri, template_param, '-'))
        self.request.write('</div>')
        self.request.write('</p>') # close textarea

        self.request.write('<div id="editComment" id="editorResizeButtons"> '
                           '%s<br><input type="text" class="formfields" '
                           'name="comment" id="editorComment" value="%s" '
                           'size="%d" maxlength="80" style="width:99%%;">'
                           '</div>' % (_("<font size=\"+1\">Please comment "
                                         "about this change:</font>"),
                                       wikiutil.escape(kw.get('comment', ''),
                                       1), text_cols))

        spam_catch_button = (
            '<span style="position: absolute; top: 0px; left: 0px;'
                         'height: 0px; width: 0px; overflow: hidden;">'
            'dont enter into this box:'
            '<input type="text" name="text_dont"/>'
            '</span>'
            '<span style="position: absolute; top: 0px; left: 0px;'
                         'height: 0px; width: 0px; overflow: hidden;">'
            '<input class="formbutton" type="submit" name="button_dont" '
                    'value="Dont press me">\n'
            '</span>')
        self.request.write(spam_catch_button)

        # button bar
        button_spellcheck = (SpellCheck and
            '<input type="submit" class="formbutton" name="button_spellcheck"'
            ' value="%s">' % _('Check Spelling')) or ''

        save_button_text = _('Save Changes')
        cancel_button_text = _('Cancel')
        
        self.request.write("</div>")

        if self.request.user.may.admin(self):
            security_button = ('<input type="button" class="formbutton" '
                              'onClick="location.href='
                              '\'%s/%s?action=Security\'" '
                              'value="Security">') % (
                                self.request.getScriptname(),
                                wikiutil.quoteWikiname(proper_name))
        else:
            security_button = ''
       
        if self.request.user.may.delete(self):
            delete_button = ('<input type="button" class="formbutton" '
                            'onClick="location.href='
                            '\'%s/%s?action=DeletePage\'" value="Delete">') % (
                                self.request.getScriptname(),
                                wikiutil.quoteWikiname(proper_name))
            rename_button = ('<input type="button" class="formbutton" '
                            'onClick="location.href=\'%s/%s?action=Rename\'"'
                            ' value="Rename">') % (
                                self.request.getScriptname(),
                                wikiutil.quoteWikiname(proper_name))
        else:
            delete_button = ''
            rename_button = ''
        
        self.request.write('<div id="editButtonRow">'
                           '<span>'
                           '<input type="submit" class="formbutton" '
                           'name="button_preview" value="%s"> '
                           '<input type="submit" class="formbutton" '
                           'name="button_save" value="%s"> '
                           '<input type="submit" class="formbutton" '
                           'name="button_cancel" value="%s"> '
                           '</span>'
                           '<span class="editActions">'
                           '<input type="button" class="formbutton" '
                           'onClick="window.open(\'%s/%s?action=Files\', '
                           '\'files\', \'width=800,height=600,'
                           'scrollbars=1\')" value="Upload Files"> '
                           '%s '
                           '%s '
                           '%s '
                           '%s</span>'
                           '</div>' % (
                                _('Preview'), save_button_text,
                                cancel_button_text,
                                self.request.getScriptname(),
                                wikiutil.quoteWikiname(proper_name),
                                button_spellcheck, delete_button,
                                rename_button, security_button))

        if self.request.config.edit_agreement_text:
            self.request.write(self.request.config.edit_agreement_text)

        badwords_re = None
        if preview is not None:
            if SpellCheck and (
                    form.has_key('button_spellcheck') or
                    form.has_key('button_newwords')):
                badwords, badwords_re, msg = SpellCheck.checkSpelling(self,
                    self.request, own_form=0)
                self.request.write("<p>%s</p>" % msg)
        self.request.write("</form>")

        if config.wiki_farm:
            from Sycamore import farm
            help_link = farm.link_to_page(farm.getBaseWikiName(),
                                          "Help with Editing",
                                          self.request.formatter,
                                          force_farm=True)
        else:
            help_link = Page("Help with Editing", self.request).link_to()

        # QuickHelp originally by Georg Mischler <*****@*****.**>
        self.request.write('<h2>Editing quick-help</h2>\n'
            '<dl><div style="float: right; margin: 10px; border: 1px solid; '
            'padding: 3pt;">See <b>%s</b> for more information.</div>' % (
                help_link) + _("<dt>Emphasis:</dt>\n"
                    "<dd>''<em>italics</em>''; '''<strong>bold</strong>''';"
                    "'''''<strong><em>bold italics</em></strong>''''';"
                    "''<em>mixed '''<strong>bold</strong>''' and "
                    "italics</em>''; ---- horizontal rule.</dd>"
                    "<dt>Headings:</dt>"
                    "<dd>= Title 1 =; == Title 2 ==; === Title 3 ===;"
                    "==== Title 4 ====; ===== Title 5 =====.</dd>"
                    "<dt>Lists:</dt>"
                    "<dd>space and one of * bullets; 1., a., A., i., I. "
                    "numbered items;"
                    "  1.#n start numbering at n; space alone indents.</dd>"
                    "<dt>Links:</dt>"
                    "<dd>[\"brackets and double quotes\"]; [\"the exact "
                    "page name\" label];"
                    "  url; [url]; [url label].</dd>"
                    "<dt>Tables:</dt>"
                    "<dd>|| cell text |||| cell text spanning two columns ||;"
                    "  no trailing white space allowed after tables or titles."
                    "</dd></dl>"))

        if preview is not None:
            if not emit_anchor:
                preview_name = "previewHide"
            else:
                preview_name = "preview"
            self.request.write('<div id="%s" class="preview">' % preview_name)
            self.send_page(content_only=1, hilite_re=badwords_re,
                           preview=preview)
            self.request.write('</div>')

        self.request.write('</div>\n') # end content div

        wikiutil.send_after_content(self.request)

        self.request.theme.emit_custom_html(config.page_footer1)
        self.request.theme.emit_custom_html(config.page_footer2)

        self.request.write('</body></html>') 
Beispiel #41
0
def mapJS(wiki_name, page_locs, nearby_locs, request):
    """
    Create a string containing javascript for google map
    page = the page object
    place = place object of center of map
    nearby = dictionary of nearby places
    """
    # pick center point as the first point if there's more than one point
    # associated with the page
    center = page_locs[0]

    pagename = center.pagename
    page = Page(pagename, request, wiki_name=wiki_name)
    out = """
<script type="text/javascript">
//<![CDATA[
function doLoad() {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl()); 
map.setCenter(new GLatLng(%s,%s),16);
        """ % (
        center.latitude,
        center.longitude,
    )

    nearbys_processed = {}
    i = 0  # for 'a' 'b' labels on markers
    if nearby_locs:
        for x in nearby_locs:
            nearby_page = Page(x.pagename, request, wiki_name=wiki_name)
            if (x.pagename, x.latitude, x.longitude) in nearbys_processed:
                # only plot a given nearby point once
                # (it is sometimes easier to just have repeated nearbys
                # in the query, hence we filter them out here)
                continue
            namestr = """'<b><a href="%s" target=_parent>%s</a></b>""" """<br>%s'""" % (
                nearby_page.url(relative=False),
                x.pagename.replace("'", "\\" + "'"),
                x.address.replace("'", "\\" + "'"),
            )
            out += """
            var point = new GLatLng(%s,%s);
            map.addOverlay(createMarker(point,%s, %s));
            """ % (
                x.latitude,
                x.longitude,
                i,
                namestr,
            )
            # add it as plotted
            nearbys_processed[(x.pagename, x.latitude, x.longitude)] = None
            i += 1

    for x in page_locs:
        namestr = """'<b><a href="%s" target=_parent>%s</a></b>""" """<br>%s'""" % (
            page.url(relative=False),
            x.pagename.replace("'", "\\" + "'"),
            x.address.replace("'", "\\" + "'"),
        )
        out += (
            "var p_point = new GLatLng(%s,%s);\n"
            "var myArrow = createArrow(p_point,%s);\n"
            "map.addOverlay(myArrow);\n"
            "GEvent.trigger(myArrow,'click');" % (x.latitude, x.longitude, namestr)
        )

    out += """
            loaded = true;
       }
       //]]>
       </script>"""
    return out
Beispiel #42
0
def execute(pagename, request):
    _ = request.getText
    page = Page(pagename, request)
    actname = __name__.split('.')[-1] 
    if not request.user.may.admin(page):
        msg = _("You don't have admin permissions on this page, "
                "so you cannot change security settings.")
        return page.send_page(msg)
    
    if request.form.has_key('button'):
        # process save
        groups = [] 
        groups_dict = {}
        for key in request.form:
            if key.endswith('_groupname'):
                groups.append(unquoteWikiname(key[:-10]))
            else:
                if key.endswith('_may_read'):
                    dowhat = 'read'
                    groupname = unquoteWikiname(key[:-9])
                elif key.endswith('_may_edit'):
                    dowhat = 'edit'
                    groupname = unquoteWikiname(key[:-9])
                elif key.endswith('_may_delete'):
                    dowhat = 'delete'
                    groupname = unquoteWikiname(key[:-11])
                elif key.endswith('_may_admin'):
                    dowhat = 'admin'
                    groupname = unquoteWikiname(key[:-10])
                else:
                    continue

                if not groups_dict.has_key(groupname):
                    groups_dict[groupname] = [False, False, False, False]

                groups_dict[groupname][ACL_RIGHTS_TABLE[dowhat]] = True

        # set groups we weren't sent any checkboxes for to
        # all false (nothing checked)
        groups_no_checks = filter(lambda(groupname): (
            groupname not in groups_dict), groups)
        for groupname in groups_no_checks:
            groups_dict[groupname] = [False, False, False, False]
 
        wikiacl.setACL(pagename, groups_dict, request)
        return page.send_page(
            msg = _("Security settings sucessfully changed!"))

    formhtml = ['<h3>Security settings for "%s":</h3>' % pagename]

    button = _("Save")
    url = page.url()
    d = {'url': url, 'actname': actname, 'button': button}
    formhtml.append('<form method="POST" action="%(url)s">\n'
                    '<input type="hidden" name="action" value="%(actname)s">\n'
                    % d)

    custom_groups = user.getGroupList(request, exclude_special_groups=True)
    grouplist = ['All', 'Known'] + custom_groups
    for groupname in grouplist:
        # "All" and "Known" are a bit condense
        if groupname == 'All':
            written_groupname = 'Everybody'
        elif groupname == 'Known':
            written_groupname = 'Logged in people'
        else:
            written_groupname = groupname

        group = wikiacl.Group(groupname, request, fresh=True)

        # we want to show the 'change security' option only if
        # it makes some sense
        show_admin = groupname in custom_groups

        formhtml.append('<h6>%s</h6>' % written_groupname)
        formhtml.append('<input type="hidden" name="%s_groupname" '
                                  'value="1">' % quoteWikiname(groupname))
        if group.may(page, 'read'):
            formhtml.append('<input type="checkbox" checked '
                                    'name="%s_may_read" value="1">' %
                            quoteWikiname(groupname))
        else:
            formhtml.append('<input type="checkbox" name="%s_may_read" '
                                   'value="1">' % quoteWikiname(groupname))
        formhtml.append(' read ')

        if group.may(page, 'edit'):
            formhtml.append('<input type="checkbox" checked '
                                   'name="%s_may_edit" value="1">' %
                            quoteWikiname(groupname))
        else:
            formhtml.append('<input type="checkbox" name="%s_may_edit" '
                                   'value="1">' % quoteWikiname(groupname))
        formhtml.append(' edit ') 

        if group.may(page, 'delete'):
            formhtml.append('<input type="checkbox" checked '
                                   'name="%s_may_delete" value="1">' %
                            quoteWikiname(groupname))
        else:
            formhtml.append('<input type="checkbox" name="%s_may_delete" '
                                   'value="1">' % quoteWikiname(groupname))
        formhtml.append(' delete ')

        if show_admin:
            if group.may(page, 'admin'):
                formhtml.append('<input type="checkbox" checked '
                                       'name="%s_may_admin" value="1">' %
                                quoteWikiname(groupname))
            else:
                formhtml.append('<input type="checkbox" name="%s_may_admin" '
                                       'value="1">' % quoteWikiname(groupname))
            formhtml.append(' change security ')

    formhtml.append(
        '<p><input type="submit" name="button" value="%(button)s">\n'
        '</p>\n'
        '</form>' % d)

    page.send_page(msg=''.join(formhtml))
Beispiel #43
0
def putFile(request, dict, thumbnail=False, do_delete=False, temporary=False,
            ticket=None, permanent=False):
    """
    Puts the file (found in dict) into the database.
    dict is a dictionary with possible keys: filename, filecontent,
                                             uploaded_time, uploaded_by,
                                             pagename, uploaded_by_ip,
                                             xsize, ysize, deleted_time,
                                             deleted_by, deleted_by_ip.
    """
    from Sycamore.wikiutil import mc_quote, isImage
    from Sycamore.Page import Page
    from Sycamore import caching
    from Sycamore.action.Files import get_filedict

    def set_cache_for_file():
        """
        Sets the memory cache for the new file.
        """
        if not config.memcache:
            return

        if not do_delete:
            if not thumbnail:
                table = 'files'
            else:
                table = 'thumbnails'
            if not temporary:
                key = "%s:%s,%s" % (table, mc_quote(dict['filename']),
                                    mc_quote(dict['pagename'].lower()))
            else:
                key = "%s,%s,%s" % (table, mc_quote(dict['filename']), ticket)
            image_obj = (raw_image, uploaded_time)
            request.mc.set(key, image_obj)
        else:
            if not thumbnail:
                key = "files:%s,%s" % (mc_quote(dict['filename']),
                                       mc_quote(dict['pagename'].lower()))
                request.mc.set(key, False)
            if is_image and thumbnail:
                key = "thumbnails:%s,%s" % (mc_quote(dict['filename']),
                                            mc_quote(dict['pagename'].lower()))
                request.mc.set(key, False)

        # set new file dict
        if not replaced_image:
            get_filedict(request, dict['pagename'], fresh=True, set=True)

    def rebuild_page_cache():
        """
        Rebuilds the page cache.
        """
        if not request.generating_cache and not request.previewing_page:
            from Sycamore import caching
            from Sycamore.Page import Page
            page = Page(dict['pagename'], request)
            if page.exists():
                page.buildCache()

    def handle_file_add():
        request.cursor.execute(
            """SELECT name from files
               where name=%(filename)s and
                     attached_to_pagename=%(pagename)s and
                     wiki_id=%(wiki_id)s""", dict)
        exists = request.cursor.fetchone()
        if exists:
            # backup file, then remove it  
            replaced_image = True
            request.cursor.execute(
                """INSERT into oldFiles
                       (name, file, uploaded_time, uploaded_by,
                        attached_to_pagename, deleted_time, deleted_by,
                        uploaded_by_ip, deleted_by_ip,
                        attached_to_pagename_propercased, wiki_id)
                   values
                       (%(filename)s,
                        (select file from files where name=%(filename)s and
                            attached_to_pagename=%(pagename)s and
                            wiki_id=%(wiki_id)s
                        ),
                        (select uploaded_time from files where
                            name=%(filename)s and
                            attached_to_pagename=%(pagename)s and
                            wiki_id=%(wiki_id)s
                        ),
                        (select uploaded_by from files where
                            name=%(filename)s and
                            attached_to_pagename=%(pagename)s and
                            wiki_id=%(wiki_id)s
                        ),
                        %(pagename)s, %(uploaded_time)s, %(uploaded_by)s,
                        (select uploaded_by_ip from files where
                            name=%(filename)s and
                            attached_to_pagename=%(pagename)s and
                            wiki_id=%(wiki_id)s
                        ),
                        %(uploaded_by_ip)s, %(pagename_propercased)s,
                        %(wiki_id)s)""", dict, isWrite=True)
            if is_image:
                request.cursor.execute(
                    """INSERT into oldImageInfo
                           (name, attached_to_pagename, xsize, ysize,
                            uploaded_time, wiki_id)
                       values
                           (%(filename)s, %(pagename)s,
                            (select xsize from imageInfo where
                                name=%(filename)s and
                                attached_to_pagename=%(pagename)s and
                                wiki_id=%(wiki_id)s
                            ),
                            (select ysize from imageInfo where
                                name=%(filename)s and
                                attached_to_pagename=%(pagename)s and
                                wiki_id=%(wiki_id)s
                            ),
                            (select uploaded_time from files where
                                name=%(filename)s and
                                attached_to_pagename=%(pagename)s and
                                wiki_id=%(wiki_id)s
                            ),
                            %(wiki_id)s)""", dict, isWrite=True)
                request.cursor.execute(
                    """DELETE from imageInfo
                       where name=%(filename)s and
                             attached_to_pagename=%(pagename)s and
                             wiki_id=%(wiki_id)s""", dict, isWrite=True)

            request.cursor.execute(
                """DELETE from files
                   where name=%(filename)s and
                         attached_to_pagename=%(pagename)s and
                         wiki_id=%(wiki_id)s""", dict, isWrite=True)

        request.cursor.execute(
            """INSERT into files
                   (name, file, uploaded_time, uploaded_by,
                    attached_to_pagename, uploaded_by_ip,
                    attached_to_pagename_propercased, wiki_id)
               values
                   (%(filename)s, %(filecontent)s, %(uploaded_time)s,
                    %(uploaded_by)s, %(pagename)s, %(uploaded_by_ip)s,
                    %(pagename_propercased)s, %(wiki_id)s)""",
            dict, isWrite=True)
        if is_image:
            request.cursor.execute(
                """INSERT into imageInfo
                       (name, attached_to_pagename, xsize, ysize, wiki_id)
                   values
                       (%(filename)s, %(pagename)s, %(xsize)s, %(ysize)s,
                        %(wiki_id)s)""", dict, isWrite=True)
      
        caching.updateRecentChanges(page)

    def handle_thumbnail_add():
        request.cursor.execute(
            """SELECT name from thumbnails
               where name=%(filename)s and
                     attached_to_pagename=%(pagename)s and
                     wiki_id=%(wiki_id)s""", dict)
        exists = request.cursor.fetchone()
        if exists:
            request.cursor.execute(
                """UPDATE thumbnails set
                       xsize=%(x)s, ysize=%(y)s, image=%(filecontent)s,
                       last_modified=%(uploaded_time)s
                   where name=%(filename)s and
                         attached_to_pagename=%(pagename)s and
                         wiki_id=%(wiki_id)s""", dict, isWrite=True)
        else:
            request.cursor.execute(
                """INSERT into thumbnails
                       (xsize, ysize, name, image, last_modified,
                        attached_to_pagename, wiki_id)
                   values
                       (%(x)s, %(y)s, %(filename)s, %(filecontent)s,
                        %(uploaded_time)s, %(pagename)s, %(wiki_id)s)""",
                dict, isWrite=True)

    def handle_file_delete():
        request.cursor.execute(
            """SELECT name from files
               where name=%(filename)s and
                     attached_to_pagename=%(pagename)s and
                     wiki_id=%(wiki_id)s""", dict)
        has_file = request.cursor.fetchone()
        if has_file:
            if not permanent:
                # backup file
                request.cursor.execute("""
                    INSERT into oldFiles
                        (name, attached_to_pagename, file, uploaded_by,
                         uploaded_time, deleted_time, deleted_by,
                         uploaded_by_ip, deleted_by_ip,
                         attached_to_pagename_propercased, wiki_id)
                    values
                        (%(filename)s, %(pagename)s,
                         (select file from files
                              where name=%(filename)s and
                                    attached_to_pagename=%(pagename)s and
                                    wiki_id=%(wiki_id)s
                         ),
                         (select uploaded_by from files
                              where name=%(filename)s and
                                    attached_to_pagename=%(pagename)s and
                                    wiki_id=%(wiki_id)s
                         ),
                         (select uploaded_time from files
                              where name=%(filename)s and
                                    attached_to_pagename=%(pagename)s and
                                    wiki_id=%(wiki_id)s
                         ),
                         %(deleted_time)s, %(deleted_by)s,
                         (select uploaded_by_ip from files
                              where name=%(filename)s and
                                    attached_to_pagename=%(pagename)s and
                                    wiki_id=%(wiki_id)s
                         ),
                         %(deleted_by_ip)s,
                         (select attached_to_pagename_propercased from files
                              where name=%(filename)s and
                                    attached_to_pagename=%(pagename)s and
                                    wiki_id=%(wiki_id)s
                         ),
                         %(wiki_id)s)""", dict, isWrite=True)
            else:
                # nuke all old cached versions of the file
                caching.deleteAllFileInfo(dict['filename'], dict['pagename'],
                                          request)
                # nuke all old versions
                request.cursor.execute(
                    """DELETE from oldFiles
                           where name=%(filename)s and
                                 attached_to_pagename=%(pagename)s and
                                 wiki_id=%(wiki_id)s""", dict, isWrite=True)

            if is_image:
                if not permanent:
                    # backup image info
                    request.cursor.execute(
                        """INSERT into oldImageInfo
                           (name, attached_to_pagename, xsize, ysize,
                            uploaded_time, wiki_id)
                           values
                           (%(filename)s, %(pagename)s,
                            (select xsize from imageInfo
                                 where name=%(filename)s and
                                       attached_to_pagename=%(pagename)s and
                                       wiki_id=%(wiki_id)s
                            ),
                            (select ysize from imageInfo
                                 where name=%(filename)s and
                                       attached_to_pagename=%(pagename)s and
                                       wiki_id=%(wiki_id)s
                            ),
                            (select uploaded_time from files
                                  where name=%(filename)s and
                                        attached_to_pagename=%(pagename)s and
                                        wiki_id=%(wiki_id)s
                            ),
                            %(wiki_id)s)""", dict, isWrite=True)
                
                else:
                    # nuke all old versions
                    request.cursor.execute(
                        """DELETE from oldImageInfo
                           where name=%(filename)s and
                                 attached_to_pagename=%(pagename)s and
                                 wiki_id=%(wiki_id)s""", dict, isWrite=True)
                # delete image info
                request.cursor.execute(
                    """DELETE from imageInfo
                       where name=%(filename)s and
                             attached_to_pagename=%(pagename)s and
                             wiki_id=%(wiki_id)s""", dict, isWrite=True)
            # delete file 
            request.cursor.execute(
                """DELETE from files
                   where name=%(filename)s and
                         attached_to_pagename=%(pagename)s and
                         wiki_id=%(wiki_id)s""", dict, isWrite=True)

            caching.updateRecentChanges(page)

    def handle_thumbnail_delete():
        """
        delete thumbnail.
        """
        request.cursor.execute(
            """DELETE from thumbnails
               where name=%(filename)s and
                     attached_to_pagename=%(pagename)s and
                     wiki_id=%(wiki_id)s""", dict, isWrite=True)

    # prep for insert of binary data
    if dict.has_key('filecontent'):
        raw_image = dict['filecontent']
        uploaded_time = dict['uploaded_time']
        dict['filecontent'] = dbapi.Binary(raw_image)

    page = Page(dict['pagename'], request)
    dict['pagename_propercased'] = page.proper_name()
    dict['pagename'] = dict['pagename'].lower()
    dict['wiki_id'] = request.config.wiki_id

    replaced_image = False
    is_image = isImage(dict['filename'])
      
    if temporary:
        # we don't update the database in this case
        set_cache_for_file()
        rebuild_page_cache()
        return

    if not thumbnail and not do_delete:
        handle_file_add()
    elif thumbnail and not do_delete:
        handle_thumbnail_add()
    elif do_delete:
        if not thumbnail:
            handle_file_delete()            
        else:
            handle_thumbnail_delete()

    set_cache_for_file()
    rebuild_page_cache()
Beispiel #44
0
def format_page_edits(request, lines, showcomments, bookmark, formatter,
                      wiki_global=False, grouped_by_wiki=False):
    _ = request.getText
    d = {} # dict for passing stuff to theme
    line = lines[0]
    d['show_comments'] = showcomments
    pagename = line.pagename
    tnow = time.time()
    
    # check whether this page is newer than the user's bookmark
    hilite = line.ed_time > (bookmark or line.ed_time)
    if wiki_global:
        page = Page(line.pagename, request, wiki_name=line.wiki_name)
    else:
        page = Page(line.pagename, request)
    # we can infer 'exists?' from current rc data in some cases
    getPageStatus(lines, pagename, request) 

    html_link = format_page_edit_icon(request, lines, page, hilite, bookmark,
                                      formatter)
    
    # print name of page, with a link to it
    force_split = len(page.page_name) > _MAX_PAGENAME_LENGTH
    
    d['rc_tag_html'] = html_link

    if wiki_global:
        if not grouped_by_wiki:
            on_wiki = (' <span class="minorText">(on %s)</span>' %
                       farm.link_to_wiki(line.wiki_name, formatter))
        else:
            on_wiki = ''
        d['pagelink_html'] = '%s%s' % (
            page.link_to(text=pagename, absolute=True), on_wiki)
    else:
        d['pagelink_html'] = page.link_to(text=pagename) 
    
    # print time of change
    d['time_html'] = None
    if config.changed_time_fmt:
        tdiff = int(tnow - line.ed_time) / 60
        if tdiff < 1440:
            numhrs = int(tdiff/60)
            nummins = tdiff%60
            txthrs = ""
            txttime = ""
            if numhrs == 1:
               txthrs = '1 hour'
            if numhrs > 1:
               txthrs = '%s hours' % str(numhrs)
            txttime = txthrs
            if nummins == 1:
               txttime = '%s 1 minute' % str(txthrs)
            if nummins > 1:
               txttime = '%s %s minutes' % (str(txthrs), str(nummins))
            if nummins == 0 and numhrs == 0:
               numsecs = int(tnow - line.ed_time) % 60
               txttime = '%s second' % str(numsecs)
               if numsecs > 1:
                 txttime = '%ss' % txttime
            d['time_html'] = '%s ago' % txttime
        else:
            d['time_html'] = time.strftime("at %I:%M %p", line.time_tuple)
    
    # print editor name or IP
    d['editors'] = []
    if config.show_hosts:
        for idx in range(len(lines)):
            name = getEditor(lines[idx], request)
            ip = lines[idx].host
            d['editors'].append((name,ip))

    comments = []
    for idx in range(len(lines)):
        comment = Comment(request, lines[idx].comment,
                          lines[idx].action, page).render()
        comments.append(comment)
    
    d['changecount'] = len(lines)
    d['comments'] = comments

    return request.theme.recentchanges_entry(d)
Beispiel #45
0
def execute(pagename, request):
    _ = request.getText
    actname = __name__.split('.')[-1]
    page = PageEditor(pagename, request)
    pagetext = page.get_raw_body()
    msg = ''

    # be extra paranoid in dangerous actions
    if (actname in config.excluded_actions or not request.user.may.edit(page)
            or not request.user.may.delete(page)):
        msg = _('You are not allowed to rename pages in this wiki!')

    # check whether page exists at all
    elif not page.exists():
        msg = _('This page is already deleted or was never created!')

    # check whether the user clicked the delete button
    elif (request.form.has_key('button')
          and request.form.has_key('newpagename')
          and request.form.has_key('ticket')):
        # check whether this is a valid renaming request (make outside
        # attacks harder by requiring two full HTTP transactions)
        if not _checkTicket(request.form['ticket'][0]):
            msg = _('Please use the interactive user '
                    'interface to rename pages!')
        else:
            renamecomment = request.form.get('comment', [''])[0]
            # strip to ensure naming consistency
            newpagename = request.form.get('newpagename')[0].strip()
            if newpagename == pagename:
                return Page(pagename, request).send_page(
                    msg="You can't rename a page to the name it already has!")
            try:
                newpage = PageEditor(newpagename, request)
            except Page.ExcessiveLength, msg:
                return Page(pagename, request).send_page(msg=msg)

            if len(renamecomment) > wikiaction.MAX_COMMENT_LENGTH:
                msg = _('Comments must be less than %s characters long.' %
                        wikiaction.MAX_COMMENT_LENGTH)
            elif len(newpagename) > MAX_PAGENAME_LENGTH:
                msg = _('Page names must be less than %s characters long.' %
                        MAX_PAGENAME_LENGTH)
            # check whether a page with the new name already exists
            elif (newpage.exists()
                  and not (newpagename.lower() == pagename.lower())):
                msg = _('A page with the name "%s" already exists!') % (
                    newpagename)

            elif not wikiaction.isValidPageName(newpagename):
                msg = _('Invalid pagename: Only the characters A-Z, a-z, 0-9, '
                        '"$", "&", ",", ".", "!", "\'", ":", ";", " ", "/", '
                        '"-", "(", ")" are allowed in page names.')

            # we actually do a rename!
            else:
                if renamecomment: renamecomment = " (" + renamecomment + ")"
                if newpagename.lower() != pagename.lower():
                    page.saveText("#redirect %s" % newpagename,
                                  '0',
                                  comment='Renamed to "%s"' % newpagename,
                                  action='RENAME',
                                  force_save=True)
                    # copy images over
                    copy_files(pagename, newpagename, request)

                newpage.saveText(pagetext,
                                 '0',
                                 comment='Renamed from "%s"%s' %
                                 (pagename, renamecomment),
                                 action="RENAME",
                                 proper_name=newpagename)

                msg = _('Page "%s" was successfully renamed to "%s"!') % (
                    pagename, newpagename)
                if newpagename.lower() != pagename.lower():
                    # check favorites because the redirect will
                    # process before the bookmarks get updated
                    if request.user.valid:
                        request.user.checkFavorites(page)

                    request.http_redirect(
                        '%s/%s?action=show&redirect=%s' %
                        (request.getScriptname(),
                         wikiutil.quoteWikiname(newpagename),
                         urllib.quote_plus(pagename.encode(config.charset),
                                           '')))

                    request.req_cache['pagenames'][(
                        newpagename.lower(),
                        request.config.wiki_name)] = newpagename
                    # we clear so the new page name appears
                    caching.CacheEntry(newpagename.lower(), request).clear()
                    return
                else:
                    request.req_cache['pagenames'][(
                        newpagename.lower(),
                        request.config.wiki_name)] = newpagename
                    # we clear so the new page name appears
                    caching.CacheEntry(newpagename.lower(), request).clear()
                    return newpage.send_page(msg)
Beispiel #46
0
    def sendEditor(self, **kw):
        """
        Send the editor form page.

        @keyword preview: if given, show this text in preview mode
        @keyword staytop: don't go to #preview
        @keyword comment: comment field (when preview is true)
        @keyword had_conflict: we had an edit conflict on a save.
        """
        import re

        try:
            from Sycamore.action import SpellCheck
        except ImportError:
            SpellCheck = None

        form = self.request.form
        _ = self._
        self.request.http_headers([("Content-Type", "text/html; charset=%s" %
                                    config.charset)] + self.request.nocache)
        msg = None
        preview = kw.get('preview', None)
        emit_anchor = not kw.get('staytop', 0)
        proper_name = self.proper_name()

        from Sycamore.formatter.text_html import Formatter
        self.request.formatter = Formatter(self.request,
                                           store_pagelinks=1,
                                           preview=preview)

        base_uri = "%s/%s?action=edit" % (self.request.getScriptname(),
                                          wikiutil.quoteWikiname(
                                              self.proper_name()))
        backto = form.get('backto', [None])[0]
        if backto:
            base_uri += '&amp;' + util.web.makeQueryString(backto=backto)

        # check edit permissions
        if not self.request.user.may.edit(self):
            msg = _('You are not allowed to edit this page.')
        elif self.prev_date:
            # Trying to edit an old version, this is not possible via
            # the web interface, but catch it just in case...
            msg = _('Cannot edit old revisions!')

        # Did one of the prechecks fail?
        if msg and not kw.get('had_conflict', None):
            self.send_page(msg=msg)
            return

        # check for preview submit
        if preview is None:
            title = _('Edit "%(pagename)s"')
        else:
            title = _('Preview of "%(pagename)s"')
            self.set_raw_body(preview.replace("\r", ""), 1)

        page_needle = self.page_name
        if config.allow_subpages and page_needle.count('/'):
            page_needle = '/' + page_needle.split('/')[-1]

        wikiutil.send_title(
            self.request,
            self.proper_name(),
            pagename=self.proper_name(),
            has_link=True,
            strict_title='Editing "%s"' % self.proper_name(),
            body_onload="sizeForIE('savetext', 100, 'editorComment', 99);")

        # start content div
        self.request.write('<div id="content" class="content">\n')

        # get request parameters
        text_rows = None
        if form.has_key('rows'):
            text_rows = int(form['rows'][0])
            if self.request.user.valid:
                # possibly update user's pref
                if text_rows != self.request.user.edit_rows:
                    self.request.user.edit_rows = text_rows
                    self.request.user.save()
        else:
            text_rows = config.edit_rows
            if self.request.user.valid:
                text_rows = int(self.request.user.edit_rows)

        if form.has_key('cols'):
            text_cols = int(form['cols'][0])
            if self.request.user.valid:
                # possibly update user's pref
                if text_rows != self.request.user.edit_rows:
                    self.request.user.edit_rows = text_rows
                    self.request.user.save()
        else:
            text_cols = 80
            if self.request.user.valid:
                text_cols = int(self.request.user.edit_cols)

        # check datestamp (version) of the page our edit is based on
        if preview is not None:
            # propagate original datestamp
            mtime = float(form['datestamp'][0])

            # did someone else change the page while we were editing?
            conflict_msg = None
            if not self.exists():
                # page does not exist, are we creating it?
                if mtime:
                    conflict_msg = _('<p>Someone else <b>deleted</b> this '
                                     'page while you were editing!')
            elif mtime != self.mtime():
                conflict_msg = _('<p>Someone else changed this page while '
                                 'you were editing.')
                # merge conflicting versions
                allow_conflicts = 1
                from Sycamore.util import diff3
                savetext = self.get_raw_body()
                oldpg = Page(self.page_name, self.request, prev_date=mtime)
                original_text = oldpg.get_raw_body()
                saved_text = Page(self.page_name, self.request).get_raw_body()
                verynewtext, had_conflict = diff3.text_merge(
                    original_text,
                    saved_text,
                    savetext,
                    marker1='----- /!\ Edit conflict! Your version: -----\n',
                    marker2='----- /!\ Edit conflict! Other version: -----\n',
                    marker3='----- /!\ End of edit conflict -----\n')
                if had_conflict and self.request.user.valid and (
                        self.request.user.id == self.last_edit_info()[1]):
                    # user pressed back button or did something weird
                    conflict_msg = None
                elif had_conflict:
                    conflict_msg = _(conflict_msg +
                                     'There was an <b>edit conflict between '
                                     'your changes!</b></p>'
                                     '<p>Please review the conflicts and '
                                     'merge the changes.</p>')
                    mtime = self.mtime()
                    self.set_raw_body(verynewtext, 1)
                else:
                    conflict_msg = _(conflict_msg +
                                     'Your changes were sucessfully merged!')
                    mtime = self.mtime()
                    self.set_raw_body(verynewtext)

            if conflict_msg:
                self.request.write('<div id="message"><div>%s'
                                   '</div></div>' % conflict_msg)
                emit_anchor = 0  # make this msg visible!
        elif self.exists():
            # datestamp of existing page
            mtime = self.mtime()
        else:
            # page creation
            mtime = 0

        # output message
        message = kw.get('msg', '')
        if message:
            self.request.write('<div id="message">%s</div>' % (message))

        # get the text body for the editor field
        if form.has_key('template'):
            # "template" parameter contains the name of the template page
            template_page = wikiutil.unquoteWikiname(form['template'][0])
            raw_body = Page(template_page, self.request).get_raw_body()
        else:
            raw_body = self.get_raw_body()

        # send text above text area

        # button toolbar
        self.request.write('<div id="editArea">')
        self.request.write(
            "<script type=\"text/javascript\">"
            "var buttonRoot = '%s';</script>" % (os.path.join(
                config.url_prefix, self.request.theme.name, 'img', 'buttons')))
        if self.request.user.name:
            if config.user_page_prefix:
                self.request.write(
                    "<script type=\"text/javascript\">"
                    "var userPageLink = '[\"%s%s\"]';</script>" %
                    (config.user_page_prefix,
                     self.request.user.propercased_name))
            else:
                self.request.write("<script type=\"text/javascript\">"
                                   "var userPageLink = '[\"%s\"]';</script>" %
                                   (config.user_page_prefix,
                                    self.request.user.propercased_name))
        else:
            self.request.write("<script type=\"text/javascript\">"
                               "var userPageLink = '%s';</script>" %
                               (self.request.remote_addr))

        if config.wiki_farm:
            self.request.write(
                "<script type=\"text/javascript\" "
                "src=\"http://%s%s%s/edit.js\"></script>\n" %
                (config.wiki_base_domain, config.web_dir, config.url_prefix))
        else:
            self.request.write("<script type=\"text/javascript\" "
                               "src=\"%s%s/edit.js\"></script>\n" %
                               (config.web_dir, config.url_prefix))

        # send form
        self.request.write('<form name="editform" id="editform" '
                           'method="post" action="%s/%s#preview">' %
                           (self.request.getScriptname(),
                            wikiutil.quoteWikiname(proper_name)))

        self.request.write(
            str(html.INPUT(type="hidden", name="action", value="savepage")))
        if backto:
            self.request.write(
                str(html.INPUT(type="hidden", name="backto", value=backto)))

        # generate default content
        if not raw_body:
            if self.isTalkPage():
                raw_body = _('This page is for discussing the '
                             'contents of ["%s"].') % self.proper_name()[:-5]
            else:
                raw_body = _('Describe %s here.') % (self.proper_name(), )

        # replace CRLF with LF
        raw_body = self._normalize_text(raw_body)

        # send datestamp (version) of the page our edit is based on
        self.request.write('<input type="hidden" name="datestamp" '
                           'value="%s">' % repr(mtime))

        # Print the editor textarea and the save button
        self.request.write('<textarea id="savetext" name="savetext" '
                           'rows="%d" cols="%d" style="width:100%%;">%s'
                           '</textarea>' %
                           (text_rows, text_cols, wikiutil.escape(raw_body)))

        # make sure we keep the template notice on a resize of the editor
        template_param = ''
        if form.has_key('template'):
            template_param = '&amp;template=' + form['template'][0]

    # draw edit size links
        self.request.write(
            _('<div class="pageEditInfo" id="editorSize">'
              'editor size:'))
        self.request.write('<a href="#" onclick="return sizeEditor(\'bigger\','
                           '\'%s&amp;preview=1&amp;cols=60%s\')">%s'
                           '</a>' % (base_uri, template_param, '+'))
        self.request.write(
            ',<a href="#" onclick="return sizeEditor(\'smaller\','
            '\'%s&amp;preview=1&amp;cols=60%s\')">%s'
            '</a>' % (base_uri, template_param, '-'))
        self.request.write('</div>')
        self.request.write('</p>')  # close textarea

        self.request.write(
            '<div id="editComment" id="editorResizeButtons"> '
            '%s<br><input type="text" class="formfields" '
            'name="comment" id="editorComment" value="%s" '
            'size="%d" maxlength="80" style="width:99%%;">'
            '</div>' % (_("<font size=\"+1\">Please comment "
                          "about this change:</font>"),
                        wikiutil.escape(kw.get('comment', ''), 1), text_cols))

        spam_catch_button = (
            '<span style="position: absolute; top: 0px; left: 0px;'
            'height: 0px; width: 0px; overflow: hidden;">'
            'dont enter into this box:'
            '<input type="text" name="text_dont"/>'
            '</span>'
            '<span style="position: absolute; top: 0px; left: 0px;'
            'height: 0px; width: 0px; overflow: hidden;">'
            '<input class="formbutton" type="submit" name="button_dont" '
            'value="Dont press me">\n'
            '</span>')
        self.request.write(spam_catch_button)

        # button bar
        button_spellcheck = (
            SpellCheck and
            '<input type="submit" class="formbutton" name="button_spellcheck"'
            ' value="%s">' % _('Check Spelling')) or ''

        save_button_text = _('Save Changes')
        cancel_button_text = _('Cancel')

        self.request.write("</div>")

        if self.request.user.may.admin(self):
            security_button = ('<input type="button" class="formbutton" '
                               'onClick="location.href='
                               '\'%s/%s?action=Security\'" '
                               'value="Security">') % (
                                   self.request.getScriptname(),
                                   wikiutil.quoteWikiname(proper_name))
        else:
            security_button = ''

        if self.request.user.may.delete(self):
            delete_button = ('<input type="button" class="formbutton" '
                             'onClick="location.href='
                             '\'%s/%s?action=DeletePage\'" value="Delete">'
                             ) % (self.request.getScriptname(),
                                  wikiutil.quoteWikiname(proper_name))
            rename_button = ('<input type="button" class="formbutton" '
                             'onClick="location.href=\'%s/%s?action=Rename\'"'
                             ' value="Rename">') % (self.request.getScriptname(
                             ), wikiutil.quoteWikiname(proper_name))
        else:
            delete_button = ''
            rename_button = ''

        self.request.write(
            '<div id="editButtonRow">'
            '<span>'
            '<input type="submit" class="formbutton" '
            'name="button_preview" value="%s"> '
            '<input type="submit" class="formbutton" '
            'name="button_save" value="%s"> '
            '<input type="submit" class="formbutton" '
            'name="button_cancel" value="%s"> '
            '</span>'
            '<span class="editActions">'
            '<input type="button" class="formbutton" '
            'onClick="window.open(\'%s/%s?action=Files\', '
            '\'files\', \'width=800,height=600,'
            'scrollbars=1\')" value="Upload Files"> '
            '%s '
            '%s '
            '%s '
            '%s</span>'
            '</div>' %
            (_('Preview'), save_button_text, cancel_button_text,
             self.request.getScriptname(), wikiutil.quoteWikiname(proper_name),
             button_spellcheck, delete_button, rename_button, security_button))

        if self.request.config.edit_agreement_text:
            self.request.write(self.request.config.edit_agreement_text)

        badwords_re = None
        if preview is not None:
            if SpellCheck and (form.has_key('button_spellcheck')
                               or form.has_key('button_newwords')):
                badwords, badwords_re, msg = SpellCheck.checkSpelling(
                    self, self.request, own_form=0)
                self.request.write("<p>%s</p>" % msg)
        self.request.write("</form>")

        if config.wiki_farm:
            from Sycamore import farm
            help_link = farm.link_to_page(farm.getBaseWikiName(),
                                          "Help with Editing",
                                          self.request.formatter,
                                          force_farm=True)
        else:
            help_link = Page("Help with Editing", self.request).link_to()

        # QuickHelp originally by Georg Mischler <*****@*****.**>
        self.request.write(
            '<h2>Editing quick-help</h2>\n'
            '<dl><div style="float: right; margin: 10px; border: 1px solid; '
            'padding: 3pt;">See <b>%s</b> for more information.</div>' %
            (help_link) +
            _("<dt>Emphasis:</dt>\n"
              "<dd>''<em>italics</em>''; '''<strong>bold</strong>''';"
              "'''''<strong><em>bold italics</em></strong>''''';"
              "''<em>mixed '''<strong>bold</strong>''' and "
              "italics</em>''; ---- horizontal rule.</dd>"
              "<dt>Headings:</dt>"
              "<dd>= Title 1 =; == Title 2 ==; === Title 3 ===;"
              "==== Title 4 ====; ===== Title 5 =====.</dd>"
              "<dt>Lists:</dt>"
              "<dd>space and one of * bullets; 1., a., A., i., I. "
              "numbered items;"
              "  1.#n start numbering at n; space alone indents.</dd>"
              "<dt>Links:</dt>"
              "<dd>[\"brackets and double quotes\"]; [\"the exact "
              "page name\" label];"
              "  url; [url]; [url label].</dd>"
              "<dt>Tables:</dt>"
              "<dd>|| cell text |||| cell text spanning two columns ||;"
              "  no trailing white space allowed after tables or titles."
              "</dd></dl>"))

        if preview is not None:
            if not emit_anchor:
                preview_name = "previewHide"
            else:
                preview_name = "preview"
            self.request.write('<div id="%s" class="preview">' % preview_name)
            self.send_page(content_only=1,
                           hilite_re=badwords_re,
                           preview=preview)
            self.request.write('</div>')

        self.request.write('</div>\n')  # end content div

        wikiutil.send_after_content(self.request)

        self.request.theme.emit_custom_html(config.page_footer1)
        self.request.theme.emit_custom_html(config.page_footer2)

        self.request.write('</body></html>')
Beispiel #47
0
def mapJS(wiki_name, page_locs, nearby_locs, request):
    """
    Create a string containing javascript for google map
    page = the page object
    place = place object of center of map
    nearby = dictionary of nearby places
    """
    # pick center point as the first point if there's more than one point
    # associated with the page
    center = page_locs[0]

    pagename = center.pagename
    page = Page(pagename, request, wiki_name=wiki_name)
    out = """
<script type="text/javascript">
//<![CDATA[
function doLoad() {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl()); 
map.setCenter(new GLatLng(%s,%s),16);
        """ % (center.latitude, center.longitude)

    nearbys_processed = {}
    i = 0  # for 'a' 'b' labels on markers
    if nearby_locs:
        for x in nearby_locs:
            nearby_page = Page(x.pagename, request, wiki_name=wiki_name)
            if (x.pagename, x.latitude, x.longitude) in nearbys_processed:
                # only plot a given nearby point once
                # (it is sometimes easier to just have repeated nearbys
                # in the query, hence we filter them out here)
                continue
            namestr = ("""'<b><a href="%s" target=_parent>%s</a></b>"""
                       """<br>%s'""" % (nearby_page.url(relative=False),
                                        x.pagename.replace("'", "\\" + "'"),
                                        x.address.replace("'", "\\" + "'")))
            out += """
            var point = new GLatLng(%s,%s);
            map.addOverlay(createMarker(point,%s, %s));
            """ % (x.latitude, x.longitude, i, namestr)
            # add it as plotted
            nearbys_processed[(x.pagename, x.latitude, x.longitude)] = None
            i += 1

    for x in page_locs:
        namestr = (
            """'<b><a href="%s" target=_parent>%s</a></b>"""
            """<br>%s'""" %
            (page.url(relative=False), x.pagename.replace(
                "'", "\\" + "'"), x.address.replace("'", "\\" + "'")))
        out += ("var p_point = new GLatLng(%s,%s);\n"
                "var myArrow = createArrow(p_point,%s);\n"
                "map.addOverlay(myArrow);\n"
                "GEvent.trigger(myArrow,'click');" %
                (x.latitude, x.longitude, namestr))

    out += """
            loaded = true;
       }
       //]]>
       </script>"""
    return out
Beispiel #48
0
def checkSpelling(page, request, own_form=1):
    """
    Do spell checking, return a tuple with the result.
    """
    _ = request.getText

    # first check to see if we we're called with a "newwords" parameter
    if request.form.has_key('button_newwords'):
        _addLocalWords(request)

    # load words
    wordsdict = _loadDict(request)

    localwords = {}
    lsw_page = Page(request.config.page_local_spelling_words, request)
    if lsw_page.exists():
        _loadWordsString(request, localwords, lsw_page.get_raw_body())

    # init status vars & load page
    badwords = {}
    text = page.get_raw_body()

    # checker regex and matching substitute function
    word_re = re.compile(r'([%s]?[%s]+)' %
                         (config.upperletters, config.lowerletters))

    def checkword(match,
                  wordsdict=wordsdict,
                  badwords=badwords,
                  localwords=localwords,
                  num_re=re.compile(r'^\d+$')):
        word = match.group(1)
        if len(word) == 1:
            return ""
        if not (wordsdict.has_key(word) or wordsdict.has_key(word.lower()) or
                localwords.has_key(word) or localwords.has_key(word.lower())):
            if not num_re.match(word):
                badwords[word] = 1
        return ""

    # do the checking
    for line in text.encode('utf-8').split('\n'):
        if line == '' or line[0] == '#': continue
        word_re.sub(checkword, line)

    if badwords:
        badwords = badwords.keys()
        badwords.sort(lambda x, y: cmp(x.lower(), y.lower()))

        # build regex recognizing the bad words
        badwords_re = r'(^|(?<!\w))(%s)(?!\w)'
        badwords_re = badwords_re % ("|".join(map(re.escape, badwords)), )
        # XXX UNICODE re.UNICODE !?
        badwords_re = re.compile(badwords_re)

        lsw_msg = ''
        if localwords:
            lsw_msg = ' ' + _('(including %(localwords)d %(pagelink)s)') % {
                'localwords': len(localwords),
                'pagelink': lsw_page.link_to()
            }
        msg = _('The following %(badwords)d words could not be found '
                'in the dictionary of '
                '%(totalwords)d words%(localwords)s and are '
                'highlighted below:') % {
                    'badwords': len(badwords),
                    'totalwords': len(wordsdict) + len(localwords),
                    'localwords': lsw_msg
                } + "<br>"

        # figure out what this action is called
        action_name = os.path.splitext(os.path.basename(__file__))[0]

        # add a form containing the bad words
        if own_form:
            msg = msg + ('<form method="POST" action="%s">'
                         '<input type="hidden" name="action" value="%s">' % (
                             page.url(request),
                             action_name,
                         ))
        checkbox = ('<input type="checkbox" name="newwords" '
                    'value="%(word)s">%(word)s&nbsp;&nbsp;')
        msg = msg + (
            " ".join(
                map(lambda w, cb=checkbox: cb % {
                    'word': wikiutil.escape(w),
                },
                    badwords)) +
            '<p><input type="submit" name="button_newwords" value="%s"></p>' %
            _('Add checked words to dictionary'))
        if own_form:
            msg = msg + '</form>'
    else:
        badwords_re = None
        msg = _("No spelling errors found!")

    return badwords, badwords_re, msg
Beispiel #49
0
    def testUrl(self):
        """Test's Page.url()."""
        from Sycamore.Page import Page
        from Sycamore import farm
        list_of_wikis = self._get_list_of_wikis()

        # relative, w/o query string
        for trial in xrange(0, 200):
            pagename = make_random_string(MAX_PAGENAME_LENGTH)
            page = Page(pagename, self.request)
            pagename = page.proper_name()
            pagename_encoded = wikiutil.quoteWikiname(pagename)
            proper_url = '/%s' % pagename_encoded
            self.assertEqual(proper_url, page.url())

        # relative, w/ query string
        for trial in xrange(0, 200):
            pagename = make_random_string(MAX_PAGENAME_LENGTH)
            query = '?'
            the_range = random.randint(0, 10)
            for i in xrange(0, the_range):
                if i < (the_range-1): amperstand = '&'
                else: amperstand = ''
                query += ('%s=%s%s' %
                    (make_random_string(50, alphanum_only=True),
                     make_random_string(50, alphanum_only=True),
                     amperstand))
            page = Page(pagename, self.request)
            pagename = page.proper_name()
            pagename_encoded = wikiutil.quoteWikiname(pagename)
            proper_url = '/%s?%s' % (pagename_encoded, query)
            self.assertEqual(proper_url, page.url(querystr = query))

        original_wiki_name = self.request.config.wiki_name

        # absolute url, switched request
        for wiki_trial in xrange(0, 10):
            self.request.switch_wiki(random.choice(list_of_wikis))
            for trial in xrange(0, 200):
                pagename = make_random_string(MAX_PAGENAME_LENGTH)
                farm_url = farm.getWikiURL(self.request.config.wiki_name,
                                           self.request)
                page = Page(pagename, self.request)
                pagename = page.proper_name()
                pagename_encoded = wikiutil.quoteWikiname(pagename)
                proper_url = '%s%s' % (farm_url, pagename_encoded)
                self.assertEqual(proper_url, page.url(relative=False))

            for trial in xrange(0, 200):
                pagename = make_random_string(MAX_PAGENAME_LENGTH)
                farm_url = farm.getWikiURL(self.request.config.wiki_name,
                                           self.request)
                query = '?'
                the_range = random.randint(0, 10)
                for i in xrange(0, the_range):
                    if i < (the_range-1):
                        amperstand = '&'
                    else:
                        amperstand = ''
                    query += ('%s=%s%s' %
                        (make_random_string(50, alphanum_only=True),
                         make_random_string(50, alphanum_only=True),
                         amperstand))
                page = Page(pagename, self.request)
                pagename = page.proper_name()
                pagename_encoded = wikiutil.quoteWikiname(pagename)
                proper_url = '%s%s?%s' % (farm_url, pagename_encoded, query)
                self.assertEqual(proper_url,
                                 page.url(querystr=query, relative=False))

        self.request.switch_wiki(original_wiki_name)

        # absolute url, non-switched request
        for wiki_trial in xrange(0, 10):
            wiki_name = random.choice(list_of_wikis)
            for trial in xrange(0, 200):
                pagename = make_random_string(MAX_PAGENAME_LENGTH)
                farm_url = farm.getWikiURL(wiki_name, self.request)
                page = Page(pagename, self.request, wiki_name=wiki_name)
                pagename = page.proper_name()
                pagename_encoded = wikiutil.quoteWikiname(pagename)
                proper_url = '%s%s' % (farm_url, pagename_encoded)
                self.assertEqual(proper_url, page.url(relative=False))

            for trial in xrange(0, 200):
                pagename = make_random_string(MAX_PAGENAME_LENGTH)
                farm_url = farm.getWikiURL(wiki_name, self.request)
                query = '?'
                the_range = random.randint(0, 10)
                for i in xrange(0, the_range):
                    if i < (the_range-1):
                        amperstand = '&'
                    else:
                        amperstand = ''
                    query += ('%s=%s%s' %
                        (make_random_string(50, alphanum_only=True),
                         make_random_string(50, alphanum_only=True),
                         amperstand))
                page = Page(pagename, self.request, wiki_name=wiki_name)
                pagename = page.proper_name()
                pagename_encoded = wikiutil.quoteWikiname(pagename)
                proper_url = '%s%s?%s' % (farm_url, pagename_encoded, query)
                self.assertEqual(proper_url,
                                 page.url(querystr = query, relative=False))
Beispiel #50
0
def execute(pagename, request):
    from Sycamore.PageEditor import PageEditor
    _ = request.getText
    actname = __name__.split('.')[-1]
    page = Page(pagename, request)
    permanent = False
    showrc = True
    if not request.user.may.edit(page):
        return page.send_page(
            msg = _('You are not allowed to revert this page!'))

    # check whether the user clicked the delete button
    if request.form.has_key('button') and request.form.has_key('ticket'):
        # check whether this is a valid deletion request (make outside
        # attacks harder by requiring two full HTTP transactions)
        if not _checkTicket(request.form['ticket'][0]):
            return page.send_page(
                msg = _('Please use the interactive user interface to '
                        'revert pages!'))
        # revert the page
        if request.form.has_key('version'):
            version = int(request.form['version'][0])
            oldpg = Page(pagename, request, version=version)
            date = oldpg.prev_date
            if request.form.has_key('comment'):
                entered_comment = request.form['comment'][0]
            else:
                entered_comment = ''
            if len(entered_comment) > wikiaction.MAX_COMMENT_LENGTH:
                return page.send_page(msg = _(
                    'Comments must be less than %s characters long.' %
                    wikiaction.MAX_COMMENT_LENGTH))
            else:
                comment = 'v%s' % str(version)

            comment = "%sc%s" % (comment, entered_comment)
        else:
            return

        if (request.form.has_key('permanent') and
            request.form['permanent'][0] and request.user.may.admin(page)):
            permanent = True
            if (request.form.has_key('noshowrc') and
                request.form['noshowrc'][0]):
                showrc = False

        pg = PageEditor(pagename, request)
        savemsg = revert_to_page(oldpg, request, pg, comment=comment,
                                 permanent=permanent, showrc=showrc)
        return pg.send_page(msg=savemsg,
                            force_regenerate_content=(permanent and not
                                                      showrc))

    # get version
    if request.form.has_key('version'):
        version = request.form['version'][0]
    else:
        return page.send_page(msg= _(
            'Please use the interactive user interface to revert pages!'))

    oldpg = Page(pagename, request, version=version)
    # send revert form
    url = page.url()
    ticket = _createTicket()
    button = _('Revert')
    comment_label = _("Reason for the revert:")
    if request.user.may.admin(page):
        admin_label = (
            '<p>Permanently remove newer versions: '
            '<input id="noshowrctoggle" type="checkbox" name="permanent" '
                   'value="1"><span id="noshowrc">'
            "Don't log on Recent Changes: "
            '<input type="checkbox" name="noshowrc" value="1"></span></p>\n'
            '<script type="text/javascript">\n'
            "document.getElementById('noshowrc').style.visibility = "
                "'hidden';\n"
            "document.getElementById('noshowrc').style.paddingLeft = "
                "'1em';\n"
            "document.getElementById('noshowrctoggle').onclick = "
                "function () {\n"
            "document.getElementById('noshowrc').style.visibility = "
                "document.getElementById('noshowrctoggle').checked ? "
                    "'visible' : 'hidden'; \n"
            "}\n"
            "</script>\n"
        )
    else:
        admin_label = ''

    formhtml = (
        '<form method="GET" action="%(url)s">'
        '<input type="hidden" name="action" value="%(actname)s">'
        '<input type="hidden" name="ticket" value="%(ticket)s">'
        '<input type="hidden" name="version" value="%(version)s">'
        '<p>'
        '%(comment_label)s'
        '</p>'
        '<input type="text" name="comment" size="60" maxlength="80">'
        '<input type="submit" name="button" value="%(button)s">'
        '%(admin_label)s'
        '</form>' % {
            'url': url,
            'actname': actname,
            'ticket': ticket,
            'button': button,
            'comment_label': comment_label,
            'version': version,
            'admin_label': admin_label,
    })

    return oldpg.send_page(msg=formhtml)