Example #1
0
def mkContentNode(req):
    access = AccessData(req)
    id = req.params.get("id", tree.getRoot("collections").id)
    try:
        node = tree.getNode(id)
    except tree.NoSuchNodeError:
        return ContentError("No such node", 404)
    if not access.hasReadAccess(node):
        return ContentError("Permission denied", 403)

    if node.type in ["directory", "collection"]:
        if "files" not in req.params and len(filter(None, node.getStartpageDict().values())) > 0:
            for f in node.getFiles():
                if f.type == "content" and f.mimetype == "text/html" and os.path.isfile(
                        f.retrieveFile()) and fileIsNotEmpty(f.retrieveFile()):
                    return ContentNode(node)

        ids = access.filter(list(set(tree.getAllContainerChildrenAbs(node, []))))
        node.ccount = len(ids)
        #ids = access.filter(node.getAllChildren())
        c = ContentList(tree.NodeList(ids), getCollection(node))
        c.feedback(req)
        c.node = node
        return c
    else:
        return ContentNode(node)
Example #2
0
    def __get_child_nodes(self, fetch_function):
        acl = AccessData(self.request)

        node_ids = acl.filter(fetch_function())
        nodes = tree.NodeList(node_ids)

        return [Node(self.request, self.collection_content, n) for n in nodes]
Example #3
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    access = AccessData(req)
    node = tree.getNode(ids[0])

    if "sortfiles" in users.getHideMenusForUser(user) or not access.hasWriteAccess(node):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    c = getCollection(node)

    if "globalsort" in req.params:
        c.set("sortfield", req.params["globalsort"])
    collection_sortfield = c.get("sortfield")

    class SortChoice:

        def __init__(self, label, value):
            self.label = label
            self.value = value

    sortfields = [SortChoice(t(req, "off"), "")]
    for ntype, num in c.getAllOccurences(AccessData(req)).items():
        if ntype.getSortFields():
            for sortfield in ntype.getSortFields():
                sortfields += [SortChoice(sortfield.getLabel(), sortfield.getName())]
                sortfields += [SortChoice(sortfield.getLabel() + t(req, "descending"), "-" + sortfield.getName())]
            break

    return req.getTAL("web/edit/modules/sortfiles.html", {"node": node, "collection_sortfield": collection_sortfield,
                                                          "sortchoices": sortfields, "name": c.getName()}, macro="edit_sortfiles")
Example #4
0
def mkContentNode(req):
    access = AccessData(req)
    id = req.params.get("id", tree.getRoot("collections").id)
    try:
        node = tree.getNode(id)
    except tree.NoSuchNodeError:
        return ContentError("No such node", 404)
    if not access.hasReadAccess(node):
        return ContentError("Permission denied", 403)

    if node.type in ["directory", "collection"]:
        if "files" not in req.params and len(
                filter(None,
                       node.getStartpageDict().values())) > 0:
            for f in node.getFiles():
                if f.type == "content" and f.mimetype == "text/html" and os.path.isfile(
                        f.retrieveFile()) and fileIsNotEmpty(f.retrieveFile()):
                    return ContentNode(node)

        ids = access.filter(
            list(set(tree.getAllContainerChildrenAbs(node, []))))
        node.ccount = len(ids)
        #ids = access.filter(node.getAllChildren())
        c = ContentList(tree.NodeList(ids), getCollection(node))
        c.feedback(req)
        c.node = node
        return c
    else:
        return ContentNode(node)
Example #5
0
def export(req):
    p = req.path[1:].split("/")
    access = AccessData(req)

    if len(p) != 2:
        req.error(404, "Object not found")
        return

    if p[0].isdigit():
        try:
            node = tree.getNode(p[0])
        except:
            return req.error(404, "Object not found")
    else:
        return req.error(404, "Object not found")

    if not access.hasAccess(node, "read"):
        req.write(t(req, "permission_denied"))
        return

    mask = getMetaType(node.getSchema()).getMask(p[1])
    if mask:
        try:
            req.reply_headers['Content-Type'] = "text/plain; charset=utf-8"
            req.write(mask.getViewHTML([node],
                                       flags=8))  # flags =8 -> export type
        except tree.NoSuchNodeError:
            return req.error(404, "Object not found")
    else:
        req.error(404, "Object not found")
        return
Example #6
0
    def popup_thumbbig(self, req):
        access = AccessData(req)

        if (not access.hasAccess(self, "data")
                and not dozoom(self)) or not access.hasAccess(self, "read"):
            req.write(t(req, "permission_denied"))
            return

        thumbbig = None
        for file in self.getFiles():
            if file.getType() == "thumb2":
                thumbbig = file
                break
        if not thumbbig:
            self.popup_fullsize(req)
        else:
            im = PILImage.open(thumbbig.retrieveFile())
            req.writeTAL(
                "contenttypes/image.html", {
                    "filename":
                    '/file/' + str(self.id) + '/' + thumbbig.getName(),
                    "width": im.size[0],
                    "height": im.size[1]
                },
                macro="thumbbig")
Example #7
0
def send_nodefile_tal(req):
    if "file" in req.params:
        return upload_for_html(req)

    id = req.params.get("id")
    node = tree.getNode(id)
    access = AccessData(req)

    if not (access.hasAccess(node, 'read') and access.hasAccess(node, 'write') and access.hasAccess(node, 'data') and node.type in ["directory", "collections", "collection"]):
        return ""

    def fit(imagefile, cn):
        # fits the image into a box with dimensions cn, returning new width and
        # height
        try:
            sz = PIL.Image.open(imagefile).size
            (x, y) = (sz[0], sz[1])
            if x > cn[0]:
                y = (y * cn[0]) / x
                x = (x * cn[0]) / x
            if y > cn[1]:
                x = (x * cn[1]) / y
                y = (y * cn[1]) / y
            return (x, y)
        except:
            return cn

    # only pass images to the file browser
    files = [f for f in node.getFiles() if f.mimetype.startswith("image")]

    # this flag may switch the display of a "delete" button in the customs
    # file browser in web/edit/modules/startpages.html
    showdelbutton = True
    return req.getTAL("web/edit/modules/startpages.html", {"id": id, "node": node, "files": files, "fit": fit, "logoname": node.get("system.logo"), "delbutton": True}, macro="fckeditor_customs_filemanager")
Example #8
0
def export(req):
    p = req.path[1:].split("/")
    access = AccessData(req)

    if len(p) != 2:
        req.error(404, "Object not found")
        return

    if p[0].isdigit():
        try:
            node = tree.getNode(p[0])
        except:
            return req.error(404, "Object not found")
    else:
        return req.error(404, "Object not found")

    if not access.hasAccess(node, "read"):
        req.write(t(req, "permission_denied"))
        return

    mask = getMetaType(node.getSchema()).getMask(p[1])
    if mask:
        try:
            req.reply_headers['Content-Type'] = "text/plain; charset=utf-8"
            req.write(mask.getViewHTML([node], flags=8))  # flags =8 -> export type
        except tree.NoSuchNodeError:
            return req.error(404, "Object not found")
    else:
        req.error(404, "Object not found")
        return
Example #9
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    access = AccessData(req)
    language = lang(req)
    node = tree.getNode(ids[0])
    
    if "sort" in users.getHideMenusForUser(user) or not access.hasWriteAccess(node):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    msg_t = (user.getName(), node.id, node.name, node.type, req.params)
    msg = "%s sorting subfolders of node %r (%r, %r): %r" % msg_t
    logger.info(msg)

    if "order" in req.params:  # do reorder
        ids = req.params.get('order').split(',')
        children = []
        for n in ids:
            child = tree.getNode(n)
            child.setOrderPos(ids.index(n))
            children.append(child)

        req.writeTAL('web/edit/modules/subfolder.html', {'nodelist': children, "language": language}, macro="ordered_list")
        return ""

    elif "sortdirection" in req.params:  # do automatic re-order
        i = 0
        sort_dir = "" if req.params.get("sortdirection", "up") == "up" else "-"
        sorted_children = node.getContainerChildren().sort_by_fields(sort_dir + req.params.get("sortattribute"))
        for child in sorted_children:
            child.setOrderPos(i)
            i += 1
        req.writeTAL('web/edit/modules/subfolder.html', {'nodelist': sorted_children, "language": language}, macro="ordered_list")
        return ""

    nodelist = []
    attributes = []
    fields = {}
    i = 0
    for child in list(node.getContainerChildren().sort_by_orderpos()):
        i += 1  # count container children
        nodelist.append(child)
        if getMetaType(child.getSchema()):
            for field in getMetaType(child.getSchema()).getMetaFields():
                if not field in fields.keys():
                    fields[field] = 0
                fields[field] += 1

    for field in fields:
        if i == fields[field]:
            attributes.append(field)
    ctx = {
            "node": node,
            "nodelist": nodelist,
            "sortattributes": sorted(attributes, lambda x, y: cmp(x.getLabel().lower(), y.getLabel().lower())),
            "language": language,
           }
    return req.getTAL("web/edit/modules/subfolder.html", ctx, macro="edit_subfolder")
Example #10
0
def simple_search(req):
    from web.frontend.content import ContentList
    res = []
    words = []
    collections = []
    collection_ids = {}

    access = AccessData(req)
    q = u(req.params.get("query", ""))

    # test whether this query is restricted to a number of collections
    for key, value in req.params.items():
        if key.startswith("c_"):
            collection_ids[key[2:]] = 1
    # no collection means: all collections
    if len(collection_ids) == 0 or 1 in collection_ids.keys():
        for collection in access.filter(tree.getRoot("collections").getChildren()):
            collection_ids[collection.id] = 1

    # now retrieve all results in all collections
    for collection in getAllCollections():
        if collection.id in collection_ids:
            collections.append(collection)

    num = 0
    logging.getLogger('usertracing').info(access.user.name + " search for '" + q + "', " + str(num) + " results")
    try:
        if req.params.get("act_node", None) and tree.getNode(req.params.get("act_node")).getContentType() != "collections":
            # actual node is a collection or directory
            result = tree.getNode(req.params.get("act_node")).search('full=' + q)
            result = access.filter(result)
            num += len(result)
            if len(result) > 0:
                cl = ContentList(result, collection, words)
                cl.feedback(req)
                cl.linkname = "Suchergebnis"
                cl.linktarget = ""
                res.append(cl)
        else:
            # actual node is collections-node
            for collection in collections:
                result = collection.search('full=' + q)
                result = access.filter(result)
                num += len(result)

                if len(result) > 0:
                    cl = ContentList(result, collection, words)
                    cl.feedback(req)
                    cl.linkname = "Suchergebnis"
                    cl.linktarget = ""
                    res.append(cl)

        if len(res) == 1:
            return res[0]
        else:
            return SearchResult(res, q, collections)
    except:
        return SearchResult(None, q, collections)
Example #11
0
    def _get_child_collections(self):
        acl = AccessData(self.request)
        active_collection = self.active_collection

        nodes = tree.getChildNodesByFieldValue(active_collection.node.id, **{"repec.code": '__is_set__'})
        if len(nodes) == 0:
            log.info("Collection with code %s does not have child collections" % active_collection['repec.code'])

        return [Node(self.request, self, node) for node in nodes if acl.hasReadAccess(node)]
Example #12
0
def send_file(req, download=0):
    access = AccessData(req)
    id, filename = splitpath(req.path)
    if id.endswith("_transfer.zip"):
        id = id[:-13]

    try:
        n = tree.getNode(id)
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(n, "data") and n.type not in ["directory", "collections", "collection"]:
        return 403
    file = None

    if filename is None and n:
        # build zip-file and return it
        zipfilepath, files_written = build_transferzip(n)
        if files_written == 0:
            return 404
        send_result = req.sendFile(zipfilepath, "application/zip")
        if os.sep == '/':  # Unix?
            os.unlink(zipfilepath)  # unlinking files while still reading them only works on Unix/Linux
        return send_result

    # try full filename
    for f in n.getFiles():
        if f.getName() == filename:
            incUsage(n)
            file = f
            break

    # try only extension
    if not file and n.get("archive_type") == "":
        file_ext = os.path.splitext(filename)[1]
        for f in n.getFiles():
            if os.path.splitext(f.getName())[1] == file_ext and f.getType() in ['doc', 'document', 'original', 'mp3']:
                incUsage(n)
                file = f
                break

    if existMetaField(n.getSchema(), 'nodename'):
        display_file_name = '{}.{}'.format(os.path.splitext(os.path.basename(n.name))[0], os.path.splitext(filename)[-1].strip('.'))
    else:
        display_file_name = filename

    # try file from archivemanager
    if not file and n.get("archive_type") != "":
        am = archivemanager.getManager(n.get("archive_type"))
        req.reply_headers["Content-Disposition"] = 'attachment; filename="{}"'.format(display_file_name)
        return req.sendFile(am.getArchivedFileStream(n.get("archive_path")), "application/x-download")

    if not file:
        return 404

    req.reply_headers["Content-Disposition"] = 'attachment; filename="{}"'.format(display_file_name)

    return req.sendFile(file.retrieveFile(), f.getMimeType())
Example #13
0
def objlist(req):
    node = tree.getNode(req.params["id"])
    access = AccessData(req)
    
    if node.id==tree.getRoot().id or not access.hasWriteAccess(node):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    return req.getTAL("web/edit/modules/license.html", {"node":node}, macro="edit_license")
Example #14
0
def getPrintChildren(req, node, ret):
    access = AccessData(req)

    for c in node.getChildren():
        if access.hasAccess(c, "read"):
            ret.append(c)

        getPrintChildren(req, c, ret)

    return ret
Example #15
0
def getPrintChildren(req, node, ret):
    access = AccessData(req)

    for c in node.getChildren():
        if access.hasAccess(c, "read"):
            ret.append(c)

        getPrintChildren(req, c, ret)

    return ret
Example #16
0
    def popup_fullsize(self, req):
        access = AccessData(req)
        if not access.hasAccess(self, "data") or not access.hasAccess(self, "read"):
            req.write(t(req, "permission_denied"))
            return

        for f in self.getFiles():
            if f.getType() == "doc" or f.getType() == "document":
                req.sendFile(f.retrieveFile(), f.getMimeType())
                return
Example #17
0
def update_node(req, path, params, data, id):

    # get the user and verify the signature
    if params.get('user'):
        user = users.getUser(params.get('user'))
        userAccess = AccessData(user=user)

        if userAccess.user:
            valid = userAccess.verify_request_signature(req.fullpath, params)
            if not valid:
                userAccess = None
        else:
            userAccess = None
    else:
        user = users.getUser('Gast')
        userAccess = AccessData(user=user)

    node = tree.getNode(id)

    # check user access
    if userAccess and userAccess.hasAccess(node, "write"):
        pass
    else:
        s = "No Access"
        req.write(s)
        d = {
            'status': 'fail',
            'html_response_code': '403',
            'errormessage': 'no access'}
        return d['html_response_code'], len(s), d

    node.name = params.get('name')
    metadata = json.loads(params.get('metadata'))

    # set provided metadata
    for key, value in metadata.iteritems():
        node.set(u(key), u(value))

    # service flags
    node.set("updateuser", user.getName())
    node.set("updatetime", format_date())
    node.setDirty()

    d = {
        'status': 'OK',
        'html_response_code': '200',
        'build_response_end': time.time()}
    s = "OK"

    # we need to write in case of POST request, send as buffer wil not work
    req.write(s)

    req.reply_headers['updatetime'] = node.get('updatetime')

    return d['html_response_code'], len(s), d
Example #18
0
def show_attachmentbrowser(req):
    id = req.params.get("id")
    node = getNode(id)
    access = AccessData(req)
    if not access.hasAccess(node, "data"):
        req.write(t(req, "permission_denied"))
        return
    # if node.getContentType().startswith("document") or node.getContentType().startswith("dissertation"):
    #    node.getAttachmentBrowser(req)
    from core.attachment import getAttachmentBrowser
    getAttachmentBrowser(node, req)
Example #19
0
def show_attachmentbrowser(req):
    id = req.params.get("id")
    node = getNode(id)
    access = AccessData(req)
    if not access.hasAccess(node, "data"):
        req.write(t(req, "permission_denied"))
        return
    # if node.getContentType().startswith("document") or node.getContentType().startswith("dissertation"):
    #    node.getAttachmentBrowser(req)
    from core.attachment import getAttachmentBrowser
    getAttachmentBrowser(node, req)
Example #20
0
    def popup_fullsize(self, req):
        access = AccessData(req)
        if not access.hasAccess(self, "data") or not access.hasAccess(
                self, "read"):
            req.write(t(req, "permission_denied"))
            return

        for f in self.getFiles():
            if f.getType() == "doc" or f.getType() == "document":
                req.sendFile(f.retrieveFile(), f.getMimeType())
                return
Example #21
0
    def popup_fullsize(self, req):
        access = AccessData(req)
        if not access.hasAccess(self, "data") or not access.hasAccess(self, "read"):
            req.write(t(req, "permission_denied"))
            return

        f = ""
        for filenode in self.getFiles():
            if filenode.getType() in ("original", "video"):
                f = "/file/" + str(self.id) + "/" + filenode.getName()
                break
        req.writeTAL("contenttypes/flash.html", {"path": f}, macro="fullsize")
Example #22
0
def send_rawimage(req):
    access = AccessData(req)
    try:
        n = tree.getNode(splitpath(req.path)[0])
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(n, "data") and n.type != "directory":
        return 403
    for f in n.getFiles():
        if f.getType() == "original":
            return req.sendFile(f.retrieveFile(), f.getMimeType())
    return 404
Example #23
0
def send_doc(req):
    access = AccessData(req)
    try:
        n = tree.getNode(splitpath(req.path)[0])
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(n, "data") and n.type != "directory":
        return 403
    for f in n.getFiles():
        if f.getType() in ["doc", "document"]:
            incUsage(n)
            return req.sendFile(f.retrieveFile(), f.getMimeType())
    return 404
Example #24
0
def send_rawimage(req):
    access = AccessData(req)
    try:
        n = tree.getNode(splitpath(req.path)[0])
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(n, "data") and n.type != "directory":
        return 403
    for f in n.getFiles():
        if f.getType() == "original":
            incUsage(n)
            return req.sendFile(f.retrieveFile(), f.getMimeType())
    return 404
Example #25
0
def send_attachment(req):
    access = AccessData(req)
    id, filename = splitpath(req.path)
    try:
        node = tree.getNode(id)
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(node, "data") and n.type != "directory":
        return 403
    # filename is attachment.zip
    for file in node.getFiles():
        if file.getType() == "attachment":
            sendZipFile(req, file.retrieveFile())
            break
Example #26
0
def send_attachment(req):
    access = AccessData(req)
    id, filename = splitpath(req.path)
    try:
        node = tree.getNode(id)
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(node, "data") and n.type != "directory":
        return 403
    # filename is attachment.zip
    for file in node.getFiles():
        if file.getType() == "attachment":
            sendZipFile(req, file.retrieveFile())
            break
Example #27
0
    def html(self, req):
        paths = ""
        stylebig = self.getContentStyles()
        liststyle = req.session.get("style-" + self.node.getContentType(), "")

        if not self.node.isContainer():
            plist = getPaths(self.node, AccessData(req))
            paths = tal.getTAL(theme.getTemplate("content_nav.html"),
                               {"paths": plist},
                               macro="paths",
                               language=lang(req))
        # render style of node for nodebig
        if len(stylebig) > 1:
            # more than on style found
            for item in stylebig:
                if liststyle:
                    if item.getName() == liststyle.getName():
                        return getFormatedString(
                            self.node.show_node_big(
                                req, template=item.getTemplate())) + paths
                else:
                    if item.isDefaultStyle():
                        return getFormatedString(
                            self.node.show_node_big(
                                req, template=item.getTemplate())) + paths
        elif len(stylebig) == 1:
            return getFormatedString(
                self.node.show_node_big(
                    req, template=stylebig[0].getTemplate())) + paths
        return getFormatedString(self.node.show_node_big(req)) + paths
Example #28
0
    def getPopup(self, req):
        access = AccessData(req)
        try:
            name = req.params['name']
            fieldname = req.params.get('fieldname', name)
        except:
            logg.exception("missing request parameter")
            return httpstatus.HTTP_NOT_FOUND

        index = tree.getRoot("collections").getAllAttributeValues(
            name, access, req.params.get('schema')).keys()
        index.sort(lambda x, y: cmp(x.lower(), y.lower()))

        if req.params.get("print", "") != "":
            req.reply_headers[
                "Content-Disposition"] = "attachment; filename=index.txt"
            for word in index:
                if word.strip() != "":
                    req.write(word.strip() + "\r\n")
            return

        req.writeTAL("metadata/ilist.html", {
            "index": index,
            "fieldname": fieldname
        },
                     macro="popup")
        return httpstatus.HTTP_OK
Example #29
0
def send_rawfile(req, n=None):
    access = AccessData(req)
    if not n:
        id, filename = splitpath(req.path)
        n = None
        try:
            n = tree.getNode(id)
        except tree.NoSuchNodeError:
            return 404

    if not access.hasAccess(n, "data") and n.getContentType() not in ["directory", "collections", "collection"]:
        return 403
    for f in n.getFiles():
        if f.getType() == "original":
            return req.sendFile(f.retrieveFile(n), f.getMimeType(n))
    return 404
Example #30
0
    def write(self, req, contentHTML, show_navbar=1):
        self.params["show_navbar"] = show_navbar
        self.params["content"] = contentHTML
        self.params["act_node"] = req.params.get("id", req.params.get("dir", ""))
        self.params["acl"] = AccessData(req)

        rootnode = tree.getRoot("collections")
        self.params["header_items"] = rootnode.getCustomItems("header")
        self.params["footer_left_items"] = rootnode.getCustomItems("footer_left")
        self.params["footer_right_items"] = rootnode.getCustomItems("footer_right")
        self.params["t"] = time.strftime("%d.%m.%Y %H:%M:%S")
        self.params["head_meta"] = req.params.get('head_meta', '')

        # header
        self.params["header"] = req.getTAL(theme.getTemplate("frame.html"), self.params, macro="frame_header")

        # footer
        self.params["footer"] = req.getTAL(theme.getTemplate("frame.html"), self.params, macro="frame_footer")

        self.params["tree"] = ""
        self.params["search"] = ""
        if show_navbar == 1:
            # search mask
            self.params["search"] = req.getTAL(
                theme.getTemplate("frame.html"), {
                    "search": self.params["navigation"]["search"], "act_node": self.params["act_node"]}, macro="frame_search")

            # tree
            self.params["tree"] = req.getTAL(
                theme.getTemplate("frame.html"), {
                    "collections": self.collection_portlet.getCollections(), "acl": self.params["acl"]}, macro="frame_tree")

        req.writeTAL(theme.getTemplate("frame.html"), self.params, macro="frame")
Example #31
0
def search_results(req, id):
    access = AccessData(req)
    user = users.getUserFromRequest(req)
    if "search" in users.getHideMenusForUser(user):
        req.writeTAL("web/edit/edit.html", {}, macro="access_error")
        return ""

    if "Reset" in req.params:
        return search_form(req, id, "edit_search_reset_msg")

    try:
        searchvalues = req.session["esearchvals"]
    except:
        req.session["esearchvals"] = searchvalues = {}

    node = tree.getNode(id)
    objtype = req.params["objtype"]
    type = getMetaType(objtype)

    query = ""

    if "full" in req.params:
        value = req.params["full"]
        searchvalues[objtype + ".full"] = value
        for word in value.split(" "):
            if word:
                if query:
                    query += " and "
                query += "full=" + protect(word)

    for field in type.getMetaFields():
        if field.Searchfield():
            name = field.getName()
            if name in req.params and req.params.get(name, "").replace(
                    "'", '').replace('"', '').strip() != "":
                value = req.params[name].strip()

                if value:
                    searchvalues[objtype + "." + field.getName()] = value
                    if field.getFieldtype() == "list" or field.getFieldtype(
                    ) == "ilist" or field.getFieldtype() == "mlist":
                        if query:
                            query += " and "
                        query += name + "=" + protect(value)
                    else:
                        query += name + "=" + protect(value)

    query += ' and schema="' + req.params.get("objtype", "*") + '"'

    utrace.info(access.user.name + " search for " + query)
    nodes = node.search(query)
    req.session["nodelist"] = EditorNodeList(nodes)

    if len(nodes):
        return req.getTAL("web/edit/modules/search.html", {"id": id},
                          macro="start_new_search") + shownodelist(req, nodes)

    return search_form(req, id, "edit_search_noresult_msg")
Example #32
0
    def popup_fullsize(self, req):
        def videowidth():
            return int(self.get('vid-width') or 0) + 64

        def videoheight():
            int(self.get('vid-height') or 0) + 53

        access = AccessData(req)
        if not access.hasAccess(self, "data") or not access.hasAccess(
                self, "read"):
            req.write(t(req, "permission_denied"))
            return

        f = None
        for filenode in self.getFiles():
            if filenode.getType() in [
                    "original", "video"
            ] and filenode.retrieveFile().endswith('flv'):
                f = "/file/%s/%s" % (self.id, filenode.getName())
                break

        script = ""
        if f:
            script = '<p href="%s" style="display:block;width:%spx;height:%spx;" id="player"/p>' % (
                f, videowidth(), videoheight())

        # use jw player
        captions_info = getCaptionInfoDict(self)
        if captions_info:
            logger.info(
                "video: '%s' (%s): captions: dictionary 'captions_info': %s" %
                (self.name, self.id, captions_info))

        context = {
            "file": f,
            "script": script,
            "node": self,
            "width": videowidth(),
            "height": videoheight(),
            "captions_info": json.dumps(captions_info),
        }

        req.writeTAL("contenttypes/video.html",
                     context,
                     macro="fullsize_flv_jwplayer")
Example #33
0
    def popup_thumbbig(self, req):
        access = AccessData(req)

        if (not access.hasAccess(self, "data") and not dozoom(self)) or not access.hasAccess(self, "read"):
            req.write(t(req, "permission_denied"))
            return

        thumbbig = None
        for file in self.getFiles():
            if file.getType() == "thumb2":
                thumbbig = file
                break
        if not thumbbig:
            self.popup_fullsize(req)
        else:
            im = PILImage.open(thumbbig.retrieveFile())
            req.writeTAL("contenttypes/image.html", {"filename": '/file/' + str(self.id) + '/' +
                                                     thumbbig.getName(), "width": im.size[0], "height": im.size[1]}, macro="thumbbig")
Example #34
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    access = AccessData(user=user)
    language = lang(req)
    node = tree.getNode(ids[0])

    if not access.hasWriteAccess(node):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    if req.params.get("upload")=="uploadfile":
        # try to import file
        return import_new(req)


    v = {"error":req.params.get("error")}

    class SortChoice:
        def __init__(self, label, value):
            self.label = label
            self.value = value

    col = node
    if "globalsort" in req.params:
        col.set("sortfield", req.params.get("globalsort"))
    v['collection_sortfield'] = col.get("sortfield")
    sortfields = [SortChoice(t(req,"off"),"")]
    if col.type not in ["root", "collections", "home"]:
        for ntype, num in col.getAllOccurences(acl.AccessData(req)).items():
            if ntype.getSortFields():
                for sortfield in ntype.getSortFields():
                    sortfields += [SortChoice(sortfield.getLabel(), sortfield.getName())]
                    sortfields += [SortChoice(sortfield.getLabel()+t(req,"descending"), "-"+sortfield.getName())]
                break
    v['sortchoices'] = sortfields
    v['ids'] = ids
    v['count'] = len(node.getContentChildren())
    v['nodelist'] = showdir(req, node)
    v['language'] = lang(req)
    v['t'] = t

    _html = req.getTAL("web/edit/modules/imports.html", v, macro="upload_form")

    return _html
Example #35
0
def send_nodefile_tal(req):
    if "file" in req.params:
        return upload_for_html(req)

    id = req.params.get("id")
    node = tree.getNode(id)
    access = AccessData(req)

    if not (access.hasAccess(node, 'read') and access.hasAccess(node, 'write')
            and access.hasAccess(node, 'data')
            and node.type in ["directory", "collections", "collection"]):
        return ""

    def fit(imagefile, cn):
        # fits the image into a box with dimensions cn, returning new width and
        # height
        try:
            sz = PIL.Image.open(imagefile).size
            (x, y) = (sz[0], sz[1])
            if x > cn[0]:
                y = (y * cn[0]) / x
                x = (x * cn[0]) / x
            if y > cn[1]:
                x = (x * cn[1]) / y
                y = (y * cn[1]) / y
            return (x, y)
        except:
            return cn

    # only pass images to the file browser
    files = [f for f in node.getFiles() if f.mimetype.startswith("image")]

    # this flag may switch the display of a "delete" button in the customs
    # file browser in web/edit/modules/startpages.html
    showdelbutton = True
    return req.getTAL("web/edit/modules/startpages.html", {
        "id": id,
        "node": node,
        "files": files,
        "fit": fit,
        "logoname": node.get("system.logo"),
        "delbutton": True
    },
                      macro="fckeditor_customs_filemanager")
Example #36
0
def send_attfile(req):
    access = AccessData(req)
    f = req.path[9:].split('/')
    try:
        node = getNode(f[0])
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(node, "data") and node.type != "directory":
        return 403
    if len([file for file in node.getFiles() if file._path in ["/".join(f[1:]), "/".join(f[1:-1])]]) == 0:  # check filepath
        return 403

    filename = clean_path("/".join(f[1:]))
    path = join_paths(config.get("paths.datadir"), filename)
    mime, type = getMimeType(filename)
    if(get_filesize(filename) > 16 * 1048576):
        req.reply_headers["Content-Disposition"] = 'attachment; filename="{}"'.format(filename)

    return req.sendFile(path, mime)
Example #37
0
def send_rawfile(req, n=None):
    access = AccessData(req)
    if not n:
        id, filename = splitpath(req.path)
        n = None
        try:
            n = tree.getNode(id)
        except tree.NoSuchNodeError:
            return 404

    if not access.hasAccess(n, "data") and n.getContentType() not in [
            "directory", "collections", "collection"
    ]:
        return 403
    for f in n.getFiles():
        if f.getType() == "original":
            incUsage(n)
            return req.sendFile(f.retrieveFile(n), f.getMimeType(n))
    return 404
Example #38
0
    def html(self, req):
        styles = []
        nodeprint = "1"  # show print icon
        styles = self.content.getContentStyles()

        if "raw" in req.params:
            path = ""
        else:
            items = req.params.get("itemsperpage")
            try:
                id = self.content.node.id
                node = self.content.node

                if not node.getContentType() in ['collection', 'directory']:
                    nodeprint = 0
                else:
                    if node.get("system.print") != "":
                        nodeprint = node.get("system.print")
            except:
                id = 0

            printlink = '/print/' + str(id)
            if nodeprint == "1" and "sortfield0" in req.params.keys():
                printlink += '?sortfield0=' + str(
                    req.params.get("sortfield0")) + '&sortfield1=' + str(
                        req.params.get("sortfield1"))

            if req.params.get("show_navbar") == 0 or req.session.get(
                    "area") == "publish":
                breadscrubs = []
            else:
                try:
                    breadscrubs = self.getPath(lang(req),
                                               access=AccessData(req))
                except AttributeError:
                    log.exception("")
                    return req.error(404, "Object cannot be shown")

            path = req.getTAL(theme.getTemplate("content_nav.html"), {
                "params": self.params,
                "path": breadscrubs,
                "styles": styles,
                "logo": self.collectionlogo,
                "searchmode": req.params.get("searchmode", ""),
                "items": items,
                "id": id,
                "nodeprint": nodeprint,
                "printlink": printlink,
                "area": req.session.get("area", "")
            },
                              macro="path")

        return path + '\n<!-- CONTENT START -->\n' + self.content.html(
            req) + '\n<!-- CONTENT END -->\n'
Example #39
0
def getNodeListXMLForUser(node, readuser=None, exclude_filetypes=[], attribute_name_filter=None):
    if readuser:
        # only write child data if children_access_user has read access
        children_access = AccessData(user=users.getUser(readuser))
    else:
        children_access = None
    wr = _StringWriter()
    wr.write('<nodelist exportversion="%s">\n' % getInformation()["version"])
    node.writexml(wr, children_access=children_access, exclude_filetypes=exclude_filetypes, attribute_name_filter=attribute_name_filter)
    wr.write("</nodelist>\n")
    return wr.get()
Example #40
0
 def getSchemas(self):
     schemas = filter(lambda x: x.isActive(), loadTypesFromDB())
     schemalist = {}
     for user in self.getChildren():
         try:
             for schema in AccessData(user=user).filter(schemas):
                 schemalist[schema.getName()] = "."
         except:
             pass
     schemalist = sorted(schemalist.keys())
     return schemalist
Example #41
0
def getAccessRights(node):
    """ Get acccess rights for the public.
    The values returned descend from
    http://wiki.surffoundation.nl/display/standards/info-eu-repo/#info-eu-repo-AccessRights.
    This values are used by OpenAIRE portal.

    """
    try:  # if node.get('updatetime') is empty, the method parse_date would raise an exception
        l_date = parse_date(node.get('updatetime'))
    except:
        l_date = date.now()
    guestAccess = AccessData(user=users.getUser('Gast'))
    if date.now() < l_date:
        return "embargoedAccess"
    elif guestAccess.hasAccess(node, 'read'):
        if guestAccess.hasAccess(node, 'data'):
            return "openAccess"
        else:
            return "restrictedAccess"
    else:
        return "closedAccess"
Example #42
0
def getAccessRights(node):
    """ Get acccess rights for the public.
    The values returned descend from
    http://wiki.surffoundation.nl/display/standards/info-eu-repo/#info-eu-repo-AccessRights.
    This values are used by OpenAIRE portal.

    """
    try:  # if node.get('updatetime') is empty, the method parse_date would raise an exception
        l_date = parse_date(node.get('updatetime'))
    except:
        l_date = date.now()
    guestAccess = AccessData(user=users.getUser('Gast'))
    if date.now() < l_date:
        return "embargoedAccess"
    elif guestAccess.hasAccess(node, 'read'):
        if guestAccess.hasAccess(node, 'data'):
            return "openAccess"
        else:
            return "restrictedAccess"
    else:
        return "closedAccess"
Example #43
0
    def popup_fullsize(self, req):
        access = AccessData(req)
        d = {}
        svg = 0
        if (not access.hasAccess(self, "data") and not dozoom(self)) or not access.hasAccess(self, "read"):
            req.write(t(req, "permission_denied"))
            return
        zoom_exists = 0
        for file in self.getFiles():
            if file.getType() == "zoom":
                zoom_exists = 1
            if file.getName().lower().endswith('svg') and file.type == "original":
                svg = 1

        d["svg"] = svg
        d["width"] = self.get("origwidth")
        d["height"] = self.get("origheight")
        d["key"] = req.params.get("id", "")
        # we assume that width==origwidth, height==origheight
        d['flash'] = dozoom(self) and zoom_exists
        d['tileurl'] = "/tile/" + self.id + "/"
        req.writeTAL("contenttypes/image.html", d, macro="imageviewer")
Example #44
0
    def popup_fullsize(self, req):

        def videowidth():
            return int(self.get('vid-width') or 0) + 64

        def videoheight():
            int(self.get('vid-height') or 0) + 53

        access = AccessData(req)
        if not access.hasAccess(self, "data") or not access.hasAccess(self, "read"):
            req.write(t(req, "permission_denied"))
            return

        f = None
        for filenode in self.getFiles():
            if filenode.getType() in ["original", "video"] and filenode.retrieveFile().endswith('flv'):
                f = "/file/%s/%s" % (self.id, filenode.getName())
                break

        script = ""
        if f:
            script = '<p href="%s" style="display:block;width:%spx;height:%spx;" id="player"/p>' % (f, videowidth(), videoheight())

        # use jw player
        captions_info = getCaptionInfoDict(self)
        if captions_info:
            logger.info("video: '%s' (%s): captions: dictionary 'captions_info': %s" % (self.name, self.id, captions_info))

        context = {
            "file": f,
            "script": script,
            "node": self,
            "width": videowidth(),
            "height": videoheight(),
            "captions_info": json.dumps(captions_info),
        }

        req.writeTAL("contenttypes/video.html", context, macro="fullsize_flv_jwplayer")
Example #45
0
def update_node(req, path, params, data, id):

    # get the user and verify the signature
    if params.get('user'):
        user = users.getUser(params.get('user'))
        userAccess = AccessData(user=user)

        if userAccess.user:
            valid = userAccess.verify_request_signature(req.fullpath, params)
            if not valid:
                userAccess = None
        else:
            userAccess = None
    else:
        user = users.getUser('Gast')
        userAccess = AccessData(user=user)

    node = tree.getNode(id)

    # check user access
    if userAccess and userAccess.hasAccess(node, "write"):
        pass
    else:
        s = "No Access"
        req.write(s)
        d = {
            'status': 'fail',
            'html_response_code': '403',
            'errormessage': 'no access'
        }
        return d['html_response_code'], len(s), d

    node.name = params.get('name')
    metadata = json.loads(params.get('metadata'))

    # set provided metadata
    for key, value in metadata.iteritems():
        node.set(u(key), u(value))

    # service flags
    node.set("updateuser", user.getName())
    node.set("updatetime", format_date())
    node.setDirty()

    d = {
        'status': 'OK',
        'html_response_code': '200',
        'build_response_end': time.time()
    }
    s = "OK"

    # we need to write in case of POST request, send as buffer wil not work
    req.write(s)

    req.reply_headers['updatetime'] = node.get('updatetime')

    return d['html_response_code'], len(s), d
Example #46
0
def send_attfile(req):
    access = AccessData(req)
    f = req.path[9:].split('/')
    try:
        node = getNode(f[0])
    except tree.NoSuchNodeError:
        return 404
    if not access.hasAccess(node, "data") and node.type != "directory":
        return 403
    if len([
            file for file in node.getFiles()
            if file._path in ["/".join(f[1:]), "/".join(f[1:-1])]
    ]) == 0:  # check filepath
        return 403

    filename = clean_path("/".join(f[1:]))
    path = join_paths(config.get("paths.datadir"), filename)
    mime, type = getMimeType(filename)
    if (get_filesize(filename) > 16 * 1048576):
        req.reply_headers[
            "Content-Disposition"] = 'attachment; filename="{}"'.format(
                filename)

    return req.sendFile(path, mime)
Example #47
0
def getContent(req, ids):
    ret = ""
    user = users.getUserFromRequest(req)
    access = AccessData(req)
    nodes = []
    for id in ids:
        if not access.hasWriteAccess(tree.getNode(id)):
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")
        nodes += [tree.getNode(id)]

    if "classes" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    v = {}
    v["basedirs"] = [tree.getRoot('home'), tree.getRoot('collections')]
    id = req.params.get("id", tree.getRoot().id)
    v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s'" % (id, id)
    v["idstr"] = ",".join(ids)
    v["nodes"] = nodes
    v["t"] = t
    v["language"] = lang(req)
    return req.getTAL("web/edit/modules/classes.html", v, macro="classtree")
Example #48
0
    def popup_fullsize(self, req):
        access = AccessData(req)
        d = {}
        svg = 0
        if (not access.hasAccess(self, "data")
                and not dozoom(self)) or not access.hasAccess(self, "read"):
            req.write(t(req, "permission_denied"))
            return
        zoom_exists = 0
        for file in self.getFiles():
            if file.getType() == "zoom":
                zoom_exists = 1
            if file.getName().lower().endswith(
                    'svg') and file.type == "original":
                svg = 1

        d["svg"] = svg
        d["width"] = self.get("origwidth")
        d["height"] = self.get("origheight")
        d["key"] = req.params.get("id", "")
        # we assume that width==origwidth, height==origheight
        d['flash'] = dozoom(self) and zoom_exists
        d['tileurl'] = "/tile/" + self.id + "/"
        req.writeTAL("contenttypes/image.html", d, macro="imageviewer")
Example #49
0
def writetree(req,
              node,
              f,
              key="",
              openednodes=None,
              sessionkey="unfoldedids",
              omitroot=0):
    ret = ""
    access = AccessData(req)

    try:
        unfoldedids = req.session[sessionkey]
        len(unfoldedids)
    except:
        req.session[sessionkey] = unfoldedids = {tree.getRoot().id: 1}

    if openednodes:
        # open all selected nodes and their parent nodes
        def o(u, n):
            u[n.id] = 1
            for n in n.getParents():
                o(u, n)

        for n in openednodes:
            o(unfoldedids, n)
        req.session[sessionkey] = unfoldedids

    try:
        unfold = req.params["tree_unfold"]
        unfoldedids[unfold] = 1
    except KeyError:
        pass

    try:
        fold = req.params["tree_fold"]
        unfoldedids[fold] = 0
    except KeyError:
        pass

    if omitroot:
        for c in node.getChildren().sort("name"):
            ret += writenode(req, c, unfoldedids, f, 0, key, access)
    else:
        ret += writenode(req, node, unfoldedids, f, 0, key, access)

    return ret
Example #50
0
def getPathTo(req):
    # returns path(s) to selected node, 'x' separated, with selected nodes in ()
    # parameters: pathTo=selected Node
    access = AccessData(req)
    collectionsid = tree.getRoot('collections').id
    id = req.params.get("pathTo", collectionsid).split(",")[0]
    node = tree.getNode(id)

    items = []
    checked = []

    for path in getPaths(node, access):
        if node.id not in path and node.isContainer():  # add node if container
            path.append(node)

        checked.append(path[-1].id)  # last item of path is checked

        if path[0].getParents()[0].id == collectionsid and collectionsid not in items:
            items.append(collectionsid)

        for item in path:
            if item.id not in items:
                items.append(item.id)

        items.append("x")  # set devider for next path
        if req.params.get("multiselect", "false") == "false":  # if not multiselect use only first path
            break

    if len(items) == 0 or collectionsid in tree.getNode(items[0]).getParents()[0].id:
        items = [collectionsid] + items

    items = (",").join(items)

    for check in checked:  # set marked items
        items = items.replace(check, "(%s)" % (check))

    req.write(items)
    return
Example #51
0
def upload_new_node(req, path, params, data):

    try:
        uploadfile = params['data']
        del params['data']
    except KeyError:
        uploadfile = None

    # get the user and verify the signature
    if params.get('user'):
        # user=users.getUser(params.get('user'))
        #userAccess = AccessData(user=user)
        _user = users.getUser(params.get('user'))
        if not _user:  # user of dynamic

            class dummyuser:  # dummy user class

                # return all groups with given dynamic user
                def getGroups(self):
                    return [g.name for g in tree.getRoot('usergroups').getChildren() if g.get(
                        'allow_dynamic') == '1' and params.get('user') in g.get('dynamic_users')]

                def getName(self):
                    return params.get('user')

                def getDirID(self):  # unique identifier
                    return params.get('user')

                def isAdmin(self):
                    return 0

            _user = dummyuser()
        userAccess = AccessData(user=_user)

        if userAccess.user:
            user = userAccess.user
            if not userAccess.verify_request_signature(
                    req.fullpath +
                    '?',
                    params):
                userAccess = None
        else:
            userAccess = None
    else:
        user = users.getUser(config.get('user.guestuser'))
        userAccess = AccessData(user=user)

    parent = tree.getNode(params.get('parent'))

    # check user access
    if userAccess and userAccess.hasAccess(parent, "write"):
        pass
    else:
        s = "No Access"
        req.write(s)
        d = {
            'status': 'fail',
            'html_response_code': '403',
            'errormessage': 'no access'}
        logger.error("user has no edit permission for node %s" % parent)
        return d['html_response_code'], len(s), d

    datatype = params.get('type')
    uploaddir = users.getUploadDir(user)

    n = tree.Node(name=params.get('name'), type=datatype)
    if isinstance(uploadfile, types.InstanceType):  # file object used
        nfile = importFile(uploadfile.filename, uploadfile.tempname)
    else:  # string used
        nfile = importFileFromData(
            'uploadTest.jpg',
            base64.b64decode(uploadfile))
    if nfile:
        n.addFile(nfile)
    else:
        logger.error("error in file uploadservice")

    try:  # test metadata
        metadata = json.loads(params.get('metadata'))
    except ValueError:
        metadata = dict()

    # set provided metadata
    for key, value in metadata.iteritems():
        n.set(u(key), u(value))

    # service flags
    n.set("creator", user.getName())
    n.set("creationtime", format_date())

    parent.addChild(n)

    # process the file, we've added to the new node
    if hasattr(n, "event_files_changed"):
        try:
            n.event_files_changed()

        except OperationException as e:
            for file in n.getFiles():
                if os.path.exists(file.retrieveFile()):
                    os.remove(file.retrieveFile())
            raise OperationException(e.value)

    # make sure the new node is visible immediately from the web service and
    # the search index gets updated
    n.setDirty()
    tree.remove_from_nodecaches(parent)

    d = {
        'status': 'Created',
        'html_response_code': '201',
        'build_response_end': time.time()}
    s = "Created"

    # provide the uploader with the new node ID
    req.reply_headers['NodeID'] = n.id

    # we need to write in case of POST request, send as buffer will not work
    req.write(s)

    return d['html_response_code'], len(s), d
Example #52
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    node = tree.getNode(ids[0])
    access = AccessData(req)
    
    if not access.hasWriteAccess(node) or "searchmask" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    p2 = {}
    for k, v in req.params.items():
        if k.endswith(".x") or k.endswith(".y"):
            p2[k[:-2]] = v
        else:
            p2[k] = v
    req.params = p2

    openfield = None
    delfield = None
    delsubfield = None
    for k, v in req.params.items():
        if k.startswith("open_"):
            openfield = k[5:]
        if k.startswith("del_"):
            delfield = k[4:]
        if k.startswith("delsub_"):
            delsubfield = k[7:]

    try:
        root = tree.getRoot("searchmasks") 
    except tree.NoSuchNodeError:
        root = tree.Node("searchmasks", type="searchmasks")
        tree.getRoot().addChild(root)

    searchtype = req.params.get("searchtype", None)
    if not searchtype:
        searchtype = node.get("searchtype")
        if not searchtype:
            searchtype = "none"
            # if a parent has a search mask, use 'inherit'
            n = node
            while len(n.getParents()):
                n = n.getParents()[0]
                if n.get("searchtype") == "own":
                    searchtype = "parent"
    node.set("searchtype", searchtype)

    try:
        myschema = tree.getNode(req.params.get("schema", None))
    except tree.NoSuchNodeError:
        if req.params.get("schema", None) and req.params.get("schema").endswith(";"):
            myschema = tree.getNode(req.params.get("schema")[:-1])
        else:
            myschema = None
    try:
        schemafield = tree.getNode(req.params.get("schemafield", None))
    except tree.NoSuchNodeError:
        if req.params.get("schemafield", None) and req.params.get("schemafield").endswith(";"):
            schemafield = tree.getNode(req.params.get("schemafield")[:-1])
        else:
            schemafield = None

    if myschema and schemafield and schemafield not in myschema.getChildren():
        schemafield = None
    if schemafield and schemafield.type != "metafield":
        schemafield = None
   
    fields = None
    selectedfield = None
    isnewfield = False
    createsub = False
    closefield = False

    if searchtype == "own":
        maskname = node.get("searchmaskname")

        if not maskname or root.hasChild(maskname) == 0:
            mask = searchmask.generateMask(node)
        else:
            mask = root.getChild(maskname)
        
        selectedfieldid = req.params.get("selectedfield", None)
        if selectedfieldid:  # edit
            selectedfield = tree.getNode(selectedfieldid)
            assert selectedfield in mask.getChildren()
            selectedfield.setName(req.params["fieldname"])
            if "createsub" in req.params and schemafield:
                createsub = True
                selectedfield.addChild(schemafield)
            if delsubfield:
                selectedfield.removeChild(tree.getNode(delsubfield))

        if req.params.get("isnewfield", "") == "yes":  # create a new field
            isnewfield = True
            l = mask.getNumChildren()
            mask.addChild(tree.Node("Suchfeld %s" % l, type="searchmaskitem"))

        elif delfield:  # del a field
            delfield = tree.getNode(delfield)
            assert delfield in mask.getChildren()
            mask.removeChild(delfield)

        elif openfield:  # unfold a new field
            selectedfieldid = openfield

        elif "close" in req.params:  # fold a field
            closefield = True
            selectedfieldid = None

        if selectedfieldid:
            selectedfield = tree.getNode(selectedfieldid)
            if selectedfield not in mask.getChildren():  # this usually happens if the field was just deleted
                selectedfield = None
        else:
            selectedfield = None

        if mask is None:
            print "no parent searchmask found, empty mask created"
            mask = tree.Node(name=maskname, type="searchmask")

        fields = mask.getChildren()

    data = {"idstr": ",".join(ids), "node": node, "searchtype": searchtype, "schemas": schema.loadTypesFromDB(),
            "searchfields": fields, "selectedfield": selectedfield,
            "newfieldlink": "edit_content?id=%s&tab=searchmask" % node.id, "defaultschemaid": None,
            "defaultfieldid": None, "id": req.params.get("id")}

    if myschema:
        data["defaultschemaid"] = myschema.id
    if schemafield:
        data["defaultfieldid"] = schemafield.id

    data["schema"] = myschema

    def display(schemafield): 
        if not schemafield or schemafield.type != 'metafield':
            return 0
        if not schemafield.Searchfield():
            return 0
        if schemafield.get('type') == 'union':
            return 0
        return 1
    data["display"] = display

    searchtypechanged = False
    if req.params.get("searchtypechanged", "") == "true":
        searchtypechanged = True

    if any([openfield, isnewfield, delfield, delsubfield, createsub, myschema, searchtypechanged, closefield]):
        content = req.getTAL("web/edit/modules/searchmask.html", data, macro="edit_search")
        s = json.dumps({'content': content})
        req.write(s)
        return None

    return req.getTAL("web/edit/modules/searchmask.html", data, macro="edit_search")
Example #53
0
def get_sheme(req, path, params, data, name):

    atime = starttime = time.time()
    r_timetable = []
    userAccess = None

    # get the user and verify the signature
    if params.get('user'):
        # user=users.getUser(params.get('user'))
        #userAccess = AccessData(user=user)
        _user = users.getUser(params.get('user'))
        if not _user:  # user of dynamic

            class dummyuser:  # dummy user class

                def getGroups(self):  # return all groups with given dynamic user
                    return [g.name for g in tree.getRoot('usergroups').getChildren() if g.get(
                        'allow_dynamic') == '1' and params.get('user') in g.get('dynamic_users')]

                def getName(self):
                    return params.get('user')

                def getDirID(self):  # unique identifier
                    return params.get('user')

                def isAdmin(self):
                    return 0

            _user = dummyuser()
        userAccess = AccessData(user=_user)

        if userAccess.user is not None:
            valid = userAccess.verify_request_signature(req.fullpath, params)
            if not valid:
                userAccess = None
        else:
            userAccess = None

    if userAccess is None:
        d = {}
        d['status'] = 'fail'
        d['html_response_code'] = '403'  # denied
        return d['html_response_code'], 0, d

    d = {}
    d['timetable'] = []
    d['status'] = 'ok'
    d['html_response_code'] = '200'  # ok
    d['build_response_end'] = time.time()
    if r_timetable:
        d['timetable'] = r_timetable[:]

    if name.endswith('/'):
        name = name[:-1]
    s = exportMetaScheme(name)

    def compressForDeflate(s):
        import gzip
        return gzip.zlib.compress(s, 9)

    def compressForGzip(s):
        import cStringIO
        import gzip
        buffer = cStringIO.StringIO()
        gzfile = gzip.GzipFile(mode='wb', fileobj=buffer, compresslevel=9)
        gzfile.write(s)
        gzfile.close()
        return buffer.getvalue()

    if 'deflate' in req.params:
        size_uncompressed = len(s)
        compressed_s = compressForDeflate(s)
        s = compressed_s
        size_compressed = len(s)
        try:
            percentage = 100.0 * size_compressed / size_uncompressed
        except:
            percentage = 100.0
        req.reply_headers['Content-Encoding'] = "deflate"
        d['timetable'].append(["'deflate' in request: executed compressForDeflate(s), %d bytes -> %d bytes (compressed to: %.1f %%)" %
                               (size_uncompressed, size_compressed, percentage), time.time() - atime])
        atime = time.time()

    elif 'gzip' in req.params:
        size_uncompressed = len(s)
        compressed_s = compressForGzip(s)
        s = compressed_s
        size_compressed = len(s)
        try:
            percentage = 100.0 * size_compressed / size_uncompressed
        except:
            percentage = 100.0
        req.reply_headers['Content-Encoding'] = "gzip"
        d['timetable'].append(["'gzip' in request: executed compressForGzip(s), %d bytes -> %d bytes (compressed to: %.1f %%)" %
                               (size_uncompressed, size_compressed, percentage), time.time() - atime])
        atime = time.time()

    mimetype = 'text/html'

    req.reply_headers['Content-Type'] = "text/xml; charset=utf-8"
    req.reply_headers['Content-Length'] = len(s)

    req.sendAsBuffer(s, mimetype, force=1)
    d['timetable'].append(["executed req.sendAsBuffer, %d bytes, mimetype='%s'" % (len(s), mimetype), time.time() - atime])
    atime = time.time()
    return d['html_response_code'], len(s), d
Example #54
0
def getData(req):
    access = AccessData(req)
    pid = req.params.get("parentId")
    style = req.params.get("style", "edittree")
    ret = []

    for c in tree.getNode(pid).getChildren().sort_by_orderpos():
        if not access.hasReadAccess(c):
            continue
        try:
            if c.isContainer():
                cnum = len(c.getContainerChildren())
                inum = len(c.getContentChildren())

                label = c.getLabel()
                title = c.getLabel() + " (" + str(c.id) + ")"

                cls = "folder"

                itemcls = ""
                if not access.hasWriteAccess(c):
                    itemcls = "read"

                if c.type == "collection":  # or "collection" in c.type:
                    cls = "collection"
                if hasattr(c, 'treeiconclass'):
                    cls = c.treeiconclass()

                if c.getName().startswith(translate('user_trash', request=req)):
                    cls = "trashicon"
                elif c.getName().startswith(translate('user_upload', request=req)):
                    cls = "uploadicon"
                elif c.getName().startswith(translate('user_import', request=req)):
                    cls = "importicon"
                elif c.getName().startswith(translate('user_faulty', request=req)):
                    cls = "faultyicon"
                elif c.getName().startswith(translate('user_directory', request=req)):
                    cls = "homeicon"

                if style == "edittree":  # standard tree for edit area
                    if inum > 0:
                        label += " <small>(" + str(inum) + ")</small>"

                    ret.append('<li class="' + cls + '.gif" id="Node' + c.id + '">')
                    ret.append('<a href="#" title="' + title + '" id="' + c.id + '" class="' + itemcls + '">' + label + '</a>')

                    if cnum > 0:
                        ret.append('<ul><li parentId="' + c.id + '" class="spinner.gif"><a href="#">&nbsp;</a></li></ul>')
                    ret.append('</li>')

                elif style == "classification":  # style for classification
                    ret.append('<li class="' + cls + '.gif" id="Node' + c.id + '">')
                    ret.append('<a href="#" title="' + title + '" id="' + c.id + '" class="' + itemcls +
                               '">' + label + ' <input type="image" src="/img/ftree/uncheck.gif"/></a>')

                    if cnum > 0:
                        ret.append('<ul><li parentId="' + c.id + '" class="spinner.gif"><a href="#">&nbsp;</a></li></ul>')

                    ret.append('</li>')
        except:
            pass

    req.write("\n".join(ret))
    return