Example #1
0
def shownodelist(req, nodes, publishwarn=1, markunpublished=0, dir=None):
    req.session["nodelist"] = EditorNodeList(nodes)
    script_array = "allobjects = new Array();\n"
    nodelist = []

    user = users.getUserFromRequest(req)

    for child in nodes:
        try:
            if isDirectory(child) or isCollection(child):
                continue
            script_array += "allobjects['%s'] = 0;\n" % child.id
            nodelist.append(child)
        except TypeError:
            continue

    chkjavascript = ""
    notpublished = {}
    if publishwarn or markunpublished:
        homedir = getHomeDir(user)
        homedirs = getAllSubDirs(homedir)
        if markunpublished:
            chkjavascript = """<script language="javascript">"""
        for node in nodes:
            ok = 0
            for p in node.getParents():
                if p not in homedirs:
                    ok = 1
            if not ok:
                if markunpublished:
                    chkjavascript += """allobjects['check%s'] = 1;
                                        document.getElementById('check%s').checked = true;
                                     """ % (node.id, node.id)

                notpublished[node] = node
        chkjavascript += """</script>"""
        # if all nodes are properly published, don't bother
        # to warn the user
        if not notpublished:
            publishwarn = 0

    unpublishedlink = None
    if publishwarn:
        user = users.getUserFromRequest(req)
        if dir:
            uploaddir = dir
        else:
            uploaddir = getUploadDir(user)
        unpublishedlink = "edit_content?tab=publish&id=" "" + uploaddir.id

    return req.getTAL("web/edit/edit_common.html", {
        "notpublished": notpublished,
        "chkjavascript": chkjavascript,
        "unpublishedlink": unpublishedlink,
        "nodelist": nodelist,
        "script_array": script_array,
        "language": lang(req)
    },
                      macro="show_nodelist")
Example #2
0
def shownodelist(req, nodes, publishwarn=1, markunpublished=0, dir=None):
    req.session["nodelist"] = EditorNodeList(nodes)
    script_array = "allobjects = new Array();\n"
    nodelist = []

    user = users.getUserFromRequest(req)

    for child in nodes:
        try:
            if isDirectory(child) or isCollection(child):
                continue
            script_array += "allobjects['%s'] = 0;\n" % child.id
            nodelist.append(child)
        except TypeError:
            continue

    chkjavascript = ""
    notpublished = {}
    if publishwarn or markunpublished:
        homedir = getHomeDir(user)
        homedirs = getAllSubDirs(homedir)
        if markunpublished:
            chkjavascript = """<script language="javascript">"""
        for node in nodes:
            ok = 0
            for p in node.getParents():
                if p not in homedirs:
                    ok = 1
            if not ok:
                if markunpublished:
                    chkjavascript += """allobjects['check%s'] = 1;
                                        document.getElementById('check%s').checked = true;
                                     """ % (node.id, node.id)

                notpublished[node] = node
        chkjavascript += """</script>"""
        # if all nodes are properly published, don't bother
        # to warn the user
        if not notpublished:
            publishwarn = 0

    unpublishedlink = None
    if publishwarn:
        user = users.getUserFromRequest(req)
        if dir:
            uploaddir = dir
        else:
            uploaddir = getUploadDir(user)
        unpublishedlink = "edit_content?tab=publish&id=""" + uploaddir.id

    return req.getTAL("web/edit/edit_common.html", {"notpublished": notpublished, "chkjavascript": chkjavascript, "unpublishedlink": unpublishedlink, "nodelist": nodelist, "script_array": script_array, "language": lang(req)}, macro="show_nodelist")
Example #3
0
def action(req):
    global editModules
    language = lang(req)
    user = current_user

    trashdir = user.trash_dir
    uploaddir = user.upload_dir

    trashdir_parents = trashdir.parents
    action = req.params.get("action", "")
    changednodes = {}

    if not user.is_editor:
        req.write("""permission denied""")
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return

    if "tab" in req.params:
        tab = req.params.get("tab").split("_")[-1]
        return editModules[tab].getContent(req, [req.params.get("id")])

    if action == "getlabels":
        nids = req.params.get('ids', [])
        nids = [nid.strip() for nid in nids.split(',') if nid.strip()]

        for nid in set(nids + [_n.id for _n in [trashdir, uploaddir]]):
            try:
                changednodes[nid] = getTreeLabel(q(Node).get(nid), language)
            except:
                logg.exception("exception ignored: could not make fancytree label for node %s", nid)
        res_dict = {'changednodes': changednodes}
        req.write(json.dumps(res_dict, indent=4, ensure_ascii=False))
        return

    else:
        # all 'action's except 'getlabels' require a base dir (src)
        # but expanding of a subdir in the edit-tree via fancytree has
        # not a srcid, so no action is necessary
        srcid = req.params.get("src")
        if not srcid:
            return
        try:
            src = q(Node).get(srcid)
        except:
            req.writeTAL(
                "web/edit/edit.html", {"edit_action_error": srcid}, macro="edit_action_error")
            return

    if req.params.get('action') == 'addcontainer':
        node = q(Node).get(srcid)
        if not node.has_write_access():
            # deliver errorlabel
            req.writeTALstr(
                '<tal:block i18n:translate="edit_nopermission"/>', {})
            return
        # create new container
        newnode_type = req.params.get('type')
        if newnode_type in ['bare_collection', 'bare_directory']:
            newnode_type = newnode_type.replace('bare_', '')

        translated_label = t(lang(req), 'edit_add_' + newnode_type)
        if translated_label.startswith('edit_add_'):
            translated_label = t(
                lang(req), 'edit_add_container_default') + newnode_type

        content_class = Node.get_class_for_typestring(newnode_type)
        newnode = content_class(name=translated_label)
        node.children.append(newnode)
        newnode.set("creator", user.login_name)
        newnode.set("creationtime", unicode(
            time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime(time.time()))))
        newnode.set("nodename", translated_label)  # set attribute named "nodename" to label text
        # place newnode at top of the children by setting the orderpos to the lowest orderpos - 1
        # if the orderpos gets negative, shift the oderpos of all children by incrementing with a positive number
        # make this number large enough, to avoid the next shifting of orderpos if more containers are added
        if len(node.children) == 1:
            # newnode is the only one child
            newnode.orderpos = 1000
        else:
            newnode.orderpos = node.children[0].orderpos
            newnode.orderpos = min([c.orderpos for c in node.children]) - 1
            while newnode.orderpos < 0:
                # in order to avoid negative orderpos, add a positive number to the orderpos of all children
                # make this number large enough, so there is no shift of orderpos is necessary if the next
                # container is added to the children
                for c in node.children:
                    c.orderpos += 1000
        db.session.commit()
        req.params["dest"] = newnode.id

        label = getTreeLabel(newnode, lang=language)

        fancytree_nodedata = {
            'title': label,
            'key': newnode.id,
            'isLazy': False,
            'isFolder': True,
            'icon': getEditorIconPath(newnode),
            'readonly': 0,
            'tooltip': '%s (%s)' % (label, newnode.id),
            'children': [],
        }

        req.write(json.dumps(fancytree_nodedata, ensure_ascii=False))
        logg.info("%s adding new container %s (%s) to %s (%s, %s)",
                  user.login_name, newnode.id, newnode.type, node.id, node.name, node.type)
        return

    try:
        destid = req.params.get("dest", None)
        dest = q(Node).get(destid)
        folderid = destid
    except:
        destid = None
        dest = None
        folderid = srcid

    idlist = getIDs(req)
    mysrc = None
    errorobj = None

    # try:
    if action == "clear_trash":
        for n in trashdir.children:
            # if trashdir is it's sole parent, remove file from disk
            # attn: this will not touch files from children of deleted
            # containers
            if len(n.parents) == 1:
                logg.info("%s going to remove files from disk for node %s (%s, %s)", user.login_name, n.id, n.name, n.type)
                for f in n.files:
                    # dangerous ??? check this
                    f_path = f.abspath
                    if os.path.exists(f_path):
                        logg.info("%s going to remove file %r from disk", user.login_name, f_path)
                        os.remove(f_path)
            trashdir.children.remove(n)
            db.session.commit()
            dest = trashdir
        changednodes[trashdir.id] = 1
        _parent_descr = [(p.name, p.id, p.type) for p in trashdir_parents]
        logg.info("%s cleared trash folder with id %s, child of %s", user.login_name, trashdir.id, _parent_descr)
        # return
    else:
        for id in idlist:
            obj = q(Node).get(id)
            mysrc = src

            if isDirectory(obj) or isCollection(obj):
                mysrc = obj.parents[0]

            if action == "delete":
                if mysrc.has_write_access() and obj.has_write_access():
                    if mysrc.id != trashdir.id:
                        mysrc.children.remove(obj)
                        changednodes[mysrc.id] = 1
                        trashdir.children.append(obj)
                        db.session.commit()
                        changednodes[trashdir.id] = 1
                        logg.info("%s moved to trash bin %s (%s, %s) from %s (%s, %s)",
                                  user.login_name, obj.id, obj.name, obj.type, mysrc.id, mysrc.name, mysrc.type)
                        dest = mysrc

                else:
                    logg.info("%s has no write access for node %s", user.login_name, mysrc.id)
                    req.writeTALstr(
                        '<tal:block i18n:translate="edit_nopermission"/>', {})
                dest = mysrc

            elif action in ["move", "copy"]:

                if (dest != mysrc) and \
                            mysrc.has_write_access() and \
                            dest.has_write_access() and \
                            obj.has_write_access() and \
                            isinstance(dest, Container):
                    if not dest.is_descendant_of(obj):
                        if action == "move":
                            mysrc.children.remove(obj)
                            changednodes[mysrc.id] = 1  # getLabel(mysrc)
                        dest.children.append(obj)
                        changednodes[dest.id] = 1  # getLabel(dest)
                        db.session.commit()

                        if logg.isEnabledFor(logging.INFO):
                            _what = "%s %s %r (%s, %s) " % (
                                user.login_name, action, obj.id, obj.name, obj.type)
                            _from = "from %s (%s, %s) " % (
                                mysrc.id, mysrc.name, mysrc.type)
                            _to = "to %s (%s, %s)" % (
                                dest.id, dest.name, dest.type)
                            logg.info(_what + _from + _to)

                    else:
                        logg.error("%s could not %s %s from %s to %s", user.login_name, action, obj.id, mysrc.id, dest.id)
                else:
                    return
                mysrc = None

    if not mysrc:
        mysrc = src

    if action in ["move", "copy", "delete", "clear_trash"]:

        for nid in changednodes:
            try:
                changednodes[nid] = getTreeLabel(
                    q(Node).get(nid), lang=language)
            except:
                logg.exception("exception ignored: could not make fancytree label for node %s", nid)
        res_dict = {'changednodes': changednodes}
        req.write(json.dumps(res_dict, indent=4, ensure_ascii=False))
    else:
        try:
            if dest is not None:
                req.write(dest.id)
            else:
                req.write('no-node-id-specified (web.edit.edit.action)')
        except:
            req.write('no-node-id-specified (web.edit.edit.action)')
            logg.exception('exception ignored, no-node-id-specified (web.edit.edit.action)')
    return
Example #4
0
    def feedback(self, req):
        Portlet.feedback(self, req)
        self.lang = lang(req)
        if "dir" in req.params or "id" in req.params:
            id = req.params.get("id", req.params.get("dir"))
            try:
                node = tree.getNode(id)
                if isCollection(node):
                    self.collection = node
                    self.directory = node
                else:
                    if isDirectory(node):
                        self.directory = node
                    else:
                        if not isDirectory(self.directory) or not isParentOf(node, self.directory):
                            self.directory = getDirectory(node)
                    if self.collection.type == "collections" or not isParentOf(node, self.collection):
                        self.collection = getCollection(node)
            except tree.NoSuchNodeError:
                pass
        try:
            self.hide_empty = self.collection.get("style_hide_empty") == "1"
        except:
            self.hide_empty = False
        access = AccessData(req)
        # open all parents, so we see that node
        opened = {}
        parents = [self.directory]
        counter = 0
        while parents:
            counter += 1
            if counter > 50:
                raise RecursionException
            p = parents.pop()
            opened[p.id] = 1
            parents += p.getParents()

        m = {}

        def f(m, node, indent, hide_empty):
            if indent > 15:
                raise RecursionException
            if not access.hasReadAccess(node):
                return

            count = -1
            m[node.id] = e = NavTreeEntry(self, node, indent, node.type == "directory", hide_empty=hide_empty, lang=self.lang)
            if node.id in opened or e.defaultopen:
                m[node.id].folded = 0
                for c in node.getContainerChildren():
                    if c.get("style_hide_empty") == "1":
                        hide_empty = 1
                    f(m, c, indent + 1, hide_empty)

        f(m, tree.getRoot("collections"), 0, self.hide_empty)

        if "cunfold" in req.params:
            id = req.params["cunfold"]
            if id in m:
                m[id].folded = 0

        if self.directory.id in m:
            m[self.directory.id].folded = 0
            m[self.directory.id].active = 1

        if self.collection.id in m:
            m[self.collection.id].active = 1

        col_data = []

        def f(col_data, node, indent):
            if indent > 15:
                raise RecursionException
            if node.id not in m:
                return

            data = m[node.id]
            col_data += [data]
            if not data.folded or data.defaultopen:
                for c in node.getContainerChildren().sort_by_orderpos():
                    f(col_data, c, indent + 1)

        f(col_data, tree.getRoot("collections"), 0)
        self.col_data = col_data
Example #5
0
def action(req):
    global editModules
    language = lang(req)
    user = current_user

    trashdir = user.trash_dir
    uploaddir = user.upload_dir

    trashdir_parents = trashdir.parents
    action = req.params.get("action", "")
    changednodes = {}

    if not user.is_editor:
        req.write("""permission denied""")
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return

    if "tab" in req.params:
        tab = req.params.get("tab").split("_")[-1]
        return editModules[tab].getContent(req, [req.params.get("id")])

    if action == "getlabels":
        nids = req.params.get('ids', [])
        nids = [nid.strip() for nid in nids.split(',') if nid.strip()]

        for nid in set(nids + [_n.id for _n in [trashdir, uploaddir]]):
            try:
                changednodes[nid] = getTreeLabel(q(Node).get(nid), language)
            except:
                logg.exception(
                    "exception ignored: could not make fancytree label for node %s",
                    nid)
        res_dict = {'changednodes': changednodes}
        req.write(json.dumps(res_dict, indent=4, ensure_ascii=False))
        return

    else:
        # all 'action's except 'getlabels' require a base dir (src)
        # but expanding of a subdir in the edit-tree via fancytree has
        # not a srcid, so no action is necessary
        srcid = req.params.get("src")
        if not srcid:
            return
        try:
            src = q(Node).get(srcid)
        except:
            req.writeTAL("web/edit/edit.html", {"edit_action_error": srcid},
                         macro="edit_action_error")
            return

    if req.params.get('action') == 'addcontainer':
        node = q(Node).get(srcid)
        if not node.has_write_access():
            # deliver errorlabel
            req.writeTALstr('<tal:block i18n:translate="edit_nopermission"/>',
                            {})
            return
        # create new container
        newnode_type = req.params.get('type')
        if newnode_type in ['bare_collection', 'bare_directory']:
            newnode_type = newnode_type.replace('bare_', '')

        translated_label = t(lang(req), 'edit_add_' + newnode_type)
        if translated_label.startswith('edit_add_'):
            translated_label = t(lang(req),
                                 'edit_add_container_default') + newnode_type

        content_class = Node.get_class_for_typestring(newnode_type)
        newnode = content_class(name=translated_label)
        node.children.append(newnode)
        newnode.set("creator", user.login_name)
        newnode.set(
            "creationtime",
            unicode(
                time.strftime('%Y-%m-%dT%H:%M:%S',
                              time.localtime(time.time()))))
        newnode.set(
            "nodename",
            translated_label)  # set attribute named "nodename" to label text
        # place newnode at top of the children by setting the orderpos to the lowest orderpos - 1
        # if the orderpos gets negative, shift the oderpos of all children by incrementing with a positive number
        # make this number large enough, to avoid the next shifting of orderpos if more containers are added
        if len(node.children) == 1:
            # newnode is the only one child
            newnode.orderpos = 1000
        else:
            newnode.orderpos = node.children[0].orderpos
            newnode.orderpos = min([c.orderpos for c in node.children]) - 1
            while newnode.orderpos < 0:
                # in order to avoid negative orderpos, add a positive number to the orderpos of all children
                # make this number large enough, so there is no shift of orderpos is necessary if the next
                # container is added to the children
                for c in node.children:
                    c.orderpos += 1000
        db.session.commit()
        req.params["dest"] = newnode.id

        label = getTreeLabel(newnode, lang=language)

        fancytree_nodedata = {
            'title': label,
            'key': newnode.id,
            'isLazy': False,
            'isFolder': True,
            'icon': getEditorIconPath(newnode),
            'readonly': 0,
            'tooltip': '%s (%s)' % (label, newnode.id),
            'children': [],
        }

        req.write(json.dumps(fancytree_nodedata, ensure_ascii=False))
        logg.info("%s adding new container %s (%s) to %s (%s, %s)",
                  user.login_name, newnode.id, newnode.type, node.id,
                  node.name, node.type)
        return

    try:
        destid = req.params.get("dest", None)
        dest = q(Node).get(destid)
        folderid = destid
    except:
        destid = None
        dest = None
        folderid = srcid

    idlist = getIDs(req)
    mysrc = None
    errorobj = None

    # try:
    if action == "clear_trash":
        for n in trashdir.children:
            # if trashdir is it's sole parent, remove file from disk
            # attn: this will not touch files from children of deleted
            # containers
            if len(n.parents) == 1:
                logg.info(
                    "%s going to remove files from disk for node %s (%s, %s)",
                    user.login_name, n.id, n.name, n.type)
                for f in n.files:
                    # dangerous ??? check this
                    f_path = f.abspath
                    if os.path.exists(f_path):
                        logg.info("%s going to remove file %r from disk",
                                  user.login_name, f_path)
                        os.remove(f_path)
            trashdir.children.remove(n)
            db.session.commit()
            dest = trashdir
        changednodes[trashdir.id] = 1
        _parent_descr = [(p.name, p.id, p.type) for p in trashdir_parents]
        logg.info("%s cleared trash folder with id %s, child of %s",
                  user.login_name, trashdir.id, _parent_descr)
        # return
    else:
        for id in idlist:
            obj = q(Node).get(id)
            mysrc = src

            if isDirectory(obj) or isCollection(obj):
                mysrc = obj.parents[0]

            if action == "delete":
                if mysrc.has_write_access() and obj.has_write_access():
                    if mysrc.id != trashdir.id:
                        mysrc.children.remove(obj)
                        changednodes[mysrc.id] = 1
                        trashdir.children.append(obj)
                        db.session.commit()
                        changednodes[trashdir.id] = 1
                        logg.info(
                            "%s moved to trash bin %s (%s, %s) from %s (%s, %s)",
                            user.login_name, obj.id, obj.name, obj.type,
                            mysrc.id, mysrc.name, mysrc.type)
                        dest = mysrc

                else:
                    logg.info("%s has no write access for node %s",
                              user.login_name, mysrc.id)
                    req.writeTALstr(
                        '<tal:block i18n:translate="edit_nopermission"/>', {})
                dest = mysrc

            elif action in ["move", "copy"]:

                if (dest != mysrc) and \
                            mysrc.has_write_access() and \
                            dest.has_write_access() and \
                            obj.has_write_access() and \
                            isinstance(dest, Container):
                    if not dest.is_descendant_of(obj):
                        if action == "move":
                            mysrc.children.remove(obj)
                            changednodes[mysrc.id] = 1  # getLabel(mysrc)
                        dest.children.append(obj)
                        changednodes[dest.id] = 1  # getLabel(dest)
                        db.session.commit()

                        if logg.isEnabledFor(logging.INFO):
                            _what = "%s %s %r (%s, %s) " % (user.login_name,
                                                            action, obj.id,
                                                            obj.name, obj.type)
                            _from = "from %s (%s, %s) " % (
                                mysrc.id, mysrc.name, mysrc.type)
                            _to = "to %s (%s, %s)" % (dest.id, dest.name,
                                                      dest.type)
                            logg.info(_what + _from + _to)

                    else:
                        logg.error("%s could not %s %s from %s to %s",
                                   user.login_name, action, obj.id, mysrc.id,
                                   dest.id)
                else:
                    return
                mysrc = None

    if not mysrc:
        mysrc = src

    if action in ["move", "copy", "delete", "clear_trash"]:

        for nid in changednodes:
            try:
                changednodes[nid] = getTreeLabel(q(Node).get(nid),
                                                 lang=language)
            except:
                logg.exception(
                    "exception ignored: could not make fancytree label for node %s",
                    nid)
        res_dict = {'changednodes': changednodes}
        req.write(json.dumps(res_dict, indent=4, ensure_ascii=False))
    else:
        try:
            req.write(dest.id)
        except:
            req.write('no-node-id-specified (web.edit.edit.action)')
            logg.exception(
                'exception ignored, no-node-id-specified (web.edit.edit.action)'
            )
    return