Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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]
Ejemplo n.º 5
0
def show_shoppingbag(req, msg=""):
    """open shoppingbag and show content"""
    img = False
    doc = False
    media = False

    (width, height) = calculate_dimensions(req)
    v = {"width": width, "height": height}
    f = []

    # deliver image dimensions of original
    def calc_dim(file):
        ret = ""
        try:
            w = int(file.get("width"))
            h = int(file.get("height"))
        except:
            return "padding:0px 0px;width:90px;height:90px;"

        if w > h:
            factor = 90.0 / w
            h = h * 90.0 / w
            w = 90
            ret += 'padding:%spx 0px;' % str(int((90 - h) / 2))
        else:
            w = w * 90.0 / h
            h = 90
            ret += 'padding:0px %spx;' % str(int((90 - w) / 2))
        return ret + 'width:%spx;height:%spx;' % (str(int(w)), str(int(h)))

    # deliver document file size
    def calc_size(file):
        for f in file.getFiles():
            if f.getType() == "document":
                return format_filesize(f.getSize())
        return ""

    def calc_length(file):
        try:
            return file.getDuration()
        except:
            return ""

    access = AccessData(req)

    sb = req.session.get("shoppingbag", [])
    sb = [nid for nid in sb if nid.strip()]
    for node in access.filter(tree.NodeList(sb)):
        if node.getCategoryName() == "image":
            img = True
        if node.getCategoryName() == "document":
            doc = True
        if node.getCategoryName() in ["audio", "video"]:
            media = True
        f.append(node)

    if len(f) != len(req.session.get("shoppingbag", [])) and msg == "":
        msg = "popup_shoppingbag_items_filtered"

    v["files"] = f
    v["image"] = img
    v["document"] = doc
    v["media"] = media
    v["img_perc_range"] = range(1, 11)
    v["img_pix_sizes"] = ["1600x1200", "1280x960", "1024x768", "800x600"]
    v["calc_dim"] = calc_dim
    v["calc_size"] = calc_size
    v["calc_length"] = calc_length
    user = users.getUserFromRequest(req)
    v["shoppingbags"] = user.getShoppingBag()
    v["user"] = user
    v["msg"] = msg

    req.writeTAL(theme.getTemplate("shoppingbag.html"), v, macro="shoppingbag")
    return httpstatus.HTTP_OK
Ejemplo n.º 6
0
def extended_search(req):
    from web.frontend.content import ContentList
    max = 3
    if req.params.get("searchmode") == "extendedsuper":
        max = 10
    sfields = []
    access = AccessData(req)
    metatype = None

    collectionid = req.params.get("collection", tree.getRoot().id)
    try:
        collection = tree.getNode(collectionid)
    except:
        for coll in tree.getRoot("collections").getChildren():
            collection = tree.getNode(coll.id)
            break

    q_str = ''
    q_user = ''
    first2 = 1
    for i in range(1, max + 1):
        f = u(req.params.get("field" + str(i), "").strip())
        q = u(req.params.get("query" + str(i), "").strip())

        if not q and "query" + str(i) + "-from" not in req.params:
            continue

        if not first2:
            q_str += " and "
            q_user += " %s " % (translate("search_and", request=req))

        first2 = 0

        if not f.isdigit():
            q = u(req.params.get("query" + str(i), "").strip())
            q_str += f + '=' + protect(q)
            q_user += f + '=' + protect(q)
        else:
            masknode = tree.getNode(f)
            assert masknode.type == "searchmaskitem"
            first = 1
            q_str += "("
            for metatype in masknode.getChildren():
                if not first:
                    q_str += " or "
                    q_user += " %s " % (translate("search_or", request=req))
                first = 0
                if "query" + str(i) + "-from" in req.params and metatype.getFieldtype() == "date":
                    date_from = "0000-00-00T00:00:00"
                    date_to = "0000-00-00T00:00:00"
                    fld = metatype
                    if str(req.params["query" + str(i) + "-from"]) != "":
                        date_from = date.format_date(
                            date.parse_date(str(req.params["query" + str(i) + "-from"]), fld.getValues()), "%Y-%m-%dT%H:%M:%S")
                    if str(req.params["query" + str(i) + "-to"]) != "":
                        date_to = date.format_date(
                            date.parse_date(str(req.params["query" + str(i) + "-to"]), fld.getValues()), "%Y-%m-%dT%H:%M:%S")

                    if date_from == "0000-00-00T00:00:00" and date_to != date_from:  # from value
                        q_str += metatype.getName() + ' <= ' + date_to
                        q_user += "%s &le; \"%s\"" % (metatype.getName(), str(req.params["query" + str(i) + "-to"]))

                    elif date_to == "0000-00-00T00:00:00" and date_to != date_from:  # to value
                        q_str += metatype.getName() + ' >= ' + date_from
                        q_user += "%s &ge; \"%s\"" % (metatype.getName(), str(req.params["query" + str(i) + "-from"]))
                    else:
                        q_str += '({} >= {} and {} <= {})'.format(metatype.getName(), date_from, metatype.getName(), date_to)

                        q_user += "(%s %s \"%s\" %s \"%s\")" % (metatype.getName(),
                                                                translate("search_between",
                                                                          request=req),
                                                                str(req.params["query" + str(i) + "-from"]),
                                                                translate("search_and",
                                                                          request=req),
                                                                str(req.params["query" + str(i) + "-to"]))
                else:
                    q = u(req.params.get("query" + str(i), "").strip())
                    q_str += metatype.getName() + '=' + protect(q)
                    if metatype.getLabel() != "":
                        q_user += "%s = %s" % (metatype.getLabel(), protect(q))
                    else:
                        q_user += "%s = %s" % (metatype.getName(), protect(q))

            q_str += ")"
    try:
        if req.params.get("act_node", "") and req.params.get("act_node") != str(collection.id):
            result = tree.getNode(req.params.get("act_node")).search(q_str)
        else:
            result = collection.search(q_str)
        result = access.filter(result)
        logging.getLogger('usertracing').info(access.user.name + " xsearch for '" + q_user + "', " + str(len(result)) + " results")
        if len(result) > 0:
            cl = ContentList(result, collection, q_user.strip())
            cl.feedback(req)
            cl.linkname = ""
            cl.linktarget = ""
            return cl
        return SearchResult([], q_user.strip())
    except:
        return SearchResult(None, q_user.strip())
Ejemplo n.º 7
0
def exportsearch(req, xml=0):  # format 0=pre-formated, 1=xml, 2=plain
    access = AccessData(req)
    access = core.acl.getRootAccess()

    id = req.params.get("id")
    q = req.params.get("q", "")
    lang = req.params.get("language", "")
    collections = tree.getRoot("collections")

    if xml:
        req.reply_headers['Content-Type'] = "text/xml; charset=utf-8"
        req.write('<?xml version="1.0" encoding="utf-8"?>')

    else:
        req.reply_headers['Content-Type'] = "text/plain; charset=utf-8"

    try:
        node = tree.getNode(id)
    except tree.NoSuchNodeError:
        if xml:
            req.write("<error>Invalid ID</error>")
        else:
            req.write("var error='invalid id';")
        return
    if not isParentOf(node, collections):
        if xml:
            req.write("<error>Invalid ID</error>")
        else:
            req.write("var error='invalid id';")
        return

    if not q:
        nodes = access.filter(node.search("objtype=document"))
    else:
        #nodes = access.filter(node.search("objtype=document and "+q));
        nodes = access.filter(node.search(q))

    limit = int(req.params.get("limit", 99999))
    sortfield = req.params.get("sort", None)

    if sortfield:
        nodes = nodes.sort_by_fields(sortfield)

    if limit < len(nodes):
        nodes = nodes[0:limit]

    if xml:  # xml
        req.write("<nodelist>")
        i = 0
        for node in nodes:
            s = xmlnode.getSingleNodeXML(node)
            req.write(s)
            i = i + 1
        req.write("</nodelist>")

    elif req.params.get("data", None):
        req.write('a=new Array(%d);' % len(nodes))
        i = 0
        for node in nodes:
            req.write('a[%d] = new Object();\n' % i)
            req.write("  a[%d]['nodename'] = '%s';\n" % (i, node.name))
            for k, v in node.items():
                req.write("    a[%d]['%s'] = '%s';\n" % (i, esc(k), esc(v)))
            i = i + 1
        req.write('add_data(a);\n')
    else:
        req.write('a=new Array(%d);' % len(nodes))
        i = 0
        labels = int(req.params.get("labels", 1))
        for node in nodes:
            req.write('a[%d] = new Object();\n' % i)
            req.write(
                "a[%d]['text'] = '%s';\n" %
                (i, esc(node.show_node_text(labels=labels, language=lang))))
            req.write("a[%d]['link'] = 'http://%s?id=%s';\n" %
                      (i, config.get('host.name'), node.id))
            i = i + 1
        req.write('add_data(a);\n')
    print "%d node entries xml=%d" % (i, xml)
Ejemplo n.º 8
0
def extended_search(req):
    from web.frontend.content import ContentList
    max = 3
    if req.params.get("searchmode") == "extendedsuper":
        max = 10
    sfields = []
    access = AccessData(req)
    metatype = None

    collectionid = req.params.get("collection", tree.getRoot().id)
    try:
        collection = tree.getNode(collectionid)
    except:
        for coll in tree.getRoot("collections").getChildren():
            collection = tree.getNode(coll.id)
            break

    q_str = ''
    q_user = ''
    first2 = 1
    for i in range(1, max + 1):
        f = u(req.params.get("field" + str(i), "").strip())
        q = u(req.params.get("query" + str(i), "").strip())

        if not q and "query" + str(i) + "-from" not in req.params:
            continue

        if not first2:
            q_str += " and "
            q_user += " %s " % (translate("search_and", request=req))

        first2 = 0

        if not f.isdigit():
            q = u(req.params.get("query" + str(i), "").strip())
            q_str += f + '=' + protect(q)
            q_user += f + '=' + protect(q)
        else:
            masknode = tree.getNode(f)
            assert masknode.type == "searchmaskitem"
            first = 1
            q_str += "("
            for metatype in masknode.getChildren():
                if not first:
                    q_str += " or "
                    q_user += " %s " % (translate("search_or", request=req))
                first = 0
                if "query" + str(
                        i) + "-from" in req.params and metatype.getFieldtype(
                        ) == "date":
                    date_from = "0000-00-00T00:00:00"
                    date_to = "0000-00-00T00:00:00"
                    fld = metatype
                    if str(req.params["query" + str(i) + "-from"]) != "":
                        date_from = date.format_date(
                            date.parse_date(
                                str(req.params["query" + str(i) + "-from"]),
                                fld.getValues()), "%Y-%m-%dT%H:%M:%S")
                    if str(req.params["query" + str(i) + "-to"]) != "":
                        date_to = date.format_date(
                            date.parse_date(
                                str(req.params["query" + str(i) + "-to"]),
                                fld.getValues()), "%Y-%m-%dT%H:%M:%S")

                    if date_from == "0000-00-00T00:00:00" and date_to != date_from:  # from value
                        q_str += metatype.getName() + ' <= ' + date_to
                        q_user += "%s &le; \"%s\"" % (
                            metatype.getName(),
                            str(req.params["query" + str(i) + "-to"]))

                    elif date_to == "0000-00-00T00:00:00" and date_to != date_from:  # to value
                        q_str += metatype.getName() + ' >= ' + date_from
                        q_user += "%s &ge; \"%s\"" % (
                            metatype.getName(),
                            str(req.params["query" + str(i) + "-from"]))
                    else:
                        q_str += '({} >= {} and {} <= {})'.format(
                            metatype.getName(), date_from, metatype.getName(),
                            date_to)

                        q_user += "(%s %s \"%s\" %s \"%s\")" % (
                            metatype.getName(),
                            translate("search_between", request=req),
                            str(req.params["query" + str(i) + "-from"]),
                            translate("search_and", request=req),
                            str(req.params["query" + str(i) + "-to"]))
                else:
                    q = u(req.params.get("query" + str(i), "").strip())
                    q_str += metatype.getName() + '=' + protect(q)
                    if metatype.getLabel() != "":
                        q_user += "%s = %s" % (metatype.getLabel(), protect(q))
                    else:
                        q_user += "%s = %s" % (metatype.getName(), protect(q))

            q_str += ")"
    try:
        if req.params.get(
                "act_node",
                "") and req.params.get("act_node") != str(collection.id):
            result = tree.getNode(req.params.get("act_node")).search(q_str)
        else:
            result = collection.search(q_str)
        result = access.filter(result)
        logging.getLogger('usertracing').info(access.user.name +
                                              " xsearch for '" + q_user +
                                              "', " + str(len(result)) +
                                              " results")
        if len(result) > 0:
            cl = ContentList(result, collection, q_user.strip())
            cl.feedback(req)
            cl.linkname = ""
            cl.linktarget = ""
            return cl
        return SearchResult([], q_user.strip())
    except:
        return SearchResult(None, q_user.strip())
Ejemplo n.º 9
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)