Esempio n. 1
0
def showdir(req, node, publishwarn="auto", markunpublished=0, nodes=[], sortfield_from_req=None):
    if publishwarn == "auto":
        user = users.getUserFromRequest(req)
        homedir = getHomeDir(user)
        homedirs = getAllSubDirs(homedir)
        publishwarn = node in homedirs
    if not nodes:
        nodes = node.getChildren()
    if sortfield_from_req and sortfield_from_req is not None:
        msg = "%r, %r, sorted by sortfield_from_req=%r" % (
            __name__, funcname(), sortfield_from_req)
        logger.debug(msg)
    elif sortfield_from_req is None:
        collection_sortfield = node.get("sortfield")
        if collection_sortfield:
            nodes = tree.NodeList([n.id for n in nodes]).sort_by_fields(
                [collection_sortfield])
            msg = "%r, %r, sorted by collection_sortfield=%r" % (
                __name__, funcname(), collection_sortfield)
            logger.debug(msg)
    else:
        msg = "%r, %r, *not* sorted" % (__name__, funcname())
        logger.debug(msg)

    nodes = tree.NodeList([n.id for n in nodes if not n.type == 'shoppingbag'])
    return shownodelist(req, nodes, publishwarn=publishwarn, markunpublished=markunpublished, dir=node)
Esempio n. 2
0
def showdir(req,
            node,
            publishwarn="auto",
            markunpublished=0,
            nodes=[],
            sortfield_from_req=None):
    if publishwarn == "auto":
        user = users.getUserFromRequest(req)
        homedir = getHomeDir(user)
        homedirs = getAllSubDirs(homedir)
        publishwarn = node in homedirs
    if not nodes:
        nodes = node.getChildren()
    if sortfield_from_req and sortfield_from_req is not None:
        msg = "%r, %r, sorted by sortfield_from_req=%r" % (
            __name__, funcname(), sortfield_from_req)
        logger.debug(msg)
    elif sortfield_from_req is None:
        collection_sortfield = node.get("sortfield")
        if collection_sortfield:
            nodes = tree.NodeList([n.id for n in nodes
                                   ]).sort_by_fields([collection_sortfield])
            msg = "%r, %r, sorted by collection_sortfield=%r" % (
                __name__, funcname(), collection_sortfield)
            logger.debug(msg)
    else:
        msg = "%r, %r, *not* sorted" % (__name__, funcname())
        logger.debug(msg)

    nodes = tree.NodeList([n.id for n in nodes if not n.type == 'shoppingbag'])
    return shownodelist(req,
                        nodes,
                        publishwarn=publishwarn,
                        markunpublished=markunpublished,
                        dir=node)
Esempio n. 3
0
def content(req):

    user = current_user
    language = lang(req)

    if not user.is_editor:
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    if 'id' in req.params and len(req.params) == 1:
        nid = long(req.params.get('id'))
        node = q(Data).get(nid)

        if node is not None:
            cmd = "cd (%s %r, %r)" % (nid, node.name, node.type)
            logg.info("%s: %s", user.login_name, cmd)
        else:
            cmd = "ERROR-cd to non-existing id=%r" % nid
            logg.error("%s: %s", user.login_name, cmd)

    if 'action' in req.params and req.params['action'] == 'upload':
        pass

    content = {'script': '', 'body': ''}
    v = {'dircontent': '', 'notdirectory': 0, 'operations': ''}
    try:
        v['nodeiconpath'] = getEditorIconPath(node)
    except:
        v['nodeiconpath'] = "webtree/directory.gif"

    path = req.path[1:].split("/")
    if len(path) >= 4:
        req.params["style"] = "popup"
        req.params["id"] = path[1]
        req.params["tab"] = path[2]
        req.params["option"] = path[3]
    getEditModules()

    if not user.is_editor:
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    # remove all caches for the frontend area- we might make changes there
    for sessionkey in ["contentarea", "navframe"]:
        with suppress(Exception, warn=False):
            del req.session[sessionkey]

    ids = getIDs(req)

    if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload":
        return upload_help(req)

    if len(ids) > 0:
        if ids[0] == "all":
            ids = get_ids_from_req(req)
        node = q(Node).get(long(ids[0]))
    tabs = "content"
    if isinstance(node, Root):
        tabs = "content"
    elif node is user.upload_dir:
        tabs = "upload"
    else:
        tabs = node.get_default_edit_tab()
        v["notdirectory"] = 0

    current = req.params.get("tab", tabs)
    logg.debug("... %s inside %s.%s: ->  !!! current = %s !!!", get_user_id(req), __name__, funcname(), current)
    msg = "%s selected editor module is %s" % (user.login_name, current)
    jsfunc = req.params.get("func", "")
    if jsfunc:
        msg = msg + (', js-function: %r' % jsfunc)
    logg.info(msg)

    # some tabs operate on only one file
    # if current in ["files", "view", "upload"]:
    if current in ["files", "upload"]:
        ids = ids[0:1]

    # display current images
    if not isinstance(q(Data).get(ids[0]), Container):
        v["notdirectory"] = 1
        items = []
        if current != "view":
            for id in ids:
                node = q(Data).get(id)
                if hasattr(node, "show_node_image"):
                    if not isDirectory(node) and not node.isContainer():
                        items.append((id, node.show_node_image()))
                    else:
                        items.append(("", node.show_node_image()))
        v["items"] = items
        if logg.isEnabledFor(logging.DEBUG):
            logg.debug("... %s inside %s.%s: -> display current images: items: %s",
                       get_user_id(req), __name__, funcname(), [_t[0] for _t in items])

        nid = req.params.get('src', req.params.get('id'))
        if nid is None:
            raise ValueError("invalid request, neither 'src' not 'id' parameter is set!")

        folders_only = False
        if nid.find(',') > 0:
            # more than one node selected
            # use the first one for activateEditorTreeNode
            # and display only folders
            nid = nid.split(',')[0]
            folders_only = True
        n = q(Data).get(nid)
        if current == 'metadata' and 'save' in req.params:
            pass
        s = []
        while n:
            if not folders_only:
                s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                     (n.id, n.id, get_edit_label(n, language))] + s

            folders_only = False;
            p = n.parents
            # XXX: we only check the first parent. This is wrong, how could be solve this? #
            first_parent = p[0]
            if isinstance(first_parent, Data) and first_parent.has_read_access():
                n = p[0]
            else:
                n = None
        v["dircontent"] = ' <b>&raquo;</b> '.join(s)

    else:  # or current directory
        n = q(Data).get(long(ids[0]))
        s = []
        while n:
            if len(s) == 0:
                s = ['%s' % (get_edit_label(n, language))]
            else:
                s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                     (n.id, n.id, get_edit_label(n, language))] + s

            p = n.parents
            if p and not isinstance(p[0], Root):
                n = p[0]
            else:
                n = None
        v["dircontent"] = ' <b>&raquo;</b> '.join(s)

    if current == "globals":
        basedir = config.get("paths.datadir")
        file_to_edit = None

        if "file_to_edit" in req.params:
            file_to_edit = req.params["file_to_edit"]

        if not file_to_edit:
            # todo: getstartpagedict doesnt exist
            d = node.getStartpageDict()
            if d and language in d:
                file_to_edit = d[language]

        found = False
        for f in node.files:
            if f.mimetype == 'text/html':
                filepath = f.abspath.replace(basedir, '')
                if file_to_edit == filepath:
                    found = True
                    break

    else:
        t2 = current.split("_")[-1]
        if t2 in editModules.keys():
            c = editModules[t2].getContent(req, ids)

            if isinstance(c, int):
                # module returned a custom http status code instead of HTML content
                return c

            elif c:
                content["body"] += c
            else:
                logg.debug('empty content')
                return
        else:
            req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
            content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error")

    if req.params.get("style", "") != "popup":  # normal page with header
        v["tabs"] = handletabs(req, ids, tabs)
        v["script"] = content["script"]
        v["body"] = content["body"]
        v["paging"] = showPaging(req, current, ids)
        v["node"] = node
        v["ids"] = req.params.get("ids", "").split(",")
        if req.params.get("ids", "") == "":
            v["ids"] = req.params.get("id", "").split(",")
        v["tab"] = current
        v["operations"] = req.getTAL("web/edit/edit_common.html", {'iscontainer': node.isContainer()}, macro="show_operations")
        v['user'] = user
        v['language'] = lang(req)
        v['t'] = t

        # add icons to breadcrumbs
        ipath = 'webtree/directory.gif'
        if node and node.isContainer():
            if node.name == 'home' or 'Arbeitsverzeichnis' in node.name or node == current_user.home_dir:
                ipath = 'webtree/homeicon.gif'
            elif node.name in ('Uploads', 'upload'):
                ipath = 'webtree/uploadicon.gif'
            elif node.name in ('Papierkorb', 'trash'):
                ipath = 'webtree/trashicon.gif'
            else:
                ipath = getEditorIconPath(node)

        v["dircontent"] += '&nbsp;&nbsp;<img src="' + '/img/' + ipath + '" />'

        return req.writeTAL("web/edit/edit.html", v, macro="frame_content")
Esempio n. 4
0
def _handle_edit_metadata(req, mask, nodes):
    # check and save items
    user = current_user
    userdir = user.home_dir
    flag_nodename_changed = -1
    form = req.form

    for node in nodes:
        if not node.has_write_access() or node is userdir:
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    if not hasattr(mask, "i_am_not_a_mask"):
        if form.get('generate_new_version'):
            # Create new node version
            comment = u'({})\n{}'.format(t(req, "document_new_version_comment"), form.get('version_comment', ''))

            for node in nodes:
                with node.new_tagged_version(comment=comment, user=user):
                    mask.update_node(node, req, user)
        else:
            # XXX: why check here?
            # if nodes:
            old_nodename = nodes[0].name

            for node in nodes:
                mask.update_node(node, req, user)

            db.session.commit()

            # XXX: why check here?
            # if nodes:
            new_nodename = nodes[0].name
            if ( len(nodes) == 1 or old_nodename != new_nodename) and isinstance(nodes[0], Container):
                # for updates of node label in editor tree
                flag_nodename_changed = ustr(nodes[0].id)

    else:
        for field in mask.metaFields():
            logg.debug("in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %s, field.id: %s, field.name: %s, mask: %s, maskname: %s",
                __name__, funcname(), field, field.id, field.name, mask, mask.name)
            field_name = field.name
            if field_name == 'nodename' and mask.name == 'settings':
                if '__nodename' in form:
                    field_name = '__nodename'  # no multilang here !
                elif getDefaultLanguage() + '__nodename' in form:
                    # no multilang here !
                    field_name = getDefaultLanguage() + '__nodename'
                value = form.get(field_name, None)
                if value:
                    if value != node.name:
                        flag_nodename_changed = ustr(node.id)
                    for node in nodes:
                        node.name = value
            value = form.get(field_name, None)
            if value is not None:
                for node in nodes:
                    node.set(field.name, value)
            else:
                node.set(field.getName(), "")
        db.session.commit()

    return flag_nodename_changed
Esempio n. 5
0
def getContent(req, ids):

    user = users.getUserFromRequest(req)
    access = AccessData(user=user)
    language = lang(req)

    if "action" in req.params:
        state = 'ok'

        if req.params.get('action') == "removefiles":
            basenode = tree.getNode(req.params.get('id'))
            for f in basenode.getFiles():
                try:
                    os.remove(f.retrieveFile())
                    pass
                except:
                    state = "error"
            for f in basenode.getFiles():
                basenode.removeFile(f)
            req.write(json.dumps({'state': state}))
            return None

        if req.params.get('action') == "buildnode":  # create nodes
            basenode = tree.getNode(req.params.get('id'))
            newnodes = []
            errornodes = []
            basenodefiles_processed = []
            if req.params.get('uploader', '') == 'plupload':
                filename2scheme = {}
                for k in req.params:
                    if k.startswith("scheme_"):
                        filename2scheme[
                            k.replace('scheme_', '', 1)] = req.params.get(k)

                for f in basenode.getFiles():
                    filename = f.getName()
                    if filename in filename2scheme:
                        _m = getMimeType(filename)

                        if _m[1] == "bibtex":  # bibtex import handler
                            try:
                                nn = importBibTeX(f.retrieveFile(), basenode)
                                newnodes.append(nn.id)
                                basenodefiles_processed.append(f)
                            except ValueError, e:
                                errornodes.append((filename, str(e)))

                        logger.debug("filename: %r, mimetype: %r" % (filename, _m))
                        logger.debug("__name__=%r, func=%r; _m=%r, _m[1]=%r" % (__name__, funcname(), _m, _m[1]))

                        node_type = '%s/%s' % (_m[1], filename2scheme[filename])

                        n = tree.Node(filename, type=node_type)

                        basenode.addChild(n)
                        n.set("creator", user.getName())
                        n.set("creationtime",  str(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time()))))

                        n.addFile(f)

                        n.event_files_changed()
                        clearFromCache(n)
                        newnodes.append(n.id)
                        basenodefiles_processed.append(f)
                        basenode.removeFile(f)
                        msg_t = (user.getName(), n.id, n.name, n.type,filename, basenode.id, basenode.name, basenode.type)
                        msg = "%s created new node id=%r (name=%r, type=%r) by uploading file %r, node is child of base node id=%r (name=%r, type=%r)" % msg_t
                        logger.info(msg)
                        logging.getLogger('usertracing').info(msg)

            else:
                for filename in req.params.get('files').split('|'):
                    _m = getMimeType(filename)
                    logger.debug("... in %s.%s: getMimeType(filename=%r)=%r" % (__name__, funcname(), filename, _m))
                    fs = basenode.getFiles()
                    logger.debug("... in %s.%s: basenode.id=%r, basenode_files: %r" % (__name__, funcname(), basenode.id, [(x.getName(), x.retrieveFile()) for x in fs]))
                    if _m[1] == req.params.get('type') or req.params.get('type') == 'file':
                        for f in basenode.getFiles():
                            # ambiguity here ?
                            if f.retrieveFile().endswith(filename):
                                # bibtex import handler
                                if _m[1] == "bibtex" and not req.params.get('type') == 'file':
                                    try:
                                        nn = importBibTeX(f.retrieveFile(), basenode)
                                        newnodes.append(nn.id)
                                        basenodefiles_processed.append(f)
                                    except ValueError, e:
                                        errornodes.append((filename, str(e)))
                                else:

                                    logger.debug("creating new node: filename: %r" % filename)
                                    logger.debug("files at basenode: %r" % [(x.getName(), x.retrieveFile()) for x in basenode.getFiles()])

                                    n = tree.Node(filename, type='%s/%s' % (req.params.get('type'), req.params.get('value')))
                                    basenode.addChild(n)
                                    n.set("creator", user.getName())
                                    n.set("creationtime",  str(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time()))))
                                    # clones to a file with random name
                                    cloned_file = f.clone(None)
                                    n.addFile(cloned_file)
                                    if hasattr(n, 'event_files_changed'):
                                        n.event_files_changed()
                                    clearFromCache(n)
                                    newnodes.append(n.id)
                                    basenodefiles_processed.append(f)
                                    msg_t = (user.getName(), n.id, n.name, n.type, filename, basenode.id, basenode.name, basenode.type)
                                    msg = "%s created new node id=%r (name=%r, type=%r) by uploading file %r, node is child of base node id=%r (name=%r, type=%r)" % msg_t
                                    logger.info(msg)
                                    logging.getLogger('usertracing').info(msg)
                                    break  # filename may not be unique

            new_tree_labels = [{'id': basenode.id, 'label': getTreeLabel(basenode, lang=language)}]
            for f in basenodefiles_processed:
                basenode.removeFile(f)
                f_path = f.retrieveFile()
                if os.path.exists(f_path):
                    logger.debug("%s going to remove file %r from disk" % (user.getName(), f_path))
                    os.remove(f_path)

            mime = getMimeType(filename)
            scheme_type = {mime[1]: []}
            for scheme in getSchemes(req):
                if mime[1] in scheme.getDatatypes():
                    scheme_type[mime[1]].append(scheme)
                    # break

            # standard file
            content = req.getTAL('web/edit/modules/upload.html', {'files': [filename], 'schemes': scheme_type}, macro="uploadfileok")

            res = json.dumps({'state': state, 'newnodes': newnodes, 'errornodes':
                              errornodes, 'new_tree_labels': new_tree_labels, 'ret': content})
            req.write(res)
            return None
Esempio n. 6
0
            basenode.addChild(n)
            n.set("creator", user.getName())
            n.set("creationtime",  str(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time()))))
            clearFromCache(n)
            msg_t = (user.getName(), n.id, n.name, n.type, basenode.id, basenode.name, basenode.type)
            msg = "%s created new node %r (%r, %r) using upload metadata form, node is child of base node %r (%r, %r)" % msg_t
            logger.info(msg)
            req.write(json.dumps({'newid': n.id, 'id': req.params.get('id')}))
            return None

        # create node using given identifier (doi, ...)
        if req.params.get('action') == "obj_from_identifier":
            identifier_importer = req.params.get('identifier_importer')
            identifier = req.params.get('identifier')

            msg = "... in %s.%s: going to create new node without file from identifier (%r)" % (__name__, funcname(), identifier)
            logger.debug(msg)

            if identifier_importer in identifier_importers:
                identifierImporter = identifier_importers[identifier_importer]
                importer_func = identifierImporter.importer_func

                user = users.getUserFromRequest(req)
                importdir = users.getUploadDir(user)

                new_node = importer_func(identifier, importdir, req=req)

                res = {'id': req.params.get('id'), 'error': req.params.get('error', ''), 'connect_error_msg': req.params.get('connect_error_msg', '')}

                if new_node:
                    new_node.set("creator", user.getName())
Esempio n. 7
0
def getContent(req, ids):

    user = users.getUserFromRequest(req)
    language = lang(req)

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

    if "action" in req.params:
        state = 'ok'

        if req.params.get('action') == "removefiles":
            basenode = q(Node).get(req.params.get('id'))
            for f in basenode.files:
                try:
                    os.remove(f.abspath)
                    pass
                except:
                    state = "error"
            basenode.files = []
            db.session.commit()
            req.write(json.dumps({'state': state}, ensure_ascii=False))
            return None

        if req.params.get('action') == "buildnode":  # create nodes
            basenode = q(Node).get(req.params.get('id'))
            newnodes = []
            errornodes = []
            basenodefiles_processed = []
            if req.params.get('uploader', '') == 'plupload':
                filename2scheme = {}
                for k in req.params:
                    if k.startswith("scheme_"):
                        filename2scheme[k.replace('scheme_', '',
                                                  1)] = req.params.get(k)

                for f in basenode.files:
                    filename = f.name
                    if filename in filename2scheme:
                        mimetype = getMimeType(filename)

                        if mimetype[1] == "bibtex":  # bibtex import handler
                            try:
                                new_node = importBibTeX(f.abspath, basenode)
                                newnodes.append(new_node.id)
                                basenodefiles_processed.append(f)
                            except ValueError, e:
                                errornodes.append((filename, unicode(e)))

                        logg.debug("filename: %s, mimetype: %s", filename,
                                   mimetype)
                        logg.debug("__name__=%s, func=%s; _m=%s, _m[1]=%s",
                                   __name__, funcname(), mimetype, mimetype[1])

                        content_class = Node.get_class_for_typestring(
                            mimetype[1])
                        node = content_class(name=filename,
                                             schema=filename2scheme[filename])

                        basenode.children.append(node)
                        node.set("creator", user.login_name)
                        node.set(
                            "creationtime",
                            unicode(
                                time.strftime('%Y-%m-%dT%H:%M:%S',
                                              time.localtime(time.time()))))
                        # set filetype for uploaded file as requested by the content class
                        f.filetype = content_class.get_upload_filetype()
                        node.files.append(f)
                        node.event_files_changed()
                        newnodes.append(node.id)
                        basenodefiles_processed.append(f)
                        basenode.files.remove(f)
                        db.session.commit()
                        logg.info(
                            "%s created new node id=%s (name=%s, type=%s) by uploading file %s, "
                            "node is child of base node id=%s (name=%s, type=%s)",
                            user.login_name, node.id, node.name, node.type,
                            filename, basenode.id, basenode.name,
                            basenode.type)

            else:
                for filename in req.params.get('files').split('|'):
                    mimetype = getMimeType(filename)
                    logg.debug("... in %s.%s: getMimeType(filename=%s)=%s",
                               __name__, funcname(), filename, mimetype)
                    if mimetype[1] == req.params.get('type') or req.params.get(
                            'type') == 'file':
                        for f in basenode.files:
                            # ambiguity here ?
                            if f.abspath.endswith(filename):
                                # bibtex import handler
                                if mimetype[
                                        1] == "bibtex" and not req.params.get(
                                            'type') == 'file':
                                    try:
                                        new_node = importBibTeX(
                                            f.abspath, basenode)
                                        newnodes.append(new_node.id)
                                        basenodefiles_processed.append(f)
                                    except ValueError, e:
                                        errornodes.append(
                                            (filename, unicode(e)))
                                    db.session.commit()
                                else:

                                    logg.debug(
                                        "creating new node: filename: %s",
                                        filename)
                                    logg.debug("files at basenode: %s",
                                               [(x.getName(), x.abspath)
                                                for x in basenode.files])

                                    content_class = Node.get_class_for_typestring(
                                        req.params.get('type'))
                                    node = content_class(
                                        name=filename,
                                        schema=req.params.get('value'))

                                    basenode.children.append(node)
                                    node.set("creator", user.login_name)
                                    node.set(
                                        "creationtime",
                                        unicode(
                                            time.strftime(
                                                '%Y-%m-%dT%H:%M:%S',
                                                time.localtime(time.time()))))

                                    # clones to a file with random name
                                    cloned_file = importFileRandom(f.abspath)
                                    # set filetype for uploaded file as requested by the content class
                                    cloned_file.filetype = content_class.get_upload_filetype(
                                    )
                                    node.files.append(cloned_file)
                                    node.event_files_changed()
                                    newnodes.append(node.id)
                                    basenodefiles_processed.append(f)

                                    logg.info(
                                        "%s created new node id=%s (name=%s, type=%s) by uploading file %s, "
                                        "node is child of base node id=%s (name=%s, type=%s)",
                                        user.login_name, node.id, node.name,
                                        node.type, filename, basenode.id,
                                        basenode.name, basenode.type)

                                    break  # filename may not be unique

            new_tree_labels = [{
                'id': basenode.id,
                'label': getTreeLabel(basenode, lang=language)
            }]
            for f in basenodefiles_processed:
                basenode.files.remove(f)
                f_path = f.abspath
                if os.path.exists(f_path):
                    logg.debug("%s going to remove file %s from disk",
                               user.login_name, f_path)
                    os.remove(f_path)

            mime = getMimeType(filename)
            scheme_type = {mime[1]: []}
            for scheme in get_permitted_schemas():
                if mime[1] in scheme.getDatatypes():
                    scheme_type[mime[1]].append(scheme)
                    # break

            db.session.commit()
            # standard file
            content = req.getTAL('web/edit/modules/upload.html', {
                'files': [filename],
                'schemes': scheme_type
            },
                                 macro="uploadfileok")

            res = {
                'state': state,
                'newnodes': newnodes,
                'errornodes': errornodes,
                'new_tree_labels': new_tree_labels,
                'ret': content
            }
            res = json.dumps(res, ensure_ascii=False)
            req.write(res)
            return None
Esempio n. 8
0
                ustr(
                    time.strftime('%Y-%m-%dT%H:%M:%S',
                                  time.localtime(time.time()))))
            db.session.commit()
            res = {'newid': node.id, 'id': req.params.get('id')}
            req.write(json.dumps(res, ensure_ascii=False))
            return None

        # create node using given identifier (doi, ...)
        if req.params.get('action') == "obj_from_identifier":
            identifier_importer = req.params.get('identifier_importer')
            identifier = req.params.get('identifier')

            logg.debug(
                "... in %s.%s: going to create new node without file from identifier (%s)",
                __name__, funcname(), identifier)

            if identifier_importer in identifier_importers:
                identifierImporter = identifier_importers[identifier_importer]
                importer_func = identifierImporter.importer_func

                user = users.getUserFromRequest(req)
                importdir = users.getUploadDir(user)

                new_node = importer_func(identifier, importdir, req=req)

                res = {
                    'id': req.params.get('id'),
                    'error': req.params.get('error', ''),
                    'error_detail': req.params.get('error_detail', '')
                }
Esempio n. 9
0
def content(req):

    user = users.getUserFromRequest(req)

    access = AccessData(req)
    language = lang(req)
    if not access.user.isEditor():
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    if "id" in req.params and len(req.params) == 1:
        nid = req.params.get("id")
        try:
            node = tree.getNode(nid)
        except:
            node = None
        if node:
            cmd = "cd (%s %r, %r)" % (nid, node.name, node.type)
            logger.info("%s: %s" % (user.getName(), cmd))
            # logging.getLogger("usertracing").info("%s: in editor %s" % (user.getName(), cmd))
        else:
            cmd = "ERROR-cd to non-existing id=%r" % nid
            logger.error("%s: %s") % (user.getName(), cmd)

    if "action" in req.params and req.params["action"] == "upload":
        pass

    content = {"script": "", "body": ""}
    v = {"dircontent": "", "notdirectory": 0, "operations": ""}
    try:
        v["nodeiconpath"] = getEditorIconPath(node)
    except:
        v["nodeiconpath"] = "webtree/directory.gif"

    path = req.path[1:].split("/")
    if len(path) >= 4:
        req.params["style"] = "popup"
        req.params["id"] = path[1]
        req.params["tab"] = path[2]
        req.params["option"] = path[3]
    getEditModules()

    if not access.user.isEditor():
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    # remove all caches for the frontend area- we might make changes there
    for sessionkey in ["contentarea", "navframe"]:
        try:
            del req.session[sessionkey]
        except:
            pass

    ids = getIDs(req)

    if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload":
        return upload_help(req)

    if len(ids) > 0:
        node = tree.getNode(ids[0])
    tabs = "content"
    if node.type == "root":
        tabs = "content"
    elif node.id == users.getUploadDir(access.getUser()).id:
        tabs = "upload"
    elif node.id == users.getImportDir(access.getUser()).id:
        tabs = "imports"
    elif hasattr(node, "getDefaultEditTab"):
        tabs = node.getDefaultEditTab()
        v["notdirectory"] = 0

    current = req.params.get("tab", tabs)
    logger.debug("... %s inside %s.%s: ->  !!! current = %r !!!" % (get_user_id(req), __name__, funcname(), current))
    msg = "%s selected editor module is %r" % (user.getName(), current)
    jsfunc = req.params.get("func", "")
    if jsfunc:
        msg = msg + (", js-function: %r" % jsfunc)
    logger.info(msg)

    # some tabs operate on only one file
    # if current in ["files", "view", "upload"]:
    if current in ["files", "upload"]:
        ids = ids[0:1]

    # display current images
    if not tree.getNode(ids[0]).isContainer():
        v["notdirectory"] = 1
        items = []
        if current != "view":
            for id in ids:
                node = tree.getNode(id)
                if hasattr(node, "show_node_image"):
                    if not isDirectory(node) and not node.isContainer():
                        items.append((id, node.show_node_image()))
                    else:
                        items.append(("", node.show_node_image()))
        v["items"] = items
        logger.debug(
            "... %s inside %s.%s: -> display current images: items: %r"
            % (get_user_id(req), __name__, funcname(), [_t[0] for _t in items])
        )
        try:
            n = tree.getNode(req.params.get("src", req.params.get("id")))
            if current == "metadata" and "save" in req.params:
                pass
            s = []
            while n:
                try:
                    s = [
                        '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>'
                        % (n.id, n.id, n.getLabel(lang=language))
                    ] + s
                except:
                    s = [
                        '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>'
                        % (n.id, n.id, n.name)
                    ] + s

                p = n.getParents()
                if p:
                    n = p[0]
                else:
                    n = None
            v["dircontent"] = " <b>&raquo;</b> ".join(s[1:])
        except:
            logger.exception("ERROR displaying current images")

    else:  # or current directory
        n = tree.getNode(ids[0])
        s = []
        while n:
            if len(s) == 0:
                try:
                    s = ["%s" % (n.getLabel(lang=language))]
                except:
                    s = ["%s" % (n.name)]
            else:
                try:
                    s = [
                        '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>'
                        % (n.id, n.id, n.getLabel(lang=language))
                    ] + s
                except:
                    s = [
                        '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>'
                        % (n.id, n.id, n.name)
                    ] + s

            p = n.getParents()
            if p:
                n = p[0]
            else:
                n = None
        v["dircontent"] = " <b>&raquo;</b> ".join(s[1:])

    if current == "globals":
        basedir = config.get("paths.datadir")
        file_to_edit = None

        if "file_to_edit" in req.params:
            file_to_edit = req.params["file_to_edit"]

        if not file_to_edit:
            d = node.getStartpageDict()
            if d and lang(req) in d:
                file_to_edit = d[lang(req)]

        found = False
        for f in node.getFiles():
            if f.mimetype == "text/html":
                filepath = f.retrieveFile().replace(basedir, "")
                if file_to_edit == filepath:
                    found = True
                    result = edit_editor(req, node, f)
                    if result == "error":
                        logger.error("error editing %r" % f.retrieveFile())
                    break

        if not found:
            edit_editor(req, node, None)

    elif current == "tab_metadata":
        edit_metadata(req, ids)  # undefined
    elif current == "tab_upload":
        edit_upload(req, ids)  # undefined
    elif current == "tab_import":
        edit_import(req, ids)  # undefined
    elif current == "tab_globals":
        req.write("")
    elif current == "tab_lza":
        edit_lza(req, ids)  # undefined
    elif current == "tab_logo":
        edit_logo(req, ids)  # undefined
    else:
        t = current.split("_")[-1]
        if t in editModules.keys():
            c = editModules[t].getContent(req, ids)
            if c:
                content["body"] += c  # use standard method of module
            else:
                logger.debug("empty content")
                return
        else:
            req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
            content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error")

    if req.params.get("style", "") != "popup":  # normal page with header
        v["tabs"] = handletabs(req, ids, tabs)
        v["script"] = content["script"]
        v["body"] = content["body"]
        v["paging"] = showPaging(req, current, ids)
        v["node"] = node
        v["ids"] = req.params.get("ids", "").split(",")
        if req.params.get("ids", "") == "":
            v["ids"] = req.params.get("id", "").split(",")
        v["tab"] = current
        v["operations"] = req.getTAL(
            "web/edit/edit_common.html", {"iscontainer": node.isContainer()}, macro="show_operations"
        )
        user = users.getUserFromRequest(req)
        v["user"] = user
        v["language"] = lang(req)
        v["t"] = translation_t

        v["spc"] = [Menu("sub_header_frontend", "../", target="_parent")]
        if user.isAdmin():
            v["spc"].append(Menu("sub_header_administration", "../admin", target="_parent"))

        if user.isWorkflowEditor():
            v["spc"].append(Menu("sub_header_workflow", "../publish", target="_parent"))

        v["spc"].append(Menu("sub_header_logout", "../logout", target="_parent"))

        # add icons to breadcrumbs
        ipath = "webtree/directory.gif"
        if node and node.isContainer():
            if node.name == "home" or "Arbeitsverzeichnis" in node.name:
                ipath = "webtree/homeicon.gif"
            elif node.name == "Uploads":
                ipath = "webtree/uploadicon.gif"
            elif node.name == "Importe":
                ipath = "webtree/importicon.gif"
            elif node.name == "Inkonsistente Daten":
                ipath = "webtree/faultyicon.gif"
            elif node.name == "Papierkorb":
                ipath = "webtree/trashicon.gif"
            else:
                ipath = getEditorIconPath(node)

        v["dircontent"] += '&nbsp;&nbsp;<img src="' + "/img/" + ipath + '" />'

        return req.writeTAL("web/edit/edit.html", v, macro="frame_content")
Esempio n. 10
0
def getContent(req, ids):

    user = users.getUserFromRequest(req)
    language = lang(req)

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

    if "action" in req.params:
        state = 'ok'

        if req.params.get('action') == "removefiles":
            basenode = q(Node).get(req.params.get('id'))
            for f in basenode.files:
                try:
                    os.remove(f.abspath)
                    pass
                except:
                    state = "error"
            basenode.files = []
            db.session.commit()
            req.write(json.dumps({'state': state}, ensure_ascii=False))
            return None

        if req.params.get('action') == "buildnode":  # create nodes
            basenode = q(Node).get(req.params.get('id'))
            newnodes = []
            errornodes = []
            basenodefiles_processed = []
            if req.params.get('uploader', '') == 'plupload':
                filename2scheme = {}
                for k in req.params:
                    if k.startswith("scheme_"):
                        filename2scheme[
                            k.replace('scheme_', '', 1)] = req.params.get(k)

                for f in basenode.files:
                    filename = f.name
                    if filename in filename2scheme:
                        mimetype = getMimeType(filename)

                        if mimetype[1] == "bibtex":  # bibtex import handler
                            try:
                                new_node = importBibTeX(f.abspath, basenode, req=req)
                                newnodes.append(new_node.id)
                                basenodefiles_processed.append(f)
                            except ValueError, e:
                                errornodes.append((filename, unicode(e)))

                        logg.debug("filename: %s, mimetype: %s", filename, mimetype)
                        logg.debug("__name__=%s, func=%s; _m=%s, _m[1]=%s", __name__, funcname(), mimetype, mimetype[1])

                        content_class = Node.get_class_for_typestring(mimetype[1])
                        node = content_class(name=filename, schema=filename2scheme[filename])

                        basenode.children.append(node)
                        node.set("creator", user.login_name)
                        node.set("creationtime",  unicode(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time()))))
                        # set filetype for uploaded file as requested by the content class
                        f.filetype = content_class.get_upload_filetype()
                        node.files.append(f)
                        node.event_files_changed()
                        newnodes.append(node.id)
                        basenodefiles_processed.append(f)
                        basenode.files.remove(f)
                        db.session.commit()
                        logg.info("%s created new node id=%s (name=%s, type=%s) by uploading file %s, "
                            "node is child of base node id=%s (name=%s, type=%s)", user.login_name, node.id, node.name, node.type,
                             filename, basenode.id, basenode.name, basenode.type)

            else:
                for filename in req.params.get('files').split('|'):
                    mimetype = getMimeType(filename)
                    logg.debug("... in %s.%s: getMimeType(filename=%s)=%s", __name__, funcname(), filename, mimetype)
                    if mimetype[1] == req.params.get('type') or req.params.get('type') == 'file':
                        for f in basenode.files:
                            # ambiguity here ?
                            if f.abspath.endswith(filename):
                                # bibtex import handler
                                if mimetype[1] == "bibtex" and not req.params.get('type') == 'file':
                                    try:
                                        new_node = importBibTeX(f.abspath, basenode, req=req)
                                        newnodes.append(new_node.id)
                                        basenodefiles_processed.append(f)
                                    except ValueError, e:
                                        errornodes.append((filename, unicode(e)))
                                    db.session.commit()
                                else:

                                    logg.debug("creating new node: filename: %s", filename)
                                    logg.debug("files at basenode: %s", [(x.getName(), x.abspath) for x in basenode.files])

                                    content_class = Node.get_class_for_typestring(req.params.get('type'))
                                    node = content_class(name=filename, schema=req.params.get('value'))

                                    basenode.children.append(node)
                                    node.set("creator", user.login_name)
                                    node.set("creationtime",  unicode(time.strftime('%Y-%m-%dT%H:%M:%S',
                                                                                    time.localtime(time.time()))))

                                    # clones to a file with random name
                                    cloned_file = importFileRandom(f.abspath)
                                    # set filetype for uploaded file as requested by the content class
                                    cloned_file.filetype = content_class.get_upload_filetype()
                                    node.files.append(cloned_file)
                                    node.event_files_changed()
                                    newnodes.append(node.id)
                                    basenodefiles_processed.append(f)

                                    logg.info("%s created new node id=%s (name=%s, type=%s) by uploading file %s, "
                                    "node is child of base node id=%s (name=%s, type=%s)", user.login_name, node.id, node.name, node.type, filename,
                                    basenode.id, basenode.name, basenode.type)

                                    break  # filename may not be unique

            new_tree_labels = [{'id': basenode.id, 'label': getTreeLabel(basenode, lang=language)}]
            for f in basenodefiles_processed:
                basenode.files.remove(f)
                f_path = f.abspath
                if os.path.exists(f_path):
                    logg.debug("%s going to remove file %s from disk", user.login_name, f_path)
                    os.remove(f_path)

            mime = getMimeType(filename)
            scheme_type = {mime[1]: []}
            for scheme in get_permitted_schemas():
                if mime[1] in scheme.getDatatypes():
                    scheme_type[mime[1]].append(scheme)
                    # break

            db.session.commit()
            # standard file
            content = req.getTAL('web/edit/modules/upload.html', {'files': [filename], 'schemes': scheme_type}, macro="uploadfileok")

            res = {'state': state, 'newnodes': newnodes, 'errornodes':
                              errornodes, 'new_tree_labels': new_tree_labels, 'ret': content}
            res = json.dumps(res, ensure_ascii=False)
            req.write(res)
            return None
Esempio n. 11
0
def content(req):

    user = users.getUserFromRequest(req)

    access = AccessData(req)
    language = lang(req)
    if not access.user.isEditor():
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    if 'id' in req.params and len(req.params) == 1:
        nid = req.params.get('id')
        try:
            node = tree.getNode(nid)
        except:
            node = None
        if node:
            cmd = "cd (%s %r, %r)" % (nid, node.name, node.type)
            logger.info("%s: %s" % (user.getName(), cmd))
            #logging.getLogger("usertracing").info("%s: in editor %s" % (user.getName(), cmd))
        else:
            cmd = "ERROR-cd to non-existing id=%r" % nid
            logger.error("%s: %s") % (user.getName(), cmd)

    if 'action' in req.params and req.params['action'] == 'upload':
        pass

    content = {'script': '', 'body': ''}
    v = {'dircontent': '', 'notdirectory': 0, 'operations': ''}
    try:
        v['nodeiconpath'] = getEditorIconPath(node)
    except:
        v['nodeiconpath'] = "webtree/directory.gif"

    path = req.path[1:].split("/")
    if len(path) >= 4:
        req.params["style"] = "popup"
        req.params["id"] = path[1]
        req.params["tab"] = path[2]
        req.params["option"] = path[3]
    getEditModules()

    if not access.user.isEditor():
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    # remove all caches for the frontend area- we might make changes there
    for sessionkey in ["contentarea", "navframe"]:
        try:
            del req.session[sessionkey]
        except:
            pass

    ids = getIDs(req)

    if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload":
        return upload_help(req)

    if len(ids) > 0:
        node = tree.getNode(ids[0])
    tabs = "content"
    if node.type == "root":
        tabs = "content"
    elif node.id == users.getUploadDir(access.getUser()).id:
        tabs = "upload"
    elif node.id == users.getImportDir(access.getUser()).id:
        tabs = "imports"
    elif hasattr(node, "getDefaultEditTab"):
        tabs = node.getDefaultEditTab()
        v["notdirectory"] = 0

    current = req.params.get("tab", tabs)
    logger.debug("... %s inside %s.%s: ->  !!! current = %r !!!" %
                 (get_user_id(req), __name__, funcname(), current))
    msg = "%s selected editor module is %r" % (user.getName(), current)
    jsfunc = req.params.get("func", "")
    if jsfunc:
        msg = msg + (', js-function: %r' % jsfunc)
    logger.info(msg)

    # some tabs operate on only one file
    # if current in ["files", "view", "upload"]:
    if current in ["files", "upload"]:
        ids = ids[0:1]

    # display current images
    if not tree.getNode(ids[0]).isContainer():
        v["notdirectory"] = 1
        items = []
        if current != "view":
            for id in ids:
                node = tree.getNode(id)
                if hasattr(node, "show_node_image"):
                    if not isDirectory(node) and not node.isContainer():
                        items.append((id, node.show_node_image()))
                    else:
                        items.append(("", node.show_node_image()))
        v["items"] = items
        logger.debug("... %s inside %s.%s: -> display current images: items: %r" %
                     (get_user_id(req), __name__, funcname(), [_t[0] for _t in items]))
        try:
            n = tree.getNode(req.params.get('src', req.params.get('id')))
            if current == 'metadata' and 'save' in req.params:
                pass
            s = []
            while n:
                try:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.getLabel(lang=language))] + s
                except:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.name)] + s

                p = n.getParents()
                if p:
                    n = p[0]
                else:
                    n = None
            v["dircontent"] = ' <b>&raquo;</b> '.join(s[1:])
        except:
            logger.exception('ERROR displaying current images')

    else:  # or current directory
        n = tree.getNode(ids[0])
        s = []
        while n:
            if len(s) == 0:
                try:
                    s = ['%s' % (n.getLabel(lang=language))]
                except:
                    s = ['%s' % (n.name)]
            else:
                try:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.getLabel(lang=language))] + s
                except:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.name)] + s

            p = n.getParents()
            if p:
                n = p[0]
            else:
                n = None
        v["dircontent"] = ' <b>&raquo;</b> '.join(s[1:])

    if current == "globals":
        basedir = config.get("paths.datadir")
        file_to_edit = None

        if "file_to_edit" in req.params:
            file_to_edit = req.params["file_to_edit"]

        if not file_to_edit:
            d = node.getStartpageDict()
            if d and lang(req) in d:
                file_to_edit = d[lang(req)]

        found = False
        for f in node.getFiles():
            if f.mimetype == 'text/html':
                filepath = f.retrieveFile().replace(basedir, '')
                if file_to_edit == filepath:
                    found = True
                    result = edit_editor(req, node, f)
                    if result == "error":
                        logger.error("error editing %r" % f.retrieveFile())
                    break

        if not found:
            edit_editor(req, node, None)

    elif current == "tab_metadata":
        edit_metadata(req, ids)  # undefined
    elif current == "tab_upload":
        edit_upload(req, ids)  # undefined
    elif current == "tab_import":
        edit_import(req, ids)  # undefined
    elif current == "tab_globals":
        req.write("")
    elif current == "tab_lza":
        edit_lza(req, ids)  # undefined
    elif current == "tab_logo":
        edit_logo(req, ids)  # undefined
    else:
        t = current.split("_")[-1]
        if t in editModules.keys():
            c = editModules[t].getContent(req, ids)
            if c:
                content["body"] += c  # use standard method of module
            else:
                logger.debug('empty content')
                return
        else:
            req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
            content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error")

    if req.params.get("style", "") != "popup":  # normal page with header
        v["tabs"] = handletabs(req, ids, tabs)
        v["script"] = content["script"]
        v["body"] = content["body"]
        v["paging"] = showPaging(req, current, ids)
        v["node"] = node
        v["ids"] = req.params.get("ids", "").split(",")
        if req.params.get("ids", "") == "":
            v["ids"] = req.params.get("id", "").split(",")
        v["tab"] = current
        v["operations"] = req.getTAL("web/edit/edit_common.html", {'iscontainer': node.isContainer()}, macro="show_operations")
        user = users.getUserFromRequest(req)
        v['user'] = user
        v['language'] = lang(req)
        v['t'] = translation_t

        v['spc'] = [Menu("sub_header_frontend", "../", target="_parent")]
        if user.isAdmin():
            v['spc'].append(Menu("sub_header_administration", "../admin", target="_parent"))

        if user.isWorkflowEditor():
            v['spc'].append(Menu("sub_header_workflow", "../publish", target="_parent"))

        v['spc'].append(Menu("sub_header_logout", "../logout", target="_parent"))

        # add icons to breadcrumbs
        ipath = 'webtree/directory.gif'
        if node and node.isContainer():
            if node.name == 'home' or 'Arbeitsverzeichnis' in node.name:
                ipath = 'webtree/homeicon.gif'
            elif node.name == 'Uploads':
                ipath = 'webtree/uploadicon.gif'
            elif node.name == 'Importe':
                ipath = 'webtree/importicon.gif'
            elif node.name == 'Inkonsistente Daten':
                ipath = 'webtree/faultyicon.gif'
            elif node.name == 'Papierkorb':
                ipath = 'webtree/trashicon.gif'
            else:
                ipath = getEditorIconPath(node)

        v["dircontent"] += '&nbsp;&nbsp;<img src="' + '/img/' + ipath + '" />'

        return req.writeTAL("web/edit/edit.html", v, macro="frame_content")
Esempio n. 12
0
            basenode.children.append(node)
            node.set("creator", user.login_name)
            node.set("creationtime",  ustr(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time()))))
            db.session.commit()
            res = {'newid': node.id,
                   'id': req.params.get('id')}
            req.write(json.dumps(res, ensure_ascii=False))
            return None

        # create node using given identifier (doi, ...)
        if req.params.get('action') == "obj_from_identifier":
            identifier_importer = req.params.get('identifier_importer')
            identifier = req.params.get('identifier')

            logg.debug("... in %s.%s: going to create new node without file from identifier (%s)",
                __name__, funcname(), identifier)

            if identifier_importer in identifier_importers:
                identifierImporter = identifier_importers[identifier_importer]
                importer_func = identifierImporter.importer_func

                user = users.getUserFromRequest(req)
                importdir = users.getUploadDir(user)

                new_node = importer_func(identifier, importdir, req=req)

                res = {'id': req.params.get('id'), 'error': req.params.get('error', ''), 'error_detail': req.params.get('error_detail', '')}

                if new_node:
                    new_node.set("creator", user.login_name)
                    creation_time = ustr(time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time())))
Esempio n. 13
0
def getContent(req, ids):
    ret = ""
    user = users.getUserFromRequest(req)

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

    access = AccessData(req)
    faultydir = users.getFaultyDir(user)
    metatypes = []
    nodes = []
    masklist = []
    err = 0

    # flag indicating change of node.name (fancytree node may have to be updated)
    # keep as integer
    # negative -> no change
    # else -> id of changed node
    flag_nodename_changed = -1

    for id in ids:
        node = tree.getNode(id)
        if not access.hasWriteAccess(node):
            print "error 2"
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        schema = node.getSchema()
        if schema not in metatypes:
            metatypes.append(schema)
        if len(nodes) == 0 or nodes[0].getSchema() == schema:
            nodes += [node]

    idstr = ",".join(ids)
    action = req.params.get('action', '').strip()

    logger.info("%s in editor metadata (action=%r): %r" %
                (user.getName(), action, [[n.id, n.name, n.type]for n in nodes]))

    for m in node.getType().getMasks(type="edit"):
        if access.hasReadAccess(m):
            masklist.append(m)

    if hasattr(node, "metaFields"):

        class SystemMask:

            def __init__(self, name, description, fields):
                self.name, self.description, self.fields = name, description, fields

            def getName(self):
                return self.name

            def getDescription(self):
                return self.description

            def getDefaultMask(self):
                return False

            def metaFields(self, lang=None):
                return self.fields

            def i_am_not_a_mask():
                pass
        masklist = [SystemMask(
            "settings", t(req, "settings"), node.metaFields(lang(req)))] + masklist

    default = None
    for m in masklist:
        if m.getDefaultMask():
            default = m
            break
    if not default and len(masklist):
        default = masklist[0]

    maskname = req.params.get("mask", node.get("edit.lastmask") or "editmask")
    if maskname == "":
        maskname = default.getName()

    mask = None
    for m in masklist:
        if maskname == m.getName():
            mask = m
            break

    if not mask and default:
        mask = default
        maskname = default.getName()

    for n in nodes:
        n.set("edit.lastmask", maskname)

    if not mask:
        return req.getTAL("web/edit/modules/metadata.html", {}, macro="no_mask")

    # context default for TAL interpreter
    ctx = {}
    ctx["user"] = user
    ctx["access"] = access
    ctx["metatypes"] = metatypes
    ctx["idstr"] = idstr
    ctx["node"] = nodes[0]  # ?
    ctx["flag_nodename_changed"] = flag_nodename_changed
    ctx["nodes"] = nodes
    ctx["masklist"] = masklist
    ctx["maskname"] = maskname
    ctx["language"] = lang(req)
    ctx["t"] = t

    if action == 'restore':
        vid = req.params.get('vid', '0')
        node = nodes[0].getActiveVersion()
        if (vid != '0' and vid != node.id):
            n = tree.getNode(vid)
            # Not active version
            if n.next_nid != '0':

                next = tree.getNode(n.next_nid)
                if next.prev_nid != '0':
                    next.removeChild(tree.getNode(next.prev_nid))
                next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    prev.setNextID(n.next_nid)
                    n.removeChild(prev)
                    next.addChild(prev)
                node.setNextID(n.id)

                n.setPrevID(node.id)
                n.setNextID('0')

                for pid in db.getParents(node.id):
                    parentNode = tree.getNode(pid)
                    parentNode.addChild(n)
                    parentNode.removeChild(node)
                n.addChild(node)

                nodes = [n]
                ids = [n.id]

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {'url': '?id=' + n.id + '&tab=metadata', 'pid':
                        None, 'flag_nodename_changed': flag_nodename_changed}

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if action == 'delete':
        vid = req.params.get('vid', '0')
        if (vid != '0'):
            node = nodes[0].getActiveVersion()
            n = tree.getNode(vid)

            if (vid != node.id):
                n.set("deleted", "true")
                for pid in db.getParents(n.id):
                    parentNode = tree.getNode(pid)
                    parentNode.removeChild(n)
                for cid in db.getChildren(n.id):
                    n.removeChild(tree.getNode(cid))
                if n.next_nid != '0' and n.prev_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    _next.addChild(tree.getNode(n.prev_nid))

                if n.next_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    if n.prev_nid != '0':
                        _next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    _prev = tree.getNode(n.prev_nid)
                    if n.next_nid != '0':
                        _prev.setNextID(n.next_nid)
            else:
                pids = db.getParents(n.id)

                # Active version
                prev = None
                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    while prev.prev_nid != None and prev.prev_nid != '0' and prev.get("deleted") == "true":
                        prev = tree.getNode(prev.prev_nid)

                if prev != None and prev.get("deleted") != "true":
                    prev.setNextID('0')
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.addChild(prev)
                    nodes = [prev]
                    ids = [prev.id]
                    n.set("deleted", "true")
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    for cid in db.getChildren(n.id):
                        n.removeChild(tree.getNode(cid))

                    if n.next_nid != '0' and n.prev_nid != '0':
                        _next = tree.getNode(n.next_nid)
                        _next.addChild(tree.getNode(n.prev_nid))

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + prev.id + '&tab=metadata', 'pid':
                            None, 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")
                else:
                    # Version 0
                    # Move node to trash
                    trashdir = users.getTrashDir(user)
                    trashdir.addChild(n)
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + pids[0] + '&tab=content', 'pid': pids[
                        0], 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if "edit_metadata" in req.params:
        # check and save items
        userdir = users.getHomeDir(users.getUserFromRequest(req))

        for node in nodes:
            if not access.hasWriteAccess(node) or node.id == userdir.id:
                print "error 3"
                req.setStatus(httpstatus.HTTP_FORBIDDEN)
                return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        logging.getLogger('usertracing').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').debug(pf(req.params))

        for node in nodes:
            node.set("updateuser", user.getName())
            if node.get('updatetime') < str(now()):
                node.set("updatetime", str(format_date()))

        if not hasattr(mask, "i_am_not_a_mask"):
            if (req.params.get('generate_new_version')):
                # Create new node version
                _ids = []
                _nodes = []
                for node in nodes:
                    n = node.createNewVersion(user)
                    n.set("system.version.comment", '(' + t(req, "document_new_version_comment") +
                          ')\n' + req.params.get('version_comment', ''))

                    # add all existing attributes to the new version node
                    for attr, value in node.items():
                        # do not overwrite existing attributes
                        # do not copy system attributes
                        if n.get(attr) != "" or attr.startswith("system."):
                            pass
                        else:
                            n.set(attr, value)

                    _nodes.append(n)
                    _ids.append(n.id)

                ids = _ids
                idstr = ",".join(ids)
                nodes = _nodes
                nodes = mask.updateNode(nodes, req)

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {
                    'url': '?id=' + nodes[0].id + '&tab=metadata',
                    'pid': None,
                }

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(
                    nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                ret += req.getTAL("web/edit/modules/metadata.html",
                                  data, macro="redirect")
            else:
                if nodes:
                    old_nodename = nodes[0].name
                nodes = mask.updateNode(nodes, req)
                if nodes:
                    new_nodename = nodes[0].name
                    if (old_nodename != new_nodename) and hasattr(nodes[0], 'isContainer') and nodes[0].isContainer():
                        # for updates of node label in editor tree
                        flag_nodename_changed = str(node.id)

        else:
            for field in mask.metaFields():
                msg = "in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %r, field.id: %r, field.name: %r, mask: %r, maskname: %r" % (
                    __name__, funcname(), field, field.id, field.getName(), mask, maskname)
                logger.debug(msg)
                field_name = field.getName()

                if field_name == 'nodename' and maskname == 'settings':
                    if '__nodename' in req.params:
                        field_name = '__nodename'  # no multilang here !
                    elif getDefaultLanguage() + '__nodename' in req.params:
                        # no multilang here !
                        field_name = getDefaultLanguage() + '__nodename'
                    value = req.params.get(field_name, None)
                    if value:
                        if value != node.name:
                            flag_nodename_changed = str(node.id)
                        for node in nodes:
                            node.setName(value)
                elif field_name in ('repec.code', 'repec.provider') and maskname == 'settings':
                    if '__' + field_name in req.params:
                        field_name = '__' + field_name  # no multilang here!
                    elif getDefaultLanguage() + '__' + field_name in req.params:
                        field_name = getDefaultLanguage() + '__' + field_name  # no multilang here!

                value = req.params.get(field_name, None)

                if value is not None:
                    for node in nodes:
                        node.set(field.getName(), value)
                else:
                    node.set(field.getName(), "")

    if "edit_metadata" in req.params or node.get("faulty") == "true":
        if not hasattr(mask, "i_am_not_a_mask"):
            req.params["errorlist"] = mask.validate(nodes)

    node_versions = nodes[0].getVersionList()
    update_date, creation_date = get_datelists(nodes)

    data = {}
    data["versions"] = node_versions
    data["creation_date"] = creation_date
    data["update_date"] = update_date
    data["err"] = err

    _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
    data["maskform"] = _maskform
    data["fields"] = _fields

    data.update(ctx)
    data["flag_nodename_changed"] = flag_nodename_changed

    ret += req.getTAL("web/edit/modules/metadata.html",
                      data, macro="edit_metadata")
    return ret
Esempio n. 14
0
def _handle_edit_metadata(req, mask, nodes):
    # check and save items
    user = current_user
    userdir = user.home_dir
    flag_nodename_changed = -1
    form = req.form

    for node in nodes:
        if not node.has_write_access() or node is userdir:
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    if not hasattr(mask, "i_am_not_a_mask"):
        if form.get('generate_new_version'):
            # Create new node version
            comment = u'({})\n{}'.format(t(req, "document_new_version_comment"), form.get('version_comment', ''))

            for node in nodes:
                with node.new_tagged_version(comment=comment, user=user):
                    mask.update_node(node, req, user)
        else:
            # XXX: why check here?
            # if nodes:
            old_nodename = nodes[0].name

            for node in nodes:
                mask.update_node(node, req, user)

            db.session.commit()

            # XXX: why check here?
            # if nodes:
            new_nodename = nodes[0].name
            if ( len(nodes) == 1 or old_nodename != new_nodename) and isinstance(nodes[0], Container):
                # for updates of node label in editor tree
                flag_nodename_changed = ustr(nodes[0].id)

    else:
        for field in mask.metaFields():
            logg.debug("in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %s, field.id: %s, field.name: %s, mask: %s, maskname: %s",
                __name__, funcname(), field, field.id, field.name, mask, mask.name)
            field_name = field.name
            if field_name == 'nodename' and mask.name == 'settings':
                if '__nodename' in form:
                    field_name = '__nodename'  # no multilang here !
                elif getDefaultLanguage() + '__nodename' in form:
                    # no multilang here !
                    field_name = getDefaultLanguage() + '__nodename'
                value = form.get(field_name, None)
                if value:
                    if value != node.name:
                        flag_nodename_changed = ustr(node.id)
                    for node in nodes:
                        node.name = value
            value = form.get(field_name, None)
            if value is not None:
                for node in nodes:
                    node.set(field.name, value)
            else:
                node.set(field.getName(), "")
        db.session.commit()

    return flag_nodename_changed
Esempio n. 15
0
def getContent(req, ids):
    ret = ""
    user = users.getUserFromRequest(req)

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

    access = AccessData(req)
    faultydir = users.getFaultyDir(user)
    metatypes = []
    nodes = []
    masklist = []
    err = 0

    # flag indicating change of node.name (fancytree node may have to be updated)
    # keep as integer
    # negative -> no change
    # else -> id of changed node
    flag_nodename_changed = -1

    for id in ids:
        node = tree.getNode(id)
        if not access.hasWriteAccess(node):
            print "error 2"
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        schema = node.getSchema()
        if schema not in metatypes:
            metatypes.append(schema)
        if len(nodes) == 0 or nodes[0].getSchema() == schema:
            nodes += [node]

    idstr = ",".join(ids)
    action = req.params.get('action', '').strip()

    logger.info("%s in editor metadata (action=%r): %r" %
                (user.getName(), action, [[n.id, n.name, n.type]for n in nodes]))

    for m in node.getType().getMasks(type="edit"):
        if access.hasReadAccess(m):
            masklist.append(m)

    if hasattr(node, "metaFields"):

        class SystemMask:

            def __init__(self, name, description, fields):
                self.name, self.description, self.fields = name, description, fields

            def getName(self):
                return self.name

            def getDescription(self):
                return self.description

            def getDefaultMask(self):
                return False

            def metaFields(self, lang=None):
                return self.fields

            def i_am_not_a_mask():
                pass
        masklist = [SystemMask(
            "settings", t(req, "settings"), node.metaFields(lang(req)))] + masklist

    default = None
    for m in masklist:
        if m.getDefaultMask():
            default = m
            break
    if not default and len(masklist):
        default = masklist[0]

    maskname = req.params.get("mask", node.get("edit.lastmask") or "editmask")
    if maskname == "":
        maskname = default.getName()

    mask = None
    for m in masklist:
        if maskname == m.getName():
            mask = m
            break

    if not mask and default:
        mask = default
        maskname = default.getName()

    for n in nodes:
        n.set("edit.lastmask", maskname)

    if not mask:
        return req.getTAL("web/edit/modules/metadata.html", {}, macro="no_mask")

    # context default for TAL interpreter
    ctx = {}
    ctx["user"] = user
    ctx["access"] = access
    ctx["metatypes"] = metatypes
    ctx["idstr"] = idstr
    ctx["node"] = nodes[0]  # ?
    ctx["flag_nodename_changed"] = flag_nodename_changed
    ctx["nodes"] = nodes
    ctx["masklist"] = masklist
    ctx["maskname"] = maskname
    ctx["language"] = lang(req)
    ctx["t"] = t

    if action == 'restore':
        vid = req.params.get('vid', '0')
        node = nodes[0].getActiveVersion()
        if (vid != '0' and vid != node.id):
            n = tree.getNode(vid)
            # Not active version
            if n.next_nid != '0':

                next = tree.getNode(n.next_nid)
                if next.prev_nid != '0':
                    next.removeChild(tree.getNode(next.prev_nid))
                next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    prev.setNextID(n.next_nid)
                    n.removeChild(prev)
                    next.addChild(prev)
                node.setNextID(n.id)

                n.setPrevID(node.id)
                n.setNextID('0')

                for pid in db.getParents(node.id):
                    parentNode = tree.getNode(pid)
                    parentNode.addChild(n)
                    parentNode.removeChild(node)
                n.addChild(node)

                nodes = [n]
                ids = [n.id]

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {'url': '?id=' + n.id + '&tab=metadata', 'pid':
                        None, 'flag_nodename_changed': flag_nodename_changed}

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if action == 'delete':
        vid = req.params.get('vid', '0')
        if (vid != '0'):
            node = nodes[0].getActiveVersion()
            n = tree.getNode(vid)

            if (vid != node.id):
                n.set("deleted", "true")
                for pid in db.getParents(n.id):
                    parentNode = tree.getNode(pid)
                    parentNode.removeChild(n)
                for cid in db.getChildren(n.id):
                    n.removeChild(tree.getNode(cid))
                if n.next_nid != '0' and n.prev_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    _next.addChild(tree.getNode(n.prev_nid))

                if n.next_nid != '0':
                    _next = tree.getNode(n.next_nid)
                    if n.prev_nid != '0':
                        _next.setPrevID(n.prev_nid)

                if n.prev_nid != '0':
                    _prev = tree.getNode(n.prev_nid)
                    if n.next_nid != '0':
                        _prev.setNextID(n.next_nid)
            else:
                pids = db.getParents(n.id)

                # Active version
                prev = None
                if n.prev_nid != '0':
                    prev = tree.getNode(n.prev_nid)
                    while prev.prev_nid != None and prev.prev_nid != '0' and prev.get("deleted") == "true":
                        prev = tree.getNode(prev.prev_nid)

                if prev != None and prev.get("deleted") != "true":
                    prev.setNextID('0')
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.addChild(prev)
                    nodes = [prev]
                    ids = [prev.id]
                    n.set("deleted", "true")
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    for cid in db.getChildren(n.id):
                        n.removeChild(tree.getNode(cid))

                    if n.next_nid != '0' and n.prev_nid != '0':
                        _next = tree.getNode(n.next_nid)
                        _next.addChild(tree.getNode(n.prev_nid))

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + prev.id + '&tab=metadata', 'pid':
                            None, 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")
                else:
                    # Version 0
                    # Move node to trash
                    trashdir = users.getTrashDir(user)
                    trashdir.addChild(n)
                    for pid in pids:
                        parentNode = tree.getNode(pid)
                        parentNode.removeChild(n)

                    node_versions = nodes[0].getVersionList()
                    update_date, creation_date = get_datelists(nodes)

                    data = {'url': '?id=' + pids[0] + '&tab=content', 'pid': pids[
                        0], 'flag_nodename_changed': flag_nodename_changed}

                    data["versions"] = node_versions
                    data["creation_date"] = creation_date
                    data["update_date"] = update_date

                    _maskform, _fields = get_maskform_and_fields(
                        nodes, mask, req)
                    data["maskform"] = _maskform
                    data["fields"] = _fields

                    data.update(ctx)

                    return req.getTAL("web/edit/modules/metadata.html", data, macro="redirect")

    if "edit_metadata" in req.params:
        # check and save items
        userdir = users.getHomeDir(users.getUserFromRequest(req))

        for node in nodes:
            if not access.hasWriteAccess(node) or node.id == userdir.id:
                print "error 3"
                req.setStatus(httpstatus.HTTP_FORBIDDEN)
                return req.getTAL("web/edit/edit.html", {}, macro="access_error")

        logging.getLogger('usertracing').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').info(
            access.user.name + " change metadata " + idstr)
        logging.getLogger('editor').debug(pf(req.params))

        for node in nodes:
            node.set("updateuser", user.getName())
            if node.get('updatetime') < str(now()):
                node.set("updatetime", str(format_date()))

        if not hasattr(mask, "i_am_not_a_mask"):
            if (req.params.get('generate_new_version')):
                # Create new node version
                _ids = []
                _nodes = []
                for node in nodes:
                    n = node.createNewVersion(user)
                    n.set("system.version.comment", '(' + t(req, "document_new_version_comment") +
                          ')\n' + req.params.get('version_comment', ''))

                    # add all existing attributes to the new version node
                    for attr, value in node.items():
                        # do not overwrite existing attributes
                        # do not copy system attributes
                        if n.get(attr) != "" or attr.startswith("system."):
                            pass
                        else:
                            n.set(attr, value)

                    _nodes.append(n)
                    _ids.append(n.id)

                ids = _ids
                idstr = ",".join(ids)
                nodes = _nodes
                nodes = mask.updateNode(nodes, req)

                node_versions = nodes[0].getVersionList()
                update_date, creation_date = get_datelists(nodes)

                data = {
                    'url': '?id=' + nodes[0].id + '&tab=metadata',
                    'pid': None,
                }

                data["versions"] = node_versions
                data["creation_date"] = creation_date
                data["update_date"] = update_date

                _maskform, _fields = get_maskform_and_fields(
                    nodes, mask, req)
                data["maskform"] = _maskform
                data["fields"] = _fields

                data.update(ctx)

                ret += req.getTAL("web/edit/modules/metadata.html",
                                  data, macro="redirect")
            else:
                if nodes:
                    old_nodename = nodes[0].name
                nodes = mask.updateNode(nodes, req)
                if nodes:
                    new_nodename = nodes[0].name
                    if (old_nodename != new_nodename) and hasattr(nodes[0], 'isContainer') and nodes[0].isContainer():
                        # for updates of node label in editor tree
                        flag_nodename_changed = str(node.id)

        else:
            for field in mask.metaFields():
                msg = "in %s.%s: (hasattr(mask,'i_am_not_a_mask')) field: %r, field.id: %r, field.name: %r, mask: %r, maskname: %r" % (
                    __name__, funcname(), field, field.id, field.getName(), mask, maskname)
                logger.debug(msg)
                field_name = field.getName()
                if field_name == 'nodename' and maskname == 'settings':
                    if '__nodename' in req.params:
                        field_name = '__nodename'  # no multilang here !
                    elif getDefaultLanguage() + '__nodename' in req.params:
                        # no multilang here !
                        field_name = getDefaultLanguage() + '__nodename'
                    value = req.params.get(field_name, None)
                    if value:
                        if value != node.name:
                            flag_nodename_changed = str(node.id)
                        for node in nodes:
                            node.setName(value)
                value = req.params.get(field_name, None)
                if value is not None:
                    for node in nodes:
                        node.set(field.getName(), value)
                else:
                    node.set(field.getName(), "")

    if "edit_metadata" in req.params or node.get("faulty") == "true":
        if not hasattr(mask, "i_am_not_a_mask"):
            req.params["errorlist"] = mask.validate(nodes)

    node_versions = nodes[0].getVersionList()
    update_date, creation_date = get_datelists(nodes)

    data = {}
    data["versions"] = node_versions
    data["creation_date"] = creation_date
    data["update_date"] = update_date
    data["err"] = err

    _maskform, _fields = get_maskform_and_fields(nodes, mask, req)
    data["maskform"] = _maskform
    data["fields"] = _fields

    data.update(ctx)
    data["flag_nodename_changed"] = flag_nodename_changed

    ret += req.getTAL("web/edit/modules/metadata.html",
                      data, macro="edit_metadata")
    return ret
Esempio n. 16
0
def content(req):

    user = current_user
    language = lang(req)

    if not user.is_editor:
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    if 'id' in req.params and len(req.params) == 1:
        nid = long(req.params.get('id'))
        node = q(Data).get(nid)

        if node is not None:
            cmd = "cd (%s %r, %r)" % (nid, node.name, node.type)
            logg.info("%s: %s", user.login_name, cmd)
        else:
            cmd = "ERROR-cd to non-existing id=%r" % nid
            logg.error("%s: %s", user.login_name, cmd)

    if 'action' in req.params and req.params['action'] == 'upload':
        pass

    content = {'script': '', 'body': ''}
    v = {'dircontent': '', 'notdirectory': 0, 'operations': ''}
    try:
        v['nodeiconpath'] = getEditorIconPath(node)
    except:
        v['nodeiconpath'] = "webtree/directory.gif"

    path = req.path[1:].split("/")
    if len(path) >= 4:
        req.params["style"] = "popup"
        req.params["id"] = path[1]
        req.params["tab"] = path[2]
        req.params["option"] = path[3]
    getEditModules()

    if not user.is_editor:
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    # remove all caches for the frontend area- we might make changes there
    for sessionkey in ["contentarea", "navframe"]:
        try:
            del req.session[sessionkey]
        except:
            pass

    ids = getIDs(req)

    if req.params.get("type", "") == "help" and req.params.get("tab",
                                                               "") == "upload":
        return upload_help(req)

    if len(ids) > 0:
        if ids[0] == "all":
            ids = get_ids_from_req(req)
        node = q(Node).get(long(ids[0]))
    tabs = "content"
    if isinstance(node, Root):
        tabs = "content"
    elif node is user.upload_dir:
        tabs = "upload"
    else:
        tabs = node.get_default_edit_tab()
        v["notdirectory"] = 0

    current = req.params.get("tab", tabs)
    logg.debug("... %s inside %s.%s: ->  !!! current = %s !!!",
               get_user_id(req), __name__, funcname(), current)
    msg = "%s selected editor module is %s" % (user.login_name, current)
    jsfunc = req.params.get("func", "")
    if jsfunc:
        msg = msg + (', js-function: %r' % jsfunc)
    logg.info(msg)

    # some tabs operate on only one file
    # if current in ["files", "view", "upload"]:
    if current in ["files", "upload"]:
        ids = ids[0:1]

    # display current images
    if not isinstance(q(Data).get(ids[0]), Container):
        v["notdirectory"] = 1
        items = []
        if current != "view":
            for id in ids:
                node = q(Data).get(id)
                if hasattr(node, "show_node_image"):
                    if not isDirectory(node) and not node.isContainer():
                        items.append((id, node.show_node_image()))
                    else:
                        items.append(("", node.show_node_image()))
        v["items"] = items
        if logg.isEnabledFor(logging.DEBUG):
            logg.debug(
                "... %s inside %s.%s: -> display current images: items: %s",
                get_user_id(req), __name__, funcname(),
                [_t[0] for _t in items])

        nid = req.params.get('src', req.params.get('id'))
        if nid is None:
            raise ValueError(
                "invalid request, neither 'src' not 'id' parameter is set!")

        folders_only = False
        if nid.find(',') > 0:
            # more than one node selected
            # use the first one for activateEditorTreeNode
            # and display only folders
            nid = nid.split(',')[0]
            folders_only = True
        n = q(Data).get(nid)
        if current == 'metadata' and 'save' in req.params:
            pass
        s = []
        while n:
            if not folders_only:
                s = [
                    '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>'
                    % (n.id, n.id, get_edit_label(n, language))
                ] + s

            folders_only = False
            p = n.parents
            # XXX: we only check the first parent. This is wrong, how could be solve this? #
            first_parent = p[0]
            if isinstance(first_parent,
                          Data) and first_parent.has_read_access():
                n = p[0]
            else:
                n = None
        v["dircontent"] = ' <b>&raquo;</b> '.join(s)

    else:  # or current directory
        n = q(Data).get(long(ids[0]))
        s = []
        while n:
            if len(s) == 0:
                s = ['%s' % (get_edit_label(n, language))]
            else:
                s = [
                    '<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>'
                    % (n.id, n.id, get_edit_label(n, language))
                ] + s

            p = n.parents
            if p and not isinstance(p[0], Root):
                n = p[0]
            else:
                n = None
        v["dircontent"] = ' <b>&raquo;</b> '.join(s)

    if current == "globals":
        basedir = config.get("paths.datadir")
        file_to_edit = None

        if "file_to_edit" in req.params:
            file_to_edit = req.params["file_to_edit"]

        if not file_to_edit:
            # todo: getstartpagedict doesnt exist
            d = node.getStartpageDict()
            if d and language in d:
                file_to_edit = d[language]

        found = False
        for f in node.files:
            if f.mimetype == 'text/html':
                filepath = f.abspath.replace(basedir, '')
                if file_to_edit == filepath:
                    found = True
                    break

    else:
        t2 = current.split("_")[-1]
        if t2 in editModules.keys():
            c = editModules[t2].getContent(req, ids)

            if isinstance(c, int):
                # module returned a custom http status code instead of HTML content
                return c

            elif c:
                content["body"] += c
            else:
                logg.debug('empty content')
                return
        else:
            req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
            content["body"] += req.getTAL("web/edit/edit.html",
                                          {"module": current},
                                          macro="module_error")

    if req.params.get("style", "") != "popup":  # normal page with header
        v["tabs"] = handletabs(req, ids, tabs)
        v["script"] = content["script"]
        v["body"] = content["body"]
        v["paging"] = showPaging(req, current, ids)
        v["node"] = node
        v["ids"] = req.params.get("ids", "").split(",")
        if req.params.get("ids", "") == "":
            v["ids"] = req.params.get("id", "").split(",")
        v["tab"] = current
        v["operations"] = req.getTAL("web/edit/edit_common.html",
                                     {'iscontainer': node.isContainer()},
                                     macro="show_operations")
        v['user'] = user
        v['language'] = lang(req)
        v['t'] = t

        # add icons to breadcrumbs
        ipath = 'webtree/directory.gif'
        if node and node.isContainer():
            if node.name == 'home' or 'Arbeitsverzeichnis' in node.name or node == current_user.home_dir:
                ipath = 'webtree/homeicon.gif'
            elif node.name in ('Uploads', 'upload'):
                ipath = 'webtree/uploadicon.gif'
            elif node.name in ('Papierkorb', 'trash'):
                ipath = 'webtree/trashicon.gif'
            else:
                ipath = getEditorIconPath(node)

        v["dircontent"] += '&nbsp;&nbsp;<img src="' + '/img/' + ipath + '" />'

        return req.writeTAL("web/edit/edit.html", v, macro="frame_content")