Ejemplo n.º 1
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
Ejemplo n.º 2
0
def getContent(req, ids):
    class SortChoice:
        def __init__(self, label, value):
            self.label = label
            self.value = value

    def getSchemes(_req):
        return filter(lambda x: x.isActive(), acl.AccessData(_req).filter(loadTypesFromDB()))

    def getDatatypes(_req, _schemes):
        _dtypes = []
        datatypes = loadAllDatatypes()
        for scheme in _schemes:
            for dtype in scheme.getDatatypes():
                if dtype not in _dtypes:
                    for _t in datatypes:
                        if _t.getName() == dtype and not elemInList(dtypes, _t.getName()):
                            dtypes.append(_t)
        _dtypes.sort(
            lambda x, y: cmp(
                translate(x.getLongName(), request=_req).lower(), translate(y.getLongName(), request=req).lower()
            )
        )
        return _dtypes

    node = tree.getNode(ids[0])

    if "action" in req.params:
        if req.params.get("action") == "resort":
            _dir = "up"
            field = req.params.get("value", "").strip()
            nl = list(node.getChildren())
            if field:
                if field[0] == "-":
                    field = field[1:]
                    _dir = "down"
                nl.sort(lambda x, y: cmp(x.get(field).lower(), y.get(field).lower()))
                if _dir == "down":
                    nl.reverse()
            req.write(json.dumps({"state": "ok", "values": showdir(req, node, nodes=nl, sortfield_from_req=field)}))
            return None

        elif req.params.get("action") == "save":  # save selection for collection
            field = req.params.get("value")
            if field.strip() == "":
                node.removeAttribute("sortfield")
            else:
                node.set("sortfield", field)
            req.write(json.dumps({"state": "ok", "message": translate("edit_content_save_order", request=req)}))
        return None

    if node.isContainer():
        schemes = []
        dtypes = []

        v = {"operations": showoperations(req, node), "items": showdir(req, node)}
        access = acl.AccessData(req)
        if access.hasWriteAccess(node):
            schemes = getSchemes(req)
            dtypes = getDatatypes(req, schemes)

        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"]:
            try:
                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
            except TypeError:
                pass
        v["sortchoices"] = sortfields
        v["types"] = dtypes
        v["schemes"] = schemes
        v["id"] = ids[0]
        v["count"] = len(node.getContentChildren())
        v["language"] = lang(req)
        v["t"] = t
        return req.getTAL("web/edit/modules/content.html", v, macro="edit_content")
    if hasattr(node, "editContentDefault"):
        return node.editContentDefault(req)
    return ""
Ejemplo n.º 3
0
def getContent(req, ids):
    logg.error("publish.getContent")
    user = current_user
    publishdir = q(Node).get(ids[0])
    ret = ""

    errorids = []
    publisherror = []
    changes = []
    if "dopublish" in req.params.keys():
        logg.debug("dopublish")
        num_req_err_nodes = 0
        num_db_err_nodes = 0
        num_rights_err_nodes = 0
        objlist = []
        for key in req.params.keys():
            if key.isdigit():
                objlist.append(key)
                src = q(Node).get(req.params.get("id"))

        for obj_id in objlist:
            remove_from_src = False
            obj = q(Node).get(obj_id)
            metadatatype = obj.metadatatype
            mask_validated = False
            for mask in metadatatype.getMasks(type="edit"): # check required fields
                if mask.has_read_access() and mask.getName() == obj.system_attrs.get("edit.lastmask"):
                    for f in mask.validateNodelist([obj]):
                        errorids.append(f)
                    mask_validated = True

            logg.error(errorids)
            if len(errorids)>0: # object faulty
                num_req_err_nodes +=1
                # if object faulty, it is not necessary to do the rest of error handling for this object
                continue

            if not mask_validated:
                msg = "user %r going to publish node %r without having validated edit.lastmask" % (user, obj)
                logg.warning(msg)
                # should we validate standard edit mask here?

            for dest_id in req.params.get("destination", "").split(","):
                if not dest_id: # no destination given
                    continue

                dest = q(Node).get(dest_id)

                # XXX: this error handling should be revised, I think...

                error = False # general rights error
                if not src.has_read_access():
                    logg.error("Error in publishing of node %r: source position %r has no read access.", obj.id, src.id)
                    error = True
                if not dest.has_write_access():
                    logg.error("Error in publishing of node %r: destination %r has no write access.", obj.id, dest.id)
                    error = True
                if not obj.has_write_access():
                    logg.error("Error in publishing of node %r: object has no write access.", obj.id)
                    error = True
                if not isinstance(dest, Container) or dest == src:
                    # cannot happen normally due to selection tree
                    logg.error("Error in publishing of node %r: destination %r is not a directory.", obj.id, dest.id)
                    error = True

                if not error:
                    if not obj.is_descendant_of(dest):
                        dest.children.append(obj)
                        remove_from_src = True

                        if dest.id not in changes:
                            changes.append(dest.id)
                        if src.id not in changes:
                            changes.append(src.id)
                        logg.info("%s published %s (%s, %s) from src %s (%s, %s) to dest %s (%s, %s)", user.login_name,
                                  obj.id, obj.name, obj.type,
                                  src.id, src.name, src.type,
                                  dest.id, dest.name, dest.type)
                    else:
                        num_rights_err_nodes += 1
                        errorids.append(obj.id)
                        logg.error("Error in publishing of node {}: Destination node {} is child of node.".format(obj_id, dest.id))
                else:
                    # error already logged
                    num_rights_err_nodes += 1
                    errorids.append(obj.id)

            if remove_from_src:
                try:
                    src.children.remove(obj)
                    db.session.commit()
                except:
                    num_db_err_nodes += 1
                    logg.exception("Error in publishing of node {}: Database error".format(obj.id))
                    errorids.append(obj.id)


        # error messages for publishing assistant
        if num_req_err_nodes > 0:
            if num_req_err_nodes < 2:
                publisherror.append(_t(_lang(req), "error_publish_single_node"))
            else:
                publisherror.append(_t(_lang(req), "error_publish_multiple_nodes"))
        if num_rights_err_nodes > 0:
            if num_rights_err_nodes < 2:
                publisherror.append(_t(_lang(req), "error_publish_rights_single"))
            else:
                publisherror.append(_t(_lang(req), "error_publish_rights_multiple"))
        if num_db_err_nodes > 0:
            if num_db_err_nodes < 2:
                publisherror.append(_t(_lang(req), "error_publish_database_single"))
            else:
                publisherror.append(_t(_lang(req), "error_publish_database_multiple"))

        v = {}
        v["id"] = publishdir.id
        v["change"] = changes
        ret += req.getTAL("web/edit/modules/publish.html", v, macro="reload")

    # build normal window
    stddir = ""  # preset value for destination ids
    stdname = ""

    v = {"id": publishdir.id,
         "stddir": stddir,
         "stdname": stdname,
         "showdir": showdir(req,
                            publishdir,
                            publishwarn=None,
                            markunpublished=1,
                            faultyidlist=errorids,
                            ),
         "basedir": q(Collections).one(),
         "script": "var currentitem = '%s';\nvar currentfolder = '%s'" % (publishdir.id, publishdir.id), "idstr": ids,
         "faultyerrlist": publisherror,
        }
    v["csrf"] = req.csrf_token.current_token
    ret += req.getTAL("web/edit/modules/publish.html", v, macro="publish_form")
    return ret
Ejemplo n.º 4
0
                        sortfields += [SortChoice(sortfield.getLabel(), sortfield.getName())]
                        sortfields += [SortChoice(sortfield.getLabel() + translation_t(req, "descending"), "-" + sortfield.getName())]
                    break
        v['sortchoices'] = sortfields
        v['count'] = len(node.getContentChildren())
        v['language'] = lang(req)
        v['t'] = translation_t

    v.update({
        "id": req.params.get("id"),
        "sid": req.session.id,
        "datatypes": getDatatypes(req, schemes),
        "schemes": schemes,
        "uploadstate": req.params.get("upload"),
        "operations": showoperations(req, node),
        "nodelist": showdir(req, node),
    })
    return req.getTAL("web/edit/modules/upload.html", v, macro="upload_form")


# differs from os.path.split in that it handles windows as well as unix
# filenames
FNAMESPLIT = re.compile(r'(([^/\\]*[/\\])*)([^/\\]*)')


def mybasename(filename):
    g = FNAMESPLIT.match(filename)
    if g:
        basename =  g.group(3)
    else:
        basename = filename
Ejemplo n.º 5
0
        v['sortchoices'] = sortfields
        v['npp_choices'] = [
            SortChoice(str(x), x) for x in edit_node_per_page_values
        ]
        v['language'] = lang(req)
        v['t'] = translation_t

    search_html = render_search_box(q(Node).get(ids[0]),
                                    language,
                                    req,
                                    edit=True)
    searchmode = req.params.get("searchmode")
    item_count = []
    items = showdir(req,
                    node,
                    sortfield=req.params.get("sortfield"),
                    item_count=item_count)
    nav = shownav(req, node, sortfield=req.params.get("sortfield"))
    navigation_height = searchbox_navlist_height(req, item_count)
    count = item_count[0] if item_count[0] == item_count[
        1] else "%d from %d" % (item_count[0], item_count[1])
    searchparams = get_searchparams(req)
    searchparams = {
        k: unicode(v).encode("utf8")
        for k, v in searchparams.items()
    }

    v.update({
        "id":
        req.params.get("id"),
        "sid":
Ejemplo n.º 6
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    publishdir = tree.getNode(ids[0])
    explicit = tree.getNodesByAttribute("writeaccess", user.getName())
    ret = ""

    actionerror = []
    changes = []
    if "dopublish" in req.params.keys():
        access = AccessData(req)

        objlist = []
        for key in req.params.keys():
            if key.isdigit():
                objlist.append(key)
                src = tree.getNode(req.params.get("id"))

        for obj_id in objlist:
            faultylist = []
            obj = tree.getNode(obj_id)
            for mask in obj.getType().getMasks(
                    type="edit"):  # check required fields
                if access.hasReadAccess(mask) and mask.getName() == obj.get(
                        "edit.lastmask"):
                    for f in mask.validateNodelist([obj]):
                        faultylist.append(f)

            if len(faultylist) > 0:  # object faulty
                actionerror.append(obj_id)
                continue

            for dest_id in req.params.get("destination", "").split(","):
                if dest_id == "":  # no destination given
                    continue

                dest = tree.getNode(dest_id)
                if dest != src and access.hasReadAccess(
                        src) and access.hasWriteAccess(
                            dest) and access.hasWriteAccess(
                                obj) and isDirectory(dest):
                    if not nodeIsChildOfNode(dest, obj):
                        dest.addChild(obj)
                        src.removeChild(obj)

                        if dest.id not in changes:
                            changes.append(dest.id)
                        if src.id not in changes:
                            changes.append(src.id)
                        log.info(
                            "%s published %s (%r, %r) from src %s (%r, %r) to dest %s (%r, %r)"
                            % (
                                user.getName(),
                                obj.id,
                                obj.name,
                                obj.type,
                                src.id,
                                src.name,
                                src.type,
                                dest.id,
                                dest.name,
                                dest.type,
                            ))
                    else:
                        actionerror.append(obj.id)
                        log.error(
                            "Error in publishing of node %r: Destination node %r is child of node."
                            % (obj_id, dest.id))

                if not access.hasReadAccess(src):
                    log.error(
                        "Error in publishing of node %r: source position %r has no read access."
                        % (obj.id, src.id))
                if not access.hasWriteAccess(dest):
                    log.error(
                        "Error in publishing of node %r: destination %r has no write access."
                        % (obj.id, dest.id))
                if not access.hasWriteAccess(obj):
                    log.error(
                        "Error in publishing of node %r: object has no write access."
                        % obj.id)
                if not isDirectory(dest):
                    log.error(
                        "Error in publishing of node %r: destination %r is not a directory."
                        % (obj.id, dest.id))

        v = {}
        v["id"] = publishdir.id
        v["change"] = changes
        ret += req.getTAL("web/edit/modules/publish.html", v, macro="reload")

    # build normal window
    stddir = ""
    stdname = ""
    l = []
    for n in explicit:
        if str(getHomeDir(user).id) != str(n):
            l.append(n)

    if len(l) == 1:
        stddir = str(l[0]) + ","
        stdname = "- " + tree.getNode(l[0]).getName()

    #v = {"id":publishdir.id,"stddir":stddir, "stdname":stdname, "showdir":showdir(req, publishdir, publishwarn=0, markunpublished=1, nodes=[])}
    v = {
        "id":
        publishdir.id,
        "stddir":
        stddir,
        "stdname":
        stdname,
        "showdir":
        showdir(req, publishdir, publishwarn=None, markunpublished=1, nodes=[])
    }
    v["basedir"] = tree.getRoot('collections')
    v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s'" % (
        publishdir.id, publishdir.id)
    v["idstr"] = ids
    v["faultylist"] = actionerror
    ret += req.getTAL("web/edit/modules/publish.html", v, macro="publish_form")
    return ret
Ejemplo n.º 7
0
def getContent(req, ids):
    def getDatatypes(_req, _schemes):
        _dtypes = []
        datatypes = Data.get_all_datatypes()
        for scheme in _schemes:
            for dtype in scheme.getDatatypes():
                if dtype not in _dtypes:
                    for _t in datatypes:
                        #                         if _t.getName() == dtype and not elemInList(dtypes, _t.getName()):
                        dtypes.append(_t)
        _dtypes.sort(lambda x, y: cmp(
            translate(x.getLongName(), request=_req).lower(),
            translate(y.getLongName(), request=req).lower()))
        return _dtypes

    def get_ids_from_query():
        ids = get_ids_from_req(req)
        return ",".join(ids)

    node = q(Data).get(long(ids[0]))

    if "action" in req.params:
        if req.params.get('action') == "resort":
            field = req.params.get('value', '').strip()
            res = showdir(req, node, sortfield=field)
            res = json.dumps({
                'state': 'ok',
                'values': res
            },
                             ensure_ascii=False)
            req.write(res)
            return None

        elif req.params.get(
                'action') == "save":  # save selection for collection
            field = req.params.get('value')
            if field.strip() == "" or field.strip() == "off":
                if node.get('sortfield'):
                    node.removeAttribute('sortfield')
            else:
                node.set('sortfield', field)
            nodes_per_page = req.params.get('nodes_per_page')
            if nodes_per_page.strip() == "":
                if node.get('nodes_per_page'):
                    node.removeAttribute('nodes_per_page')
            else:
                node.set('nodes_per_page', nodes_per_page)
            req.write(json.dumps({'state': 'ok'}))
            db.session.commit()
        return None

    if node.isContainer():
        schemes = []
        dtypes = []

        item_count = []
        items = showdir(req, node, item_count=item_count)
        nav = shownav(req, node)
        v = {
            "operations": showoperations(req, node),
            "items": items,
            "nav": nav
        }
        if node.has_write_access():
            schemes = get_permitted_schemas()
            dtypes = getDatatypes(req, schemes)

        if "globalsort" in req.params:
            node.set("sortfield", req.params.get("globalsort"))
        if req.params.get("sortfield", "") != "":
            v['collection_sortfield'] = req.params.get("sortfield")
        else:
            v['collection_sortfield'] = node.get("sortfield")

        if req.params.get("nodes_per_page"):
            v['npp_field'] = req.params.get("nodes_per_page",
                                            default_edit_nodes_per_page)
        else:
            v['npp_field'] = node.get("nodes_per_page")
        if not v['npp_field']:
            v['npp_field'] = default_edit_nodes_per_page

        search_html = render_edit_search_box(node, lang(req), req, edit=True)
        searchmode = req.params.get("searchmode")
        navigation_height = searchbox_navlist_height(req, item_count)
        if not isinstance(node, (Root, Collections, Home)):
            sortchoices = _sort.get_sort_choices(container=node,
                                                 off="off",
                                                 t_off=t(req, "off"),
                                                 t_desc=t(req, "descending"))
        else:
            sortchoices = ()

        count = item_count[0] if item_count[0] == item_count[
            1] else "%d from %d" % (item_count[0], item_count[1])
        v['sortchoices'] = tuple(sortchoices)
        v['types'] = dtypes
        v['schemes'] = schemes
        v['id'] = ids[0]
        v['count'] = count
        v['language'] = lang(req)
        v['search'] = search_html
        v['navigation_height'] = navigation_height
        v['parent'] = node.id
        v['query'] = req.query.replace('id=', 'src=')
        searchparams = get_searchparams(req)
        searchparams = {
            k: unicode(v).encode("utf8")
            for k, v in searchparams.items()
        }
        v['searchparams'] = urllib.urlencode(searchparams)
        v['get_ids_from_query'] = get_ids_from_query
        v['edit_all_objects'] = t(lang(req),
                                  "edit_all_objects").format(item_count[1])
        v['t'] = t
        res = req.getTAL("web/edit/modules/content.html",
                         v,
                         macro="edit_content")
        delete_g_nodes_entry(req)
        return res
    if hasattr(node, "editContentDefault"):
        return node.editContentDefault(req)
    return ""
Ejemplo n.º 8
0
def getContent(req, ids):
    user = current_user
    publishdir = q(Node).get(ids[0])
    ret = ""

    actionerror = []
    changes = []
    if "dopublish" in req.params.keys():

        objlist = []
        for key in req.params.keys():
            if key.isdigit():
                objlist.append(key)
                src = q(Node).get(req.params.get("id"))

        for obj_id in objlist:
            remove_from_src = False
            obj = q(Node).get(obj_id)
            metadatatype = obj.metadatatype
            mask_validated = False
            for mask in metadatatype.getMasks(type="edit"): # check required fields
                if mask.has_read_access() and mask.getName() == obj.system_attrs.get("edit.lastmask"):
                    for f in mask.validateNodelist([obj]):
                        actionerror.append(f)
                    mask_validated = True

            if len(actionerror)>0: # object faulty
                continue

            if not mask_validated:
                msg = "user %r going to publish node %r without having validated edit.lastmask" % (user, obj)
                logg.warning(msg)
                # should we validate standard edit mask here?

            for dest_id in req.params.get("destination", "").split(","):
                if not dest_id: # no destination given
                    continue

                dest = q(Node).get(dest_id)

                # XXX: this error handling should be revised, I think...

                error = False
                if not src.has_read_access():
                    logg.error("Error in publishing of node %r: source position %r has no read access.", obj.id, src.id)
                    error = True
                if not dest.has_write_access():
                    logg.error("Error in publishing of node %r: destination %r has no write access.", obj.id, dest.id)
                    error = True
                if not obj.has_write_access():
                    logg.error("Error in publishing of node %r: object has no write access.", obj.id)
                    error = True
                if not isinstance(dest, Container):
                    logg.error("Error in publishing of node %r: destination %r is not a directory.", obj.id, dest.id)
                    error = True
                if dest == src:
                    logg.error("Error in publishing of node %r: destination %r is not a directory.", obj.id, dest.id)
                    error = True

                if not error:
                    if not obj.is_descendant_of(dest):
                        dest.children.append(obj)
                        remove_from_src = True

                        if dest.id not in changes:
                            changes.append(dest.id)
                        if src.id not in changes:
                            changes.append(src.id)
                        logg.info("%s published %s (%s, %s) from src %s (%s, %s) to dest %s (%s, %s)", user.login_name,
                                  obj.id, obj.name, obj.type,
                                  src.id, src.name, src.type,
                                  dest.id, dest.name, dest.type)
                    else:
                        error_str = "Error in publishing of node %s: Destination node %s is child of node." % (obj_id, dest.id)
                        actionerror.append((obj.id, error_str))
                        logg.error(error_str)

            if remove_from_src:
                try:
                    src.children.remove(obj)
                    db.session.commit()
                except:
                    error_str = "Error in publishing of node %s: Database error" % obj.id
                    logg.exception(error_str)
                    actionerror.append((obj.id, error_str))
                    

        v = {}
        v["id"] = publishdir.id
        v["change"] = changes
        ret += req.getTAL("web/edit/modules/publish.html", v, macro="reload")

    # build normal window
    stddir = ""  # preset value for destination ids
    stdname = ""

    v = {"id": publishdir.id,
         "stddir": stddir,
         "stdname": stdname,
         "showdir": showdir(req,
                            publishdir,
                            publishwarn=None,
                            markunpublished=1,
                            faultyidlist=[id for (id, error_str) in actionerror]),
         "basedir": q(Collections).one(),
         "script": "var currentitem = '%s';\nvar currentfolder = '%s'" % (publishdir.id, publishdir.id), "idstr": ids,
         "faultyerrlist": [error_str for (id, error_str) in actionerror]}

    ret += req.getTAL("web/edit/modules/publish.html", v, macro="publish_form")
    return ret
Ejemplo n.º 9
0
def getContent(req, ids):
    class SortChoice:
        def __init__(self, label, value):
            self.label = label
            self.value = value

    def getSchemes(_req):
        return filter(lambda x: x.isActive(),
                      acl.AccessData(_req).filter(loadTypesFromDB()))

    def getDatatypes(_req, _schemes):
        _dtypes = []
        datatypes = loadAllDatatypes()
        for scheme in _schemes:
            for dtype in scheme.getDatatypes():
                if dtype not in _dtypes:
                    for _t in datatypes:
                        if _t.getName() == dtype and not elemInList(
                                dtypes, _t.getName()):
                            dtypes.append(_t)
        _dtypes.sort(lambda x, y: cmp(
            translate(x.getLongName(), request=_req).lower(),
            translate(y.getLongName(), request=req).lower()))
        return _dtypes

    node = tree.getNode(ids[0])

    if "action" in req.params:
        if req.params.get('action') == "resort":
            _dir = "up"
            field = req.params.get('value', '').strip()
            nl = list(node.getChildren())
            if field:
                if field[0] == "-":
                    field = field[1:]
                    _dir = "down"
                nl.sort(lambda x, y: cmp(
                    x.get(field).lower(),
                    y.get(field).lower()))
                if _dir == "down":
                    nl.reverse()
            req.write(
                json.dumps({
                    'state':
                    'ok',
                    'values':
                    showdir(req, node, nodes=nl, sortfield_from_req=field)
                }))
            return None

        elif req.params.get(
                'action') == "save":  # save selection for collection
            field = req.params.get('value')
            if field.strip() == "":
                node.removeAttribute('sortfield')
            else:
                node.set('sortfield', field)
            req.write(
                json.dumps({
                    'state':
                    'ok',
                    'message':
                    translate('edit_content_save_order', request=req)
                }))
        return None

    if node.isContainer():
        schemes = []
        dtypes = []

        v = {
            "operations": showoperations(req, node),
            "items": showdir(req, node)
        }
        access = acl.AccessData(req)
        if access.hasWriteAccess(node):
            schemes = getSchemes(req)
            dtypes = getDatatypes(req, schemes)

        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"]:
            try:
                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
            except TypeError:
                pass
        v['sortchoices'] = sortfields
        v['types'] = dtypes
        v['schemes'] = schemes
        v['id'] = ids[0]
        v['count'] = len(node.getContentChildren())
        v['language'] = lang(req)
        v['t'] = t
        return req.getTAL("web/edit/modules/content.html",
                          v,
                          macro="edit_content")
    if hasattr(node, "editContentDefault"):
        return node.editContentDefault(req)
    return ""
Ejemplo n.º 10
0
                    sort_fields = metadatatype.metafields.filter(Node.a.opts.like("%o%")).all()
                    if sort_fields:
                        for sortfield in sort_fields:
                            sortfields += [SortChoice(sortfield.getLabel(), sortfield.name)]
                            sortfields += [SortChoice(sortfield.getLabel() + translation_t(req, "descending"), "-" + sortfield.name)]
                        break

        v['sortchoices'] = sortfields
        v['npp_choices'] = [SortChoice(str(x), x) for x in edit_node_per_page_values]
        v['language'] = lang(req)
        v['t'] = translation_t

    search_html = render_search_box(q(Node).get(ids[0]), language, req, edit=True)
    searchmode = req.params.get("searchmode")
    item_count = []
    items = showdir(req, node, sortfield=req.params.get("sortfield"), item_count=item_count)
    nav = shownav(req, node, sortfield=req.params.get("sortfield"))
    navigation_height = searchbox_navlist_height(req, item_count)
    count = item_count[0] if item_count[0] == item_count[1] else "%d from %d" % (item_count[0], item_count[1])
    searchparams = get_searchparams(req)
    searchparams = {k: unicode(v).encode("utf8") for k, v in searchparams.items()}

    v.update({
        "id": req.params.get("id"),
        "sid": req.session.id,
        "datatypes": getDatatypes(req, schemes),
        "schemes": schemes,
        "uploadstate": req.params.get("upload"),
        "operations": showoperations(req, node),
        "nodelist": items,
        "nav": nav,
Ejemplo n.º 11
0
def getContent(req, ids):

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

    def getDatatypes(_req, _schemes):
        _dtypes = []
        datatypes = Data.get_all_datatypes()
        for scheme in _schemes:
            for dtype in scheme.getDatatypes():
                if dtype not in _dtypes:
                    for _t in datatypes:
#                         if _t.getName() == dtype and not elemInList(dtypes, _t.getName()):
                        dtypes.append(_t)
        _dtypes.sort(lambda x, y: cmp(translate(x.getLongName(), request=_req).lower(), translate(y.getLongName(), request=req).lower()))
        return _dtypes

    def get_ids_from_query():
        ids = get_ids_from_req(req)
        return ",".join(ids)

    node = q(Data).get(long(ids[0]))

    if "action" in req.params:
        if req.params.get('action') == "resort":
            field = req.params.get('value', '').strip()
            res = showdir(req, node, sortfield=field)
            res = json.dumps({'state': 'ok', 'values': res}, ensure_ascii=False)
            req.write(res)
            return None

        elif req.params.get('action') == "save":  # save selection for collection
            field = req.params.get('value')
            if field.strip() == "" or field.strip() == "off":
                if node.get('sortfield'):
                    node.removeAttribute('sortfield')
            else:
                node.set('sortfield', field)
            nodes_per_page = req.params.get('nodes_per_page')
            if nodes_per_page.strip() == "":
                if node.get('nodes_per_page'):
                    node.removeAttribute('nodes_per_page')
            else:
                node.set('nodes_per_page', nodes_per_page)
            req.write(json.dumps({'state': 'ok'}))
            db.session.commit()
        return None

    if node.isContainer():
        schemes = []
        dtypes = []

        item_count = []
        items = showdir(req, node, item_count=item_count)
        nav = shownav(req, node)
        v = {"operations": showoperations(req, node), "items": items, "nav": nav}
        if node.has_write_access():
            schemes = get_permitted_schemas()
            dtypes = getDatatypes(req, schemes)

        col = node
        if "globalsort" in req.params:
            col.set("sortfield", req.params.get("globalsort"))
        if req.params.get("sortfield", "") != "":
            v['collection_sortfield'] = req.params.get("sortfield")
        else:
            v['collection_sortfield'] = node.get("sortfield")
        if req.params.get("nodes_per_page"):
            v['npp_field'] = req.params.get("nodes_per_page", default_edit_nodes_per_page)
        else:
            v['npp_field'] = node.get("nodes_per_page")
        if not v['npp_field']:
            v['npp_field'] = default_edit_nodes_per_page
        sort_choices = [SortChoice(t(req, "off"), "off")]
        search_html = render_search_box(node, lang(req), req, edit=True)
        searchmode = req.params.get("searchmode")
        navigation_height = searchbox_navlist_height(req, item_count)
        if not isinstance(col, (Root, Collections, Home)):
            # for node in col.children:
            count = col.content_children_for_all_subcontainers.count()
            # the transformation of content_children_for_all_subcontainers in a list is very expensive if count is high
            # so try a limitation and if no sortfields found then increase limitation
            start_idx = 0
            end_idx = 10
            sortfields = None
            while start_idx < count:
                for node in col.content_children_for_all_subcontainers[start_idx:end_idx]:
                    # XXX: now without acl filtering, do we need this?
                    sortfields = node.getSortFields()
                    if sortfields:
                        for sortfield in sortfields:
                            sort_choices += [SortChoice(sortfield.getLabel(), sortfield.getName())]
                            sort_choices += [SortChoice(sortfield.getLabel() + t(req, "descending"), "-" + sortfield.getName())]
                        break
                if sortfields:
                    break
                start_idx = end_idx
                end_idx *= 10

        count = item_count[0] if item_count[0] == item_count[1] else "%d from %d" % (item_count[0], item_count[1])
        v['sortchoices'] = sort_choices
        v['npp_choices'] = [SortChoice(str(x), x) for x in edit_node_per_page_values]
        v['types'] = dtypes
        v['schemes'] = schemes
        v['id'] = ids[0]
        v['count'] = count
        v['language'] = lang(req)
        v['search'] = search_html
        v['navigation_height'] = navigation_height
        v['parent'] = col.id
        v['query'] = req.query.replace('id=','src=')
        searchparams = get_searchparams(req)
        searchparams = {k: unicode(v).encode("utf8") for k, v in searchparams.items()}
        v['searchparams'] = urllib.urlencode(searchparams)
        v['get_ids_from_query'] = get_ids_from_query
        v['edit_all_objects'] = t(lang(req), "edit_all_objects").format(item_count[1])
        v['t'] = t
        res = req.getTAL("web/edit/modules/content.html", v, macro="edit_content")
        delete_g_nodes_entry(req)
        return res
    if hasattr(node, "editContentDefault"):
        return node.editContentDefault(req)
    return ""
Ejemplo n.º 12
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    publishdir = tree.getNode(ids[0])
    explicit = tree.getNodesByAttribute("writeaccess", user.getName())
    ret = ""

    actionerror = []
    changes = []
    if "dopublish" in req.params.keys():
        access = AccessData(req)

        objlist = []
        for key in req.params.keys():
            if key.isdigit():
                objlist.append(key)
                src = tree.getNode(req.params.get("id"))

        for obj_id in objlist:
            faultylist = []
            obj = tree.getNode(obj_id)
            for mask in obj.getType().getMasks(type="edit"): # check required fields
                if access.hasReadAccess(mask) and mask.getName()==obj.get("edit.lastmask"):
                    for f in mask.validateNodelist([obj]):
                        faultylist.append(f)

            if len(faultylist)>0: # object faulty
                actionerror.append(obj_id)
                continue

            for dest_id in req.params.get("destination", "").split(","):
                if dest_id=="": # no destination given
                    continue

                dest = tree.getNode(dest_id)
                if dest != src and access.hasReadAccess(src) and access.hasWriteAccess(dest) and access.hasWriteAccess(obj) and isDirectory(dest):
                        if not nodeIsChildOfNode(dest,obj):
                            dest.addChild(obj)
                            src.removeChild(obj)

                            if dest.id not in changes:
                                changes.append(dest.id)
                            if src.id not in changes:
                                changes.append(src.id)
                            log.info("%s published %s (%r, %r) from src %s (%r, %r) to dest %s (%r, %r)" % (
                                      user.getName(),
                                      obj.id, obj.name, obj.type,
                                      src.id, src.name, src.type,
                                      dest.id, dest.name, dest.type,))
                        else:
                            actionerror.append(obj.id)
                            log.error("Error in publishing of node %r: Destination node %r is child of node." % (obj_id, dest.id))

                if not access.hasReadAccess(src):
                    log.error("Error in publishing of node %r: source position %r has no read access." % (obj.id, src.id))
                if not access.hasWriteAccess(dest):
                    log.error("Error in publishing of node %r: destination %r has no write access." % (obj.id, dest.id))
                if not access.hasWriteAccess(obj):
                    log.error("Error in publishing of node %r: object has no write access." % obj.id)
                if not isDirectory(dest):
                    log.error("Error in publishing of node %r: destination %r is not a directory." % (obj.id, dest.id))

        v = {}
        v["id"] = publishdir.id
        v["change"] = changes
        ret += req.getTAL("web/edit/modules/publish.html", v, macro="reload")

    # build normal window
    stddir = ""
    stdname = ""
    l = []
    for n in explicit:
        if str(getHomeDir(user).id)!=str(n):
            l.append(n)

    if len(l)==1:
        stddir = str(l[0])+","
        stdname = "- " + tree.getNode(l[0]).getName()

    #v = {"id":publishdir.id,"stddir":stddir, "stdname":stdname, "showdir":showdir(req, publishdir, publishwarn=0, markunpublished=1, nodes=[])}
    v = {"id":publishdir.id,"stddir":stddir, "stdname":stdname, "showdir":showdir(req, publishdir, publishwarn=None, markunpublished=1, nodes=[])}
    v["basedir"] = tree.getRoot('collections')
    v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s'" %(publishdir.id, publishdir.id)
    v["idstr"] = ids
    v["faultylist"] = actionerror
    ret += req.getTAL("web/edit/modules/publish.html", v, macro="publish_form")
    return ret
Ejemplo n.º 13
0
def getContent(req, ids):
    class SortChoice:
        def __init__(self, label, value):
            self.label = label
            self.value = value

    def getDatatypes(_req, _schemes):
        _dtypes = []
        datatypes = Data.get_all_datatypes()
        for scheme in _schemes:
            for dtype in scheme.getDatatypes():
                if dtype not in _dtypes:
                    for _t in datatypes:
                        #                         if _t.getName() == dtype and not elemInList(dtypes, _t.getName()):
                        dtypes.append(_t)
        _dtypes.sort(lambda x, y: cmp(
            translate(x.getLongName(), request=_req).lower(),
            translate(y.getLongName(), request=req).lower()))
        return _dtypes

    def get_ids_from_query():
        ids = get_ids_from_req(req)
        return ",".join(ids)

    node = q(Data).get(long(ids[0]))

    if "action" in req.params:
        if req.params.get('action') == "resort":
            field = req.params.get('value', '').strip()
            res = showdir(req, node, sortfield=field)
            res = json.dumps({
                'state': 'ok',
                'values': res
            },
                             ensure_ascii=False)
            req.write(res)
            return None

        elif req.params.get(
                'action') == "save":  # save selection for collection
            field = req.params.get('value')
            if field.strip() == "" or field.strip() == "off":
                if node.get('sortfield'):
                    node.removeAttribute('sortfield')
            else:
                node.set('sortfield', field)
            nodes_per_page = req.params.get('nodes_per_page')
            if nodes_per_page.strip() == "":
                if node.get('nodes_per_page'):
                    node.removeAttribute('nodes_per_page')
            else:
                node.set('nodes_per_page', nodes_per_page)
            req.write(json.dumps({'state': 'ok'}))
            db.session.commit()
        return None

    if node.isContainer():
        schemes = []
        dtypes = []

        item_count = []
        items = showdir(req, node, item_count=item_count)
        nav = shownav(req, node)
        v = {
            "operations": showoperations(req, node),
            "items": items,
            "nav": nav
        }
        if node.has_write_access():
            schemes = get_permitted_schemas()
            dtypes = getDatatypes(req, schemes)

        col = node
        if "globalsort" in req.params:
            col.set("sortfield", req.params.get("globalsort"))
        if req.params.get("sortfield", "") != "":
            v['collection_sortfield'] = req.params.get("sortfield")
        else:
            v['collection_sortfield'] = node.get("sortfield")
        if req.params.get("nodes_per_page"):
            v['npp_field'] = req.params.get("nodes_per_page",
                                            default_edit_nodes_per_page)
        else:
            v['npp_field'] = node.get("nodes_per_page")
        if not v['npp_field']:
            v['npp_field'] = default_edit_nodes_per_page
        sort_choices = [SortChoice(t(req, "off"), "off")]
        search_html = render_search_box(node, lang(req), req, edit=True)
        searchmode = req.params.get("searchmode")
        navigation_height = searchbox_navlist_height(req, item_count)
        if not isinstance(col, (Root, Collections, Home)):
            # for node in col.children:
            count = col.content_children_for_all_subcontainers.count()
            # the transformation of content_children_for_all_subcontainers in a list is very expensive if count is high
            # so try a limitation and if no sortfields found then increase limitation
            start_idx = 0
            end_idx = 10
            sortfields = None
            while start_idx < count:
                for node in col.content_children_for_all_subcontainers[
                        start_idx:end_idx]:
                    # XXX: now without acl filtering, do we need this?
                    sortfields = node.getSortFields()
                    if sortfields:
                        for sortfield in sortfields:
                            sort_choices += [
                                SortChoice(sortfield.getLabel(),
                                           sortfield.getName())
                            ]
                            sort_choices += [
                                SortChoice(
                                    sortfield.getLabel() +
                                    t(req, "descending"),
                                    "-" + sortfield.getName())
                            ]
                        break
                if sortfields:
                    break
                start_idx = end_idx
                end_idx *= 10

        count = item_count[0] if item_count[0] == item_count[
            1] else "%d from %d" % (item_count[0], item_count[1])
        v['sortchoices'] = sort_choices
        v['npp_choices'] = [
            SortChoice(str(x), x) for x in edit_node_per_page_values
        ]
        v['types'] = dtypes
        v['schemes'] = schemes
        v['id'] = ids[0]
        v['count'] = count
        v['language'] = lang(req)
        v['search'] = search_html
        v['navigation_height'] = navigation_height
        v['parent'] = col.id
        v['query'] = req.query.replace('id=', 'src=')
        searchparams = get_searchparams(req)
        searchparams = {
            k: unicode(v).encode("utf8")
            for k, v in searchparams.items()
        }
        v['searchparams'] = urllib.urlencode(searchparams)
        v['get_ids_from_query'] = get_ids_from_query
        v['edit_all_objects'] = t(lang(req),
                                  "edit_all_objects").format(item_count[1])
        v['t'] = t
        res = req.getTAL("web/edit/modules/content.html",
                         v,
                         macro="edit_content")
        delete_g_nodes_entry(req)
        return res
    if hasattr(node, "editContentDefault"):
        return node.editContentDefault(req)
    return ""