Exemplo n.º 1
0
def image_dialog(request):
    _ = request.getText
    url_prefix_static = request.cfg.url_prefix_static

    # wiki url
    requestUrl = request.url
    if requestUrl.find('?') == -1:
        requestUrl = requestUrl + '?action=fckdialog&dialog=image'
    action = requestUrl.split('?')[0]
    ticket = wikiutil.createTicket(request,
                                   pagename=request.page.page_name,
                                   action='AttachFile')
    redirectUrl = requestUrl

    attachmentsPagename = request.page.page_name
    attachments = _get_files(request, attachmentsPagename)
    attachments = filter(
        lambda attachment: attachment.endswith('.gif') or attachment.endswith(
            '.png') or attachment.endswith('.jpg') or attachment.endswith(
                '.jpeg'), attachments)
    attachments.sort()

    attachment_urls = {}
    for attachment in attachments:
        attachment_urls[attachment] = getAttachUrl(request.page.page_name,
                                                   attachment,
                                                   request,
                                                   do='get')

    engine = tenjin.Engine(path=[os.path.dirname(__file__) + '/views'])
    html = engine.render('image_dialog.pyhtml', locals())
    request.write(html)
Exemplo n.º 2
0
def render(req, f, content, parent='', depth=0):
    listfmt = {'class': 'attachtree_list'}
    direntryfmt = {'class': 'attachtree_direntry'}
    fileentryfmt = {'class': 'attachtree_fileentry'}

    result = f.bullet_list(1, **listfmt)

    for entry, values in sorted(content.items()):
        fullname = os.path.join(parent, unicode(entry))
        fullname = fullname.replace(os.sep, quote(os.sep, safe=""))
        if not values.items():
            result += f.listitem(1, **fileentryfmt)
            link = getAttachUrl(f.page.page_name,
                                fullname.encode("iso-8859-15"), req)
            result += f.url(1, link, 'attachtree_link')
            result += f.text(unquote(entry))
            result += f.url(0)
            result += f.listitem(0)
        else:
            result += f.listitem(1, **direntryfmt)
            result += f.text(unquote(entry))
            result += f.listitem(0)
            result += render(req, f, values, fullname, depth + 1)

    result += f.bullet_list(0)
    return result
Exemplo n.º 3
0
def handle_file_attached(event):
    """Sends an email to super users that have subscribed to this event type"""

    names = set()
    from_address = event.request.cfg.mail_from
    request = event.request
    page = Page(request, event.pagename)

    subscribers = page.getSubscribers(request, return_users=1)
    notification.filter_subscriber_list(event, subscribers, False)
    recipients = []

    for lang in subscribers:
        recipients.extend(subscribers[lang])

    attachlink = request.getBaseURL() + getAttachUrl(event.pagename, event.filename, request)
    pagelink = request.getQualifiedURL(page.url(request, {}))

    for lang in subscribers:
        emails = []
        _ = lambda text: request.getText(text, lang=lang)

        links = _("Attachment link: %(attach)s\n" \
                  "Page link: %(page)s\n") % {'attach': attachlink, 'page': pagelink}

        data = notification.attachment_added(request, _, event.pagename, event.filename, event.size)
        data['text'] = data['text'] + links

        emails = [usr.email for usr in subscribers[lang]]

        if send_notification(request, from_address, emails, data):
            names.update(recipients)

    return notification.Success(names)
Exemplo n.º 4
0
def handle_file_attached(event):
    """Handles event sent when a file is attached to a page"""

    names = set()
    request = event.request
    page = Page(request, event.pagename)
    subscribers = page.getSubscribers(request, return_users=1)
    notification.filter_subscriber_list(event, subscribers, True)
    recipients = []

    for lang in subscribers:
        recipients.extend(subscribers[lang])

    attachlink = request.getQualifiedURL(getAttachUrl(event.pagename, event.filename, request))
    pagelink = request.getQualifiedURL(page.url(request, {}))

    for lang in subscribers.keys():
        _ = lambda text: request.getText(text, lang=lang)
        data = notification.attachment_added(request, _, event.pagename, event.filename, event.size)
        links = [{'url': attachlink, 'description': _("Attachment link")},
                  {'url': pagelink, 'description': _("Page link")}]

        jids = [usr.jid for usr in subscribers[lang]]
        data['url_list'] = links
        data['action'] = "file_attached"

        if send_notification(request, jids, data):
            names.update(recipients)

    return notification.Success(names)
Exemplo n.º 5
0
def handle_file_attached(event):
    """Handles event sent when a file is attached to a page"""

    names = set()
    request = event.request
    page = Page(request, event.pagename)
    subscribers = page.getSubscribers(request, return_users=1)
    notification.filter_subscriber_list(event, subscribers, True)
    recipients = []

    for lang in subscribers:
        recipients.extend(subscribers[lang])

    attachlink = request.getQualifiedURL(getAttachUrl(event.pagename, event.filename, request))
    pagelink = request.getQualifiedURL(page.url(request, {}))

    for lang in subscribers.keys():
        _ = lambda text: request.getText(text, lang=lang)
        data = notification.attachment_added(request, _, event.pagename, event.filename, event.size)
        links = [{'url': attachlink, 'description': _("Attachment link")},
                  {'url': pagelink, 'description': _("Page link")}]

        jids = [usr.jid for usr in subscribers[lang]]
        data['url_list'] = links
        data['action'] = "file_attached"

        if send_notification(request, jids, data):
            names.update(recipients)

    return notification.Success(names)
Exemplo n.º 6
0
def render(req, f, content, parent='', depth=0):
    listfmt = {'class': 'attachtree_list'}
    direntryfmt = {'class': 'attachtree_direntry'}
    fileentryfmt = {'class': 'attachtree_fileentry'}

    result = f.bullet_list(1, **listfmt)

    for entry, values in sorted(content.items()):
        fullname = os.path.join(parent, unicode(entry))
        fullname = fullname.replace(os.sep, quote(os.sep, safe=""))
        if not values.items():
            result += f.listitem(1, **fileentryfmt)
            link = getAttachUrl(f.page.page_name,
                                fullname.encode("iso-8859-15"),
                                req)
            result += f.url(1, link, 'attachtree_link')
            result += f.text(unquote(entry))
            result += f.url(0)
            result += f.listitem(0)
        else:
            result += f.listitem(1, **direntryfmt)
            result += f.text(unquote(entry))
            result += f.listitem(0)
            result += render(req, f, values, fullname, depth + 1)

    result += f.bullet_list(0)
    return result
Exemplo n.º 7
0
 def execute(self):
     # TODO: better abstract this using the formatter
     html = []
     if exists(self.request, self.page.page_name, self.attachment):
         html.append('<img class="pagelogo" src="')
         html.append(
             getAttachUrl(self.page.page_name, self.attachment,
                          self.request))
         html.append('" >')
     return self.formatter.rawHTML('\n'.join(html))
Exemplo n.º 8
0
def execute(pagename, request):
    form = request.values
    img_id = form['name'][0:-4]

    imgs = []

    util = NgoWikiUtil(request)
    util.open_database()

    try:
        data = util.select_spec_image_by_id(img_id)
        if data == None:
            imgs.append(form['name'])
        else:
            imgs = json.loads(data['definition'])['images']
    finally:
        util.close_database(True)

    for img_file in imgs:
        request.write('<img class="logo" src="' + getAttachUrl(pagename, img_file, request) + '">' + '<BR><BR>')    
Exemplo n.º 9
0
def handle_file_changed(event):
    """Sends an email to users that have subscribed to this event type"""

    names = set()
    from_address = event.request.cfg.mail_from
    request = event.request
    page = Page(request, event.pagename)

    if isinstance(event, ev.FileAttachedEvent):
        notification_fn = notification.attachment_added
    elif isinstance(event, ev.FileRemovedEvent):
        notification_fn = notification.attachment_removed

    subscribers = page.getSubscribers(request, return_users=1)
    notification.filter_subscriber_list(event, subscribers, False)
    recipients = []

    for lang in subscribers:
        recipients.extend(subscribers[lang])

    attachlink = request.getQualifiedURL(
        getAttachUrl(event.pagename, event.filename, request))
    pagelink = request.getQualifiedURL(page.url(request, {}))

    for lang in subscribers:
        _ = lambda text: request.getText(text, lang=lang)

        links = _("Attachment link: %(attach)s\n" \
                  "Page link: %(page)s\n") % {'attach': attachlink, 'page': pagelink}

        data = notification_fn(request, _, event.pagename, event.filename,
                               event.size)
        data['text'] = data['text'] + links

        emails = [usr.email for usr in subscribers[lang]]

        if send_notification(request, from_address, emails, data):
            names.update(recipients)

    return notification.Success(names)
Exemplo n.º 10
0
def execute(pagename, request):
    form = values_to_form(request.values)

    util = form.get('util', [None])[0]

    if util == "format":
        txt = form.get('text', [None])[0]
        request.write(format_wikitext(request, txt))

    elif util == "getTemplate":
        template = form.get('name', [None])[0]
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            Page(request, template_page).send_raw()

    elif util == "newPage":
        page = form.get('page', [None])[0]
        content = form.get('content', [""])[0]
        request.content_type = "application/json"

        if request.environ['REQUEST_METHOD'] != 'POST':
            return

        if not page:
            msg = "Page name not defined!"
            json.dump(dict(status="error", msg=msg), request)
            return

        if not request.user.may.write(page):
            msg = "You are not allowed to edit this page"
            json.dump(dict(status="error", msg=msg), request)
            return

        p = Page(request, page)
        if p.exists():
            msg = "Page already exists"
            json.dump(dict(status="error", msg=msg), request)
            return

        editor = PageEditor(request, page)
        msg = editor.saveText(content, p.get_real_rev())
        json.dump(dict(status="ok", msg=msg), request)

    elif util == "getProperties":
        request.content_type = "application/json"
        key = form.get('key', [''])[0]
        json.dump(get_properties(request, key), request)
        return

    elif util == "uploadFile":
        request.content_type = "application/json"

        if not request.user.may.write(pagename):
            msg = u"You are not allowed to edit this page!"
            json.dump(dict(status="error", msg=msg), request)
            request.status_code = 403
            return

        from MoinMoin.action.AttachFile import add_attachment, AttachmentAlreadyExists

        try:
            overwrite = int(form.get('overwrite', ['0'])[0])
        except:
            overwrite = 0

        response = dict(success=list(), failed=list())
        for name in request.files:
            _file = request.files.get(name)
            filename = _file.filename
            try:
                t, s = add_attachment(request,
                                      pagename,
                                      filename,
                                      _file.stream,
                                      overwrite=overwrite)
                response['success'].append(filename)
            except AttachmentAlreadyExists:
                response['failed'].append(filename)

        json.dump(response, request)
        return

    elif util == "getAttachments":
        request.content_type = "application/json"
        from MoinMoin.action.AttachFile import _get_files, getAttachUrl

        files = _get_files(request, pagename)
        response = []
        for name in files:
            response.append(
                dict(url=getAttachUrl(pagename, name, request), name=name))

        json.dump(response, request)

    return
Exemplo n.º 11
0
    def pageListWithContext(self, request, formatter, info=1, context=180,
                            maxlines=1, paging=True, hitsFrom=0, hitsInfo=0,
                            highlight_titles=True, highlight_pages=True):
        """ Format a list of found pages with context

        @param request: current request
        @param formatter: formatter to use
        @param info: show match info near the page link
        @param context: how many characters to show around each match.
        @param maxlines: how many contexts lines to show.
        @param paging: toggle paging
        @param hitsFrom: current position in the hits
        @param hitsInfo: toggle hits info line
        @param highlight_titles: perform highlighting in page list
        @param highlight_pages: add highlight parameter to page URLs
        @rtype: unicode
        @return formatted page list with context
        """
        ngowikiutil = NgoWikiUtil(request)
        ngowikiutil.open_database()

        self._reset(request, formatter)
        f = formatter
        write = self.buffer.write
        _ = request.getText

        if paging and len(self.hits) <= request.cfg.search_results_per_page:
            paging = False

        # Add pages formatted as definition list
        hitsTo = hitsFrom + request.cfg.search_results_per_page + 1
        hitDiff = 0
        if self.hits:
            write(f.definition_list(1))

            displayHits = []
            hitIdx = 0
            for hit in self.hits:
                result = ngowikiutil.select_page_by_path(hit.page_name)
                if result == None:
                    hitDiff = hitDiff + 1
                    continue
                if len(ngowikiutil.select_page_tags_by_id(result["id"])) == 0:
                    hitDiff = hitDiff + 1
                    continue
                hitIdx = hitIdx + 1
                if paging:
                    if hitsTo <= hitIdx - 1:
                        break
                    if hitsFrom <= hitIdx - 1:
                        displayHits.append(hit)
                else:
                    displayHits.append(hit)
            if len(displayHits) <= request.cfg.search_results_per_page and hitsFrom == 0:
                paging = False
            if len(displayHits) > request.cfg.search_results_per_page:
                displayHits = displayHits[0:request.cfg.search_results_per_page]

            if len(displayHits) == 0:
                write(u'没有找到相关内容,请调整搜索条件重新搜索')

            template = '''
                <table class="listitem_with_logosummary">
                    <tr>
                        <!--
                        <td class="logo">
                            %(logo)s
                        </td>
                        -->
                        <td>
                           <div class="title">
                              <a href="%(link)s">%(title)s</a>
                           </div>
                           <div class="meta">
                               <span>%(lastmodified)s</span>
                               <span>%(tags)s</span>
                               <span><span class="metaitem">%(likecount)s<span></span>
                               <span><span class="metaitem">%(commentcount)s<span></span>
                               <span><span class="metaitem">%(hitcount)s<span></span>
                           </div>
                           <div class="summary">%(summary)s</div>
                        </td>
                     </tr>
                 </table>
                '''
            for page in displayHits:
                result = ngowikiutil.select_page_by_path(page.page_name)
                if result != None:
                    if len(ngowikiutil.select_page_tags_by_id(result["id"])) > 0:
                        page = Page(request, result["path"]) 
                        logo = '<div class="logo defaultLogo">&nbsp;</div>'
                        if len(result["logo"]) > 0 and exists(request, result["path"], result["logo"]):
                            logo = '<img class="logo" src="' + getAttachUrl(result["path"], result["logo"], request) + '">'
                        link = page.url(request)
                        title = result["title"]
                        lastmodified = page.mtime_printable(request)
                        summary = result["summary"].replace(u"'''", "").replace(u"【请在此插入图片】", "").replace(u"【请在此插入图片,最多可插入9张】", "")

                        tags = (", ".join(
                                  map(lambda x: '<a href=\'javascript:add_filter_by_tag(' + json.dumps(x["tag"]) + ')\' >' + x["tag"] + '</a>', 
                                      filter(lambda x: x["type"] == 1, ngowikiutil.select_page_tags_by_id(result["id"]))
                                  )))

                        if len(tags) > 0:
                            tags = '<span class="metaitem">' + tags + '</span>'

                        write(template % {"logo":logo, "title": title, "link": link, "lastmodified": lastmodified, "tags": tags, "summary": summary, "likecount": u'\u559c\u6b22\uff1a' + str(result["likecount"]), "commentcount": u'\u8bc4\u8bba\u6570\uff1a' + str(result["commentcount"]), "hitcount": u'\u8bbf\u95ee\u91cf\uff1a' + str(result["hitcount"])})
            write(f.definition_list(0))
            if paging:
                write(self.formatPageLinks(hitsFrom=hitsFrom,
                    hitsPerPage=request.cfg.search_results_per_page,
                    hitsNum=len(self.hits) - hitDiff))

        return self.getvalue()
Exemplo n.º 12
0
    def execute(self):
        ngowikiutil = NgoWikiUtil(self.request)
        ngowikiutil.open_database()
        try:
            offset = 0
            length = 10
            sortby = "lastmodified"
            order = "DESC"
            filterByTags = self.filterByTags
            favorite = None

            form = self.request.values
            if 'from' in form:
                offset = int(form['from'])
            if 'length' in form:
                length = int(form['length'])
            if 'sortby' in form:
                sortby = form['sortby']
                if sortby == 'title':
                    order = "ASC"
            if 'order' in form:
                order = form['order']
            if 'favorite' in form and form[
                    'favorite'] != "false" and self.user != None and self.user.valid:
                favorite = self.user.id
            if 'filterByTags' in form:
                filterByTags = form['filterByTags'].split(",")

            for tag in filterByTags:
                ngowikiutil.update_tag_hitcount(tag)

            results = ngowikiutil.select_pages_by_tag(filterByTags, favorite,
                                                      sortby, order, offset,
                                                      length)
            total = ngowikiutil.count_pages_by_tag(filterByTags, favorite)

            buffer = []
            buffer.append(
                '''
                <script language="javascript">window.__ListPagesByTag_filterByTag = %(filterByTags)s;window.__ListPagesByTag_filterByTag_default = %(filterByTagsDefault)s;</script>
                <div id="listpagesbytag_sorter"></div>
				<div id="listpagesbytag_favorite"></div>
                <div id="listpagesbytag_filter"></div>
            ''' % {
                    "filterByTagsDefault": json.dumps(self.filterByTags),
                    "filterByTags": json.dumps(",".join(filterByTags))
                })

            template = '''
                <table class="listitem_with_logosummary">
                    <tr>
                        <!--
                        <td class="logo">
                            %(logo)s
                        </td>
                        -->
                        <td>
                           <div class="title">
                              <a href="%(link)s">%(title)s</a>
                           </div>
                           <div class="meta">
                               <span>%(lastmodified)s</span>
                               <span>%(tags)s</span>
                               <span><span class="metaitem">%(likecount)s<span></span>
                               <span><span class="metaitem">%(commentcount)s<span></span>
                               <span><span class="metaitem">%(hitcount)s<span></span>
                           </div>
                           <div class="summary">%(summary)s</div>
                        </td>
                     </tr>
                 </table>
                '''
            for result in results:
                page = Page(self.request, result["path"])
                logo = '<div class="logo defaultLogo">&nbsp;</div>'
                if len(result["logo"]) > 0 and exists(
                        self.request, result["path"], result["logo"]):
                    logo = '<img class="logo" src="' + getAttachUrl(
                        result["path"], result["logo"], self.request) + '">'
                link = page.url(self.request)
                title = result["title"]
                lastmodified = page.mtime_printable(self.request)
                summary = result["summary"].replace("'''", "").replace(
                    u"【请在此插入图片】", "").replace(u"【请在此插入图片,最多可插入9张】", "")

                tags = (", ".join(
                    map(
                        lambda x: '<a href=\'javascript:add_filter_by_tag(' +
                        json.dumps(x["tag"]) + ')\' >' + x["tag"] + '</a>',
                        filter(
                            lambda x: x["type"] == 1 or x["type"] == 2,
                            ngowikiutil.select_page_tags_by_id(
                                result["id"])))))

                if len(tags) > 0:
                    tags = '<span class="metaitem">' + tags + '</span>'

                buffer.append(
                    template % {
                        "logo":
                        logo,
                        "title":
                        title,
                        "link":
                        link,
                        "lastmodified":
                        lastmodified,
                        "tags":
                        tags,
                        "summary":
                        summary,
                        "likecount":
                        u'\u559c\u6b22\uff1a' + str(result["likecount"]),
                        "commentcount":
                        u'\u8bc4\u8bba\u6570\uff1a' +
                        str(result["commentcount"]),
                        "hitcount":
                        u'\u8bbf\u95ee\u91cf\uff1a' + str(result["hitcount"])
                    })

            buffer.append("<script language='javascript'>render_pagingbar(" +
                          str(total) + ', ' + str(length) + ');</script>')
            ret = ''.join(buffer)
            return ret
        finally:
            ngowikiutil.close_database(True)
Exemplo n.º 13
0
    def execute(self):

        if FrontpageMacro.lastupdated == None or long(time.time()) - FrontpageMacro.lastupdated > 3600L:
            ngowikiutil = NgoWikiUtil(self.request)
            try:
                ngowikiutil.open_database()
                FrontpageMacro.totalcount_activities = ngowikiutil.count_pages_by_tag([u'服务产品类']) + ngowikiutil.count_pages_by_tag([u'视听产品类']) + ngowikiutil.count_pages_by_tag([u'实体产品类'])
                FrontpageMacro.totalcount_ngos = ngowikiutil.count_pages_by_tag([u'公益机构类'])
                FrontpageMacro.totalcount_enterprises = ngowikiutil.count_pages_by_tag([u'企业志愿组织类'])
                FrontpageMacro.featured_activities = ngowikiutil.select_pages_with_one_of_tags([u'服务产品类', u'视听产品类', u'实体产品类'], 'featured', 'DESC', 0, 20)
                for record in FrontpageMacro.featured_activities[0:2]:
                    record["summary"] = record["summary"].replace("'''", "")
                    record["summary"] = filter_summary(record["summary"], 50);
                    pagename = record["path"]
                    page = Page(self.request, pagename)
                    record["link"] = page.url(self.request)
                    if len(record["logo"]) > 0 and exists(self.request, record["path"], record["logo"]):
                        record["logo_link"] = getAttachUrl(record["path"], record["logo"], self.request)
                    else:
                        findLogo = False
                        text = page.getPageText()
                        match = re.search('\\{\\{attachment:([^\\|]+)\\|\\|.*}}', text)
                        if match != None:
                            logo = match.group(1)
                            if exists(self.request, record["path"], logo):
                                record["logo_link"] = getAttachUrl(record["path"], logo, self.request)
                                findLogo = True
                        if not findLogo:
                            record["logo_link"] = self.request.cfg.url_prefix_static + "/ngowiki/img/no-logo.png"
                FrontpageMacro.featured_ngos = ngowikiutil.select_pages_by_tag([u'公益机构类'], 'featured', 'DESC', 0, 2)
                for record in FrontpageMacro.featured_ngos:
                    pagename = record["path"]
                    record["summary"] = filter_summary(record["summary"], 50)
                    page = Page(self.request, pagename)
                    record["link"] = page.url(self.request)
                    if len(record["logo"]) > 0 and exists(self.request, record["path"], record["logo"]):
                        record["logo_link"] = getAttachUrl(record["path"], record["logo"], self.request)
                    else:
                        record["logo_link"] = self.request.cfg.url_prefix_static + "/ngowiki/img/no-logo.png"
                FrontpageMacro.recently_added = ngowikiutil.select_latest_created_pages([u'服务产品类', u'视听产品类', u'实体产品类', u'公益机构类', u'企业志愿组织类'], 0, 5)
                for record in FrontpageMacro.recently_added:
                    pagename = record["path"]
                    page = Page(self.request, pagename)
                    record["link"] = page.url(self.request)
                    if len(record["logo"]) > 0 and exists(self.request, record["path"], record["logo"]):
                        record["logo_link"] = getAttachUrl(record["path"], record["logo"], self.request)
                    else:
                        record["logo_link"] = self.request.cfg.url_prefix_static + "/ngowiki/img/no-logo.png"
                    if u'服务产品类' in ngowikiutil.parse_page(page)["categories"] or u'视听产品类' in ngowikiutil.parse_page(page)["categories"] or u'实体产品类' in ngowikiutil.parse_page(page)["categories"]:
                        record["recently_added_type"] = "activity"
                    elif u'公益机构类' in ngowikiutil.parse_page(page)["categories"]:
                        record["recently_added_type"] = "ngo"
                    else:
                        record["recently_added_type"] = "enterprise"
                FrontpageMacro.news_items = ngowikiutil.select_pages_by_tag([u'新闻动态类'], 'featured', 'DESC', 0, 100)
                for record in FrontpageMacro.news_items:
                    pagename = record["path"]
                    page = Page(self.request, pagename)
                    record["link"] = page.url(self.request)
                    if len(record["logo"]) > 0 and exists(self.request, record["path"], record["logo"]):
                        record["logo_link"] = getAttachUrl(record["path"], record["logo"], self.request)
                    else:
                        record["logo_link"] = self.request.cfg.url_prefix_static + "/ngowiki/img/no-logo.png"
            finally:
                ngowikiutil.close_database(True)
            FrontpageMacro.lastupdated = long(time.time())

        context = {
            'totalcount_activities': FrontpageMacro.totalcount_activities,
            'totalcount_ngos': FrontpageMacro.totalcount_ngos,
            'totalcount_enterprises': FrontpageMacro.totalcount_enterprises,
            'featured_activities': FrontpageMacro.featured_activities,
            'featured_ngos': FrontpageMacro.featured_ngos,
            'recently_added': FrontpageMacro.recently_added,
            'news_items': FrontpageMacro.news_items,
            'logo_url': self.request.cfg.url_prefix_static + "/ngowiki/img/sitelogo.png",
            'slogan_url': self.request.cfg.url_prefix_static + "/ngowiki/img/slogan2.png"
        }

        engine = tenjin.Engine(path=[os.path.dirname(__file__) + '/views'])
        html = engine.render('Frontpage.pyhtml', context)

        return self.formatter.rawHTML(html)
Exemplo n.º 14
0
def execute(pagename, request):
    form = values_to_form(request.values)

    util = form.get('util', [None])[0]

    if util == "format":
        txt = form.get('text', [None])[0]
        request.write(format_wikitext(request, txt))

    elif util == "getTemplate":
        template = form.get('name', [None])[0]
        template_page = wikiutil.unquoteWikiname(template)
        if request.user.may.read(template_page):
            Page(request, template_page).send_raw()

    elif util == "newPage":
        page = form.get('page', [None])[0]
        content = form.get('content', [""])[0]
        request.content_type = "application/json"

        if request.environ['REQUEST_METHOD'] != 'POST':
            return

        if not page:
            msg = "Page name not defined!"
            json.dump(dict(status="error", msg=msg), request)
            return

        if not request.user.may.write(page):
            msg = "You are not allowed to edit this page"
            json.dump(dict(status="error", msg=msg), request)
            return

        p = Page(request, page)
        if p.exists():
            msg = "Page already exists"
            json.dump(dict(status="error", msg=msg), request)
            return

        editor = PageEditor(request, page)
        msg = editor.saveText(content, p.get_real_rev())
        json.dump(dict(status="ok", msg=msg), request)


    elif util == "getProperties":
        request.content_type = "application/json"
        key = form.get('key', [''])[0]
        json.dump(get_properties(request, key), request)
        return

    elif util == "uploadFile":
        request.content_type = "application/json"

        if not request.user.may.write(pagename):
            msg = u"You are not allowed to edit this page!"
            json.dump(dict(status="error", msg=msg), request)
            request.status_code = 403
            return

        from MoinMoin.action.AttachFile import add_attachment, AttachmentAlreadyExists

        try:
            overwrite = int(form.get('overwrite', ['0'])[0])
        except:
            overwrite = 0

        response = dict(success=list(), failed=list())
        for name in request.files:
            _file = request.files.get(name)
            filename = _file.filename
            try:
                t,s = add_attachment(request, pagename, filename, _file.stream, overwrite=overwrite)
                response['success'].append(filename)
            except AttachmentAlreadyExists:
                response['failed'].append(filename)

        json.dump(response, request)
        return

    elif util == "getAttachments":
        request.content_type = "application/json"
        from MoinMoin.action.AttachFile import _get_files, getAttachUrl

        files = _get_files(request, pagename)
        response = []
        for name in files:
            response.append(dict(url=getAttachUrl(pagename, name, request),name=name))

        json.dump(response, request)

    return