Esempio n. 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")
Esempio n. 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")
Esempio n. 3
0
def handle_json_request(req):
    s = []
    if req.params.get("cmd") == "get_list_smi":
        searchmaskitem_id = req.params.get("searchmaskitem_id")
        f = None
        g = None
        if searchmaskitem_id and searchmaskitem_id != "full":
            f = tree.getNode(searchmaskitem_id).getFirstField()
        if not f:  # All Metadata
            f = g = getMetadataType("text")
        s = [
            f.getSearchHTML(
                Context(g,
                        value=req.params.get("query_field_value"),
                        width=174,
                        name="query" + str(req.params.get("fieldno")),
                        language=lang(req),
                        collection=tree.getNode(
                            req.params.get("collection_id")),
                        user=users.getUserFromRequest(req),
                        ip=req.ip))
        ]
    req.write(
        req.params.get("jsoncallback") + "(%s)" % json.dumps(s, indent=4))
    return
Esempio n. 4
0
def pwdchange(req, error=0):
    if len(req.params) > 2 and "password_old" not in req.params:  # user changed to browsing
        return buildURL(req)

    user = users.getUserFromRequest(req)

    if not user.canChangePWD() and not user.isAdmin():
        error = 4  # no rights

    elif "ChangeSubmit" in req.params:
        if user.getName() == config.get("user.guestuser"):
            req.request["Location"] = req.makeLink("node", {"id": tree.getRoot("collections").id})
            return httpstatus.HTTP_MOVED_TEMPORARILY

        else:
            if not users.checkLogin(user.getName(), req.params.get("password_old")):
                error = 1  # old pwd does not match

            elif req.params.get("password_new1") != req.params.get("password_new2"):
                error = 2  # new pwds do not match

            else:
                user.setPassword(req.params.get("password_new2"))
                req.request["Location"] = req.makeLink("node", {"id": tree.getRoot("collections").id})
                return httpstatus.HTTP_MOVED_TEMPORARILY

    navframe = frame.getNavigationFrame(req)
    navframe.feedback(req)
    contentHTML = req.getTAL(theme.getTemplate("login.html"), {"error": error, "user": user}, macro="change_pwd")
    navframe.write(req, contentHTML)
    return httpstatus.HTTP_OK
Esempio n. 5
0
def import_new(req):
    reload(bibtex)
    user = users.getUserFromRequest(req)
    importdir= users.getImportDir(user)
    del req.params["upload"]

    if "file" in req.params and req.params["doi"]:
        req.request["Location"] = req.makeLink("content", {"id":importdir.id, "error":"doi_and_bibtex_given"})
        req.params["error"] = "doi_and_bibtex_given"

        msg_t = (user.getName(), importdir.id, importdir.name, importdir.type, req.params["error"])
        msg = "%s using import module for node %r (%r, %r): Error: %r" % msg_t
        logg.info(msg)

    elif "file" in req.params.keys():
        file = req.params["file"]
        del req.params["file"]
        if hasattr(file,"filesize") and file.filesize>0:
            try:
                bibtex.importBibTeX(file.tempname, importdir, req)
                req.request["Location"] = req.makeLink("content", {"id":importdir.id})
            except ValueError, e:
                req.request["Location"] = req.makeLink("content", {"id":importdir.id, "error":str(e)})
                req.params["error"] = str(e)
            except bibtex.MissingMapping,e:
                req.request["Location"] = req.makeLink("content", {"id":importdir.id, "error":str(e)})
                req.params["error"] = str(e)
            except:
Esempio n. 6
0
    def feedback(self, req):
        user = users.getUserFromRequest(req)

        userlinks = UserLinks(user, area=req.session.get("area"))
        userlinks.feedback(req)

        # tabs
        navigation = {}

        # collection
        collection_portlet = self.collection_portlet
        collection_portlet.feedback(req)
        col_selected = collection_portlet.collection
        navigation["collection"] = collection_portlet

        # search
        search_portlet = self.cmap.getSearch(col_selected)
        search_portlet.feedback(req)
        navigation["search"] = search_portlet

        # languages
        front_lang = {}
        front_lang["name"] = config.get("i18n.languages").split(",")
        front_lang["actlang"] = lang(req)

        self.params = {"show_navbar": True, "user": user, "userlinks": userlinks, "navigation": navigation, "language": front_lang}
Esempio n. 7
0
def handletabs(req, ids, tabs):
    user = users.getUserFromRequest(req)
    language = lang(req)

    n = tree.getNode(ids[0])
    if n.type.startswith("workflow"):
        n = tree.getRoot()

    menu = filterMenu(getEditMenuString(n.getContentType()), user)

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

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

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

    # a html snippet may be inserted in the editor header
    help_link = tree.getRoot("collections").get("system.editor.help.link." + language).strip()
    ctx = {
        "user": user,
        "ids": ids,
        "idstr": ",".join(ids),
        "menu": menu,
        "hashelp": help.getHelpPath(["edit", "modules", req.params.get("tab") or tabs]),
        "breadcrumbs": getBreadcrumbs(menu, req.params.get("tab", tabs)),
        "spc": spc,
        "system_editor_help_link": help_link,
    }
    return req.getTAL("web/edit/edit.html", ctx, macro="edit_tabs")
Esempio n. 8
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. 9
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. 10
0
def handletabs(req, ids, tabs):
    user = users.getUserFromRequest(req)
    language = lang(req)

    n = tree.getNode(ids[0])
    if n.type.startswith("workflow"):
        n = tree.getRoot()

    menu = filterMenu(getEditMenuString(n.getContentType()), user)

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

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

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

    # a html snippet may be inserted in the editor header
    help_link = tree.getRoot('collections').get('system.editor.help.link.' + language).strip()
    ctx = {
            "user": user,
            "ids": ids,
            "idstr": ",".join(ids),
            "menu": menu,
            "hashelp": help.getHelpPath(['edit', 'modules', req.params.get('tab') or tabs]),
            "breadcrumbs": getBreadcrumbs(menu, req.params.get("tab", tabs)),
            "spc": spc,
            "system_editor_help_link": help_link,
            }
    return req.getTAL("web/edit/edit.html", ctx, macro="edit_tabs")
Esempio n. 11
0
def show_node(req):
    """ opens administration window with content """

    p = req.path[1:].split("/")
    style = req.params.get("style", "")
    user = users.getUserFromRequest(req)

    v = {}
    v["user"] = user
    v["guestuser"] = config.get("user.guestuser")
    v["version"] = mediatum_version
    v["content"] = show_content(req, p[0])
    v["navigation"] = adminNavigation()
    v["breadcrumbs"] = getMenuItemID(v["navigation"], req.path[1:])
    v["spc"] = list()

    spc = list()
    v["spc"].append(Menu("sub_header_frontend", "/"))
    v["spc"].append(Menu("sub_header_edit", "/edit"))
    if user.isWorkflowEditor():
        v["spc"].append(Menu("sub_header_workflow", "../publish"))
    v["spc"].append(Menu("sub_header_logout", "/logout"))
    v["hashelp"] = help.getHelpPath(
        ['admin', 'modules', req.path.split('/')[1]])

    if len(p) > 0:
        if style == "":
            req.writeTAL("web/admin/frame.html", v, macro="frame")
        else:
            req.write(v["content"])
Esempio n. 12
0
def show_node(req):
    """ opens administration window with content """

    p = req.path[1:].split("/")
    style = req.params.get("style", "")
    user = users.getUserFromRequest(req)

    v = {}
    v["user"] = user
    v["guestuser"] = config.get("user.guestuser")
    v["version"] = mediatum_version
    v["content"] = show_content(req, p[0])
    v["navigation"] = adminNavigation()
    v["breadcrumbs"] = getMenuItemID(v["navigation"], req.path[1:])
    v["spc"] = list()

    spc = list()
    v["spc"].append(Menu("sub_header_frontend", "/"))
    v["spc"].append(Menu("sub_header_edit", "/edit"))
    if user.isWorkflowEditor():
        v["spc"].append(Menu("sub_header_workflow", "../publish"))
    v["spc"].append(Menu("sub_header_logout", "/logout"))
    v["hashelp"] = help.getHelpPath(['admin', 'modules', req.path.split('/')[1]])

    if len(p) > 0:
        if style == "":
            req.writeTAL("web/admin/frame.html", v, macro="frame")
        else:
            req.write(v["content"])
Esempio n. 13
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    access = AccessData(req)
    node = tree.getNode(ids[0])

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

    c = getCollection(node)

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

    class SortChoice:

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

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

    return req.getTAL("web/edit/modules/sortfiles.html", {"node": node, "collection_sortfield": collection_sortfield,
                                                          "sortchoices": sortfields, "name": c.getName()}, macro="edit_sortfiles")
Esempio n. 14
0
 def feedback(self, req):
     self.user = users.getUserFromRequest(req)
     r = req.params.get(self.name, "")
     if r == "unfold":
         self.open()
     elif r == "fold":
         self.close()
     self.language = lang(req)
Esempio n. 15
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    access = AccessData(req)
    language = lang(req)
    node = tree.getNode(ids[0])
    
    if "sort" in users.getHideMenusForUser(user) or not access.hasWriteAccess(node):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

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

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

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

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

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

    for field in fields:
        if i == fields[field]:
            attributes.append(field)
    ctx = {
            "node": node,
            "nodelist": nodelist,
            "sortattributes": sorted(attributes, lambda x, y: cmp(x.getLabel().lower(), y.getLabel().lower())),
            "language": language,
           }
    return req.getTAL("web/edit/modules/subfolder.html", ctx, macro="edit_subfolder")
Esempio n. 16
0
def search_results(req, id):
    access = AccessData(req)
    user = users.getUserFromRequest(req)
    if "search" in users.getHideMenusForUser(user):
        req.writeTAL("web/edit/edit.html", {}, macro="access_error")
        return ""

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

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

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

    query = ""

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

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

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

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

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

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

    return search_form(req, id, "edit_search_noresult_msg")
Esempio n. 17
0
 def __init__(self, req=None, user=None, ip=None):
     if req is not None:
         self.user = users.getUserFromRequest(req)
         self.ip = req.ip or "127.0.0.1"
     else:
         self.user = user
         self.ip = ip or "127.0.0.1"
     self.level = None
     self.allowed_rules = {}
Esempio n. 18
0
def getHelp(req):
    global menustructure, items, paths, all_paths, index

    v = {'user': getUserFromRequest(req)}

    if "language_change" in req.params:  # change language
        req.session["language"] = req.params.get('language_change')
    language = translation.lang(req)

    if "edit.x" in req.params:  # edit content
        print "edit page"

    if "refresh.x" in req.params:  # refresh content
        menustructure = []
        index = {}
        items = {}
        paths = {}
        all_paths = {}
        initHelp()

    if req.path[-1] == "/":
        req.path = req.path[:-1]

    if re.sub('^\.', '', req.path.replace("/", ".")) in all_paths:
        pathlangs = all_paths[re.sub('^\.', '', req.path.replace("/", "."))]
        if language not in pathlangs:
            content = getHelpFileContent(req.path, pathlangs[0])
        else:
            content = getHelpFileContent(req.path, language)
    else:  # page not found 404
        req.setStatus(httpstatus.HTTP_NOT_FOUND)
        content = req.getTAL(theme.getTemplate("help.html"), {}, macro='notfound')

    if "export" in req.params:
        if req.params.get('export') == "pdf":
            print "deliver pdf"
            req.reply_headers['Content-Type'] = "application/pdf; charset=utf-8"
            content = content.replace('"/help/', '"http://' + config.get('host.name') + '/help/')
            req.write(buildHelpPDF(req.params.get('url'), language))
            return
    if language not in menustructure:
        menustructure.append(language)
        for path in all_paths:
            addExtItem(language, path, items[language])

    v['content'] = content
    v['languages'] = config.get('i18n.languages').split(',')
    v['curlang'] = translation.lang(req)
    v['items'] = items[translation.lang(req)]
    v['path'] = req.path.split("/")[1:]
    v['url'] = req.path
    v['indexvalues'] = index[language]
    indexchars = sorted(set([i[0].upper() for i in index[language].keys()]))
    v['indexchars'] = indexchars
    req.writeTAL(theme.getTemplate("help.html"), v, macro='help')
Esempio n. 19
0
def search_results(req,id):
    access = AccessData(req)
    user = users.getUserFromRequest(req)
    if "search" in users.getHideMenusForUser(user):
        req.writeTAL("web/edit/edit.html", {}, macro="access_error")
        return ""

    if "Reset" in req.params:
        return search_form(req, id, "edit_search_reset_msg")
    
    try:
        searchvalues = req.session["esearchvals"]
    except:
        req.session["esearchvals"] = searchvalues = {}

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

    if "full" in req.params:
        value = req.params["full"]
        searchvalues[objtype + ".full"] = value
        for word in value.split(" "):
            if word:
                if query:
                    query += " and "
                query += "full=" + protect(word)
 
    for field in type.getMetaFields():
        if field.Searchfield():
            name=field.getName()
            if name in req.params and req.params.get(name,"").replace("'",'').replace('"','').strip()!="":
                value = req.params[name].strip()
                
                if value:
                    searchvalues[objtype + "." + field.getName()] = value
                    if field.getFieldtype()=="list" or field.getFieldtype()=="ilist" or field.getFieldtype()=="mlist":
                        if query:
                            query += " and "
                        query += name + "=" + protect(value)
                    else:
                        query += name + "=" + protect(value)

    query += ' and schema="'+req.params.get("objtype","*")+'"'
                                
    utrace.info(access.user.name + " search for "+query)
    nodes = node.search(query)
    req.session["nodelist"] = EditorNodeList(nodes)

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

    return search_form(req, id, "edit_search_noresult_msg")
Esempio n. 20
0
def getContent(req, ids):
    if req.params.get("style","")=="popup":
        req.write(objlist(req))
        return ""
    
    user = users.getUserFromRequest(req)
    if "license" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")
        
    node = tree.getNode(ids[0])
    return req.getTAL("web/edit/modules/license.html", {"node":node, "nodes": [node]}, macro="edit_license_info")
Esempio n. 21
0
def flush_maskcache(req=None):
    global maskcache, maskcache_accesscount, maskcache_shallow, maskcache_msg
    logging.getLogger("everything").info("going to flush maskcache, content is: \r\n" + get_maskcache_report())
    maskcache = {}
    maskcache_accesscount = {}
    maskcache_shallow = {}
    if req:
        user = users.getUserFromRequest(req)
        logging.getLogger("everything").info("flush of masks cache triggered by user %s with request on '%s'" % (user.name, req.path))

        sys.stdout.flush()
    maskcache_msg = '| cache last flushed %s\r\n|\r\n' % cache_date2string(time.time(), '%04d-%02d-%02d-%02d-%02d-%02d')
Esempio n. 22
0
def getContent(req, ids):
    if len(ids) > 0:
        ids = ids[0]

    user = users.getUserFromRequest(req)
    node = tree.getNode(ids)
    access = acl.AccessData(req)

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

    if "update_stat" in req.params.keys():  # reset stored statistics data
        msg = "user %r requests update of of system.statscontent for node %r (%r, %r)" % (
            user.getName(), node.id, node.name, node.type)
        logger.info(msg)
        logging.getLogger('editor').info(msg)
        node.removeAttribute("system.statscontent")
        node.removeAttribute("system.statsdate")

    # content
    if req.params.get("style", "") == "popup":
        statstring = node.get("system.statscontent")

        if statstring == "":  # load stats from objects/renew stat
            data = StatTypes()
            for n in node.getAllChildren():
                found_dig = 0 or len([
                    file for file in n.getFiles()
                    if file.type in ["image", "document", "video"]
                ])
                data.addItem(n.getContentType(), n.getSchema(), found_dig)

            node.set("system.statscontent", str(data))
            node.set("system.statsdate", str(format_date()))
            statstring = str(data)

        v = {}
        v["data"] = StatTypes(statstring)

        v["stand"] = node.get("system.statsdate")

        req.writeTAL("web/edit/modules/statsfiles.html",
                     v,
                     macro="edit_stats_popup")
        return ""

    return req.getTAL("web/edit/modules/statsfiles.html", {"id": ids},
                      macro="edit_stats")
Esempio n. 23
0
def getContent(req, ids):
    if len(ids) > 0:
        ids = ids[0]

    user = users.getUserFromRequest(req)
    node = tree.getNode(ids)
    access = acl.AccessData(req)

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

    if req.params.get("style", "") == "popup":
        getPopupWindow(req, ids)
        return ""

    node = tree.getNode(ids)
    statfiles = {}
    p = ""

    for file in node.getFiles():
        if file.getType() == "statistic":
            period, type = getPeriod(file.retrieveFile())
            if period > p:
                p = period

            if type not in statfiles.keys():
                statfiles[type] = {}

            if period not in statfiles[type].keys():
                statfiles[type][period] = []
            statfiles[type][period].append(file)

    v = {}
    v["id"] = ids
    v["files"] = statfiles
    v["current_period"] = req.params.get("select_period", "frontend_" + p)
    if len(statfiles) > 0:
        v["current_file"] = StatisticFile(statfiles[v["current_period"].split(
            "_")[0]][v["current_period"].split("_")[1]][0])
    else:
        v["current_file"] = StatisticFile(None)
    v["nodename"] = tree.getNode

    items = v["current_file"].getProgress('country')
    return req.getTAL("web/edit/modules/statsaccess.html",
                      v,
                      macro="edit_stats")
Esempio n. 24
0
def show_content(req, op):
    user = users.getUserFromRequest(req)

    if not user.inGroup(config.get('user.admingroup')):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/admin/frame.html", {}, macro="errormessage")
    else:
        if op == "" or op not in getRoot().get("admin.menu"):
            op = "menumain"
        module = findmodule(op.split("_")[0])

        try:
            if op.index("_") > -1:
                return module.spc(req, op)
        except:
            return module.validate(req, op)
Esempio n. 25
0
 def getSearchField(self, i, width=174):
     try:
         f = None
         if self.names[i] and self.names[i] != "full":
             f = tree.getNode(self.names[i]).getFirstField()
         g = None
         if f is None:  # All Metadata
             # quick&dirty
             f = g = getMetadataType("text")
         return f.getSearchHTML(Context(g, value=self.values[i], width=width, name="query" + str(i),
                                        language=lang(self.req), collection=self.collection,
                                        user=users.getUserFromRequest(self.req), ip=self.req.ip))
     except:
         # workaround for unknown error
         logException("error during getSearchField(i)")
         return ""
Esempio n. 26
0
def getAdminStdVars(req):
    page = ""
    if req.params.get("page", "") == "0":
        page = "?page=0"

    user = users.getUserFromRequest(req)

    tabs = [("0-9", "09")]
    for i in range(65, 91):
        tabs.append((unichr(i), unichr(i)))
    tabs.append(("admin_filter_else", "-"))
    tabs.append(("admin_filter_all", "*"))

    actpage = req.params.get("page", req.params.get("actpage", "1"))
    return {"user": user, "page": page, "op": req.params.get(
        "op", ""), "tabs": tabs, "actpage": actpage, "actfilter": req.params.get("actfilter", "")}
Esempio n. 27
0
def flush_maskcache(req=None):
    global maskcache, maskcache_accesscount, maskcache_shallow, maskcache_msg
    logging.getLogger("everything").info(
        "going to flush maskcache, content is: \r\n" + get_maskcache_report())
    maskcache = {}
    maskcache_accesscount = {}
    maskcache_shallow = {}
    if req:
        user = users.getUserFromRequest(req)
        logging.getLogger("everything").info(
            "flush of masks cache triggered by user %s with request on '%s'" %
            (user.name, req.path))

        sys.stdout.flush()
    maskcache_msg = '| cache last flushed %s\r\n|\r\n' % cache_date2string(
        time.time(), '%04d-%02d-%02d-%02d-%02d-%02d')
Esempio n. 28
0
def getContent(req, ids):
    if len(ids) > 0:
        ids = ids[0]

    user = users.getUserFromRequest(req)
    node = tree.getNode(ids)
    access = acl.AccessData(req)

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

    if req.params.get("style", "") == "popup":
        getPopupWindow(req, ids)
        return ""

    node = tree.getNode(ids)
    statfiles = {}
    p = ""

    for file in node.getFiles():
        if file.getType() == "statistic":
            period, type = getPeriod(file.retrieveFile())
            if period > p:
                p = period

            if type not in statfiles.keys():
                statfiles[type] = {}

            if period not in statfiles[type].keys():
                statfiles[type][period] = []
            statfiles[type][period].append(file)

    v = {}
    v["id"] = ids
    v["files"] = statfiles
    v["current_period"] = req.params.get("select_period", "frontend_" + p)
    if len(statfiles) > 0:
        v["current_file"] = StatisticFile(statfiles[v["current_period"].split("_")[0]][v["current_period"].split("_")[1]][0])
    else:
        v["current_file"] = StatisticFile(None)
    v["nodename"] = tree.getNode

    items = v["current_file"].getProgress('country')
    return req.getTAL("web/edit/modules/statsaccess.html", v, macro="edit_stats")
Esempio n. 29
0
def getContent(req, ids):
    if len(ids) > 0:
        ids = ids[0]

    user = users.getUserFromRequest(req)
    node = tree.getNode(ids)
    access = acl.AccessData(req)

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

    if "update_stat" in req.params.keys():  # reset stored statistics data
        msg = "user %r requests update of of system.statscontent for node %r (%r, %r)" % (
            user.getName(), node.id, node.name, node.type)
        logger.info(msg)
        logging.getLogger('editor').info(msg)
        node.removeAttribute("system.statscontent")
        node.removeAttribute("system.statsdate")

    # content
    if req.params.get("style", "") == "popup":
        statstring = node.get("system.statscontent")

        if statstring == "":  # load stats from objects/renew stat
            data = StatTypes()
            for n in node.getAllChildren():
                found_dig = 0 or len(
                    [file for file in n.getFiles() if file.type in["image", "document", "video"]])
                data.addItem(n.getContentType(), n.getSchema(), found_dig)

            node.set("system.statscontent", str(data))
            node.set("system.statsdate", str(format_date()))
            statstring = str(data)

        v = {}
        v["data"] = StatTypes(statstring)

        v["stand"] = node.get("system.statsdate")

        req.writeTAL(
            "web/edit/modules/statsfiles.html", v, macro="edit_stats_popup")
        return ""

    return req.getTAL("web/edit/modules/statsfiles.html", {"id": ids}, macro="edit_stats")
Esempio n. 30
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    access = AccessData(user=user)
    language = lang(req)
    node = tree.getNode(ids[0])

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

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


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

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

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

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

    return _html
Esempio n. 31
0
def show_user_data(req):
    error = ""

    # XXX: dead code?
    if USE_EXAMPLES and 'examples' in req.params:
        try:
            import userdata_examples
            reload(userdata_examples)
        except Exception as e:
            log.error("Error loading examples:" + str(sys.exc_info()[0]) +
                      " " + str(sys.exc_info()[1]),
                      exc_info=True)

    if "jsonrequest" in req.params:
        python_callback_key = req.params.get("python_callback_key", "")
        if python_callback_key and python_callback_key in aclasses:
            req.write(aclasses[python_callback_key].callback(req=req))
        return

    user = users.getUserFromRequest(req)
    user_homedir = {}
    if not user.isGuest():
        user_homedir = users.getHomeDir(user)

    navframe = getNavigationFrame(req)
    navframe.feedback(req)

    udclasses = sorted([(uc.orderpos, uc) for uc in aclasses.values()])
    udclasses = [t[1] for t in udclasses]

    ctx = {
        "error": error,
        "user": user,
        "user_homedir": user_homedir,
        "pf": pf,
        "udclasses": udclasses,
        "req": req,
    }

    navframe.write(
        req,
        req.getTAL("web/frontend/userdata.html", ctx, macro="show_user_data"))

    return httpstatus.HTTP_OK
Esempio n. 32
0
def pwdchange(req, error=0):
    if len(
            req.params
    ) > 2 and "password_old" not in req.params:  # user changed to browsing
        return buildURL(req)

    user = users.getUserFromRequest(req)

    if not user.canChangePWD() and not user.isAdmin():
        error = 4  # no rights

    elif "ChangeSubmit" in req.params:
        if user.getName() == config.get("user.guestuser"):
            req.request["Location"] = req.makeLink(
                "node", {"id": tree.getRoot("collections").id})
            return httpstatus.HTTP_MOVED_TEMPORARILY

        else:
            if not users.checkLogin(user.getName(),
                                    req.params.get("password_old")):
                error = 1  # old pwd does not match

            elif req.params.get("password_new1") != req.params.get(
                    "password_new2"):
                error = 2  # new pwds do not match

            else:
                user.setPassword(req.params.get("password_new2"))
                req.request["Location"] = req.makeLink(
                    "node", {"id": tree.getRoot("collections").id})
                return httpstatus.HTTP_MOVED_TEMPORARILY

    navframe = frame.getNavigationFrame(req)
    navframe.feedback(req)
    contentHTML = req.getTAL(theme.getTemplate("login.html"), {
        "error": error,
        "user": user
    },
                             macro="change_pwd")
    navframe.write(req, contentHTML)
    return httpstatus.HTTP_OK
Esempio n. 33
0
def export(req):
    """ export definition: url contains /[type]/[id] """

    user = users.getUserFromRequest(req)
    if not user.isAdmin():
        return httpstatus.HTTP_FORBIDDEN

    path = req.path[1:].split("/")
    try:
        module = findmodule(path[1])

        tempfile = join_paths(config.get("paths.tempdir"), str(random.random()))
        file = open(tempfile, "w")
        file.write(module.export(req, path[2]))
        file.close()

        req.sendFile(tempfile, "application/xml")
        if os.sep == '/':  # Unix?
            os.unlink(tempfile)  # unlinking files while still reading them only works on Unix/Linux
    except:
        print "module has no export method"
Esempio n. 34
0
def show_user_data(req):
    error = ""

    # XXX: dead code?
    if USE_EXAMPLES and 'examples' in req.params:
        try:
            import userdata_examples
            reload(userdata_examples)
        except Exception as e:
            log.error("Error loading examples:" + str(sys.exc_info()[0]) + " " + str(sys.exc_info()[1]), exc_info=True)

    if "jsonrequest" in req.params:
        python_callback_key = req.params.get("python_callback_key", "")
        if python_callback_key and python_callback_key in aclasses:
            req.write(aclasses[python_callback_key].callback(req=req))
        return

    user = users.getUserFromRequest(req)
    user_homedir = {}
    if not user.isGuest():
        user_homedir = users.getHomeDir(user)

    navframe = getNavigationFrame(req)
    navframe.feedback(req)

    udclasses = sorted([(uc.orderpos, uc) for uc in aclasses.values()])
    udclasses = [t[1] for t in udclasses]

    ctx = {
        "error": error,
        "user": user,
        "user_homedir": user_homedir,
        "pf": pf,
        "udclasses": udclasses,
        "req": req,
    }

    navframe.write(req, req.getTAL("web/frontend/userdata.html", ctx, macro="show_user_data"))

    return httpstatus.HTTP_OK
Esempio n. 35
0
def getAdminStdVars(req):
    page = ""
    if req.params.get("page", "") == "0":
        page = "?page=0"

    user = users.getUserFromRequest(req)

    tabs = [("0-9", "09")]
    for i in range(65, 91):
        tabs.append((unichr(i), unichr(i)))
    tabs.append(("admin_filter_else", "-"))
    tabs.append(("admin_filter_all", "*"))

    actpage = req.params.get("page", req.params.get("actpage", "1"))
    return {
        "user": user,
        "page": page,
        "op": req.params.get("op", ""),
        "tabs": tabs,
        "actpage": actpage,
        "actfilter": req.params.get("actfilter", "")
    }
Esempio n. 36
0
def getContent(req, ids):
    ret = ""
    user = users.getUserFromRequest(req)
    access = AccessData(req)
    nodes = []
    for id in ids:
        if not access.hasWriteAccess(tree.getNode(id)):
            req.setStatus(httpstatus.HTTP_FORBIDDEN)
            return req.getTAL("web/edit/edit.html", {}, macro="access_error")
        nodes += [tree.getNode(id)]

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

    v = {}
    v["basedirs"] = [tree.getRoot('home'), tree.getRoot('collections')]
    id = req.params.get("id", tree.getRoot().id)
    v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s'" % (id, id)
    v["idstr"] = ",".join(ids)
    v["nodes"] = nodes
    v["t"] = t
    v["language"] = lang(req)
    return req.getTAL("web/edit/modules/classes.html", v, macro="classtree")
Esempio n. 37
0
def export(req):
    """ export definition: url contains /[type]/[id] """

    user = users.getUserFromRequest(req)
    if not user.isAdmin():
        return httpstatus.HTTP_FORBIDDEN

    path = req.path[1:].split("/")
    try:
        module = findmodule(path[1])

        tempfile = join_paths(config.get("paths.tempdir"),
                              str(random.random()))
        file = open(tempfile, "w")
        file.write(module.export(req, path[2]))
        file.close()

        req.sendFile(tempfile, "application/xml")
        if os.sep == '/':  # Unix?
            os.unlink(
                tempfile
            )  # unlinking files while still reading them only works on Unix/Linux
    except:
        print "module has no export method"
Esempio n. 38
0
def handle_request(req):

    errors = []

    user = users.getUserFromRequest(req)

    if not PYPDF_MODULE_PRESENT:
        return

    if req.path.startswith("/serve_page/"):

        node_id = req.params.get("node_id", None)
        if node_id:
            node = q(Node).get(node_id)
            if node is None:
                return 404  # not found
        else:
            return 404  # not found

        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)

        if not current_workflow_step:
            return 404  # not found
        current_workflow_step_children_ids = [
            n.id for n in current_workflow_step.children
        ]
        if node.id not in current_workflow_step_children_ids:
            return 403  # forbidden

        # XXX: WTF?!
        if False:  # and not access.hasAccess(node, "read"):
            req.params["addpic2pdf_error"] = "%s: %s" % (format_date().replace(
                'T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_no_access"))
            logg.info(
                "workflow step addpic2pdf(%s): no access to node %s for request from user '%s' (%s)",
                current_workflow_step.id, node.id, user.name, req.ip)
            return 403  # forbidden

        if req.path == '/serve_page/document.pdf':
            filepath = [
                f.abspath for f in node.filrd
                if f.filetype.startswith('document')
            ][0]
            return_code, file_size, abspath = serve_file(req, filepath)
            return return_code

        if req.path == '/serve_page/p_document.pdf':
            filepath = ([
                f.abspath
                for f in node.files if f.filetype.startswith('p_document')
                and f.base_name.startswith('addpic2pdf_%s_node_%s_' % (
                    unicode(current_workflow_step.id),
                    unicode(node.id),
                )) and f.filetype.startswith('p_document')
            ] + [
                f.abspath
                for f in node.files if f.filetype.startswith('document')
            ])[0]

            return_code, file_size, abspath = serve_file(req, filepath)
            return return_code

        pageno = req.path.replace("/serve_page/", "")
        pageno = pageno.split('?')[0]

        pdf_in_filepath = getPdfFilepathForProcessing(current_workflow_step,
                                                      node)

        pdf_page_image_fullpath = get_pdf_page_image(pdf_in_filepath, pageno)

        return_code, file_size, abspath = read_serve_file(
            req, pdf_page_image_fullpath, remove_after_sending=True)

        return return_code

    if req.path.startswith("/grid"):
        pdf_w = float(req.params.get('pdf_w', 595.275))
        pdf_h = float(req.params.get('pdf_h', 841.890))

        thumb_w = float(req.params.get('thumb_w', 424))
        thumb_h = float(req.params.get('thumb_h', 600))

        dpi_w = float(req.params.get('dpi_w', 72.0))
        dpi_h = float(req.params.get('dpi_h', 72.0))

        thick = int(req.params.get('thick', 5))

        orig = req.params.get('orig', "bottom_left")

        rotate = int(req.params.get('rotate', "0"))

        pdf_size = (pdf_w, pdf_h)
        thumb_size = (thumb_w, thumb_h)
        dpi = (dpi_w, dpi_h)

        orig_message = t(lang(req),
                         "admin_wfstep_addpic2pdf_grid_origin_label")

        f = getGridBuffer(pdf_size,
                          thumb_size,
                          dpi,
                          thick=5,
                          orig=["top_left", "bottom_left"][1],
                          orig_message=orig_message,
                          rotate=rotate)
        s = f.getvalue()
        req.write(s)
        req.write('')
        req.reply_headers['Content-Type'] = "image/png"
        return 200

    # part handle_request not matched by "/serve_page/" and "/grid"

    nodeid = req.params.get("selection_name", None)
    node = None

    if nodeid:
        nodeid = nodeid.replace("pdfpage_select_for_node_", "")
        node = q(Node).get(nodeid)
        if node is None:
            msg = "workflowstep addpic2pdf: nodeid='%s' for non-existant node for upload from '%s'" % (
                unicode(nodeid), req.ip)
            errors.append(msg)
            logg.error(msg)
            return 404  # not found
    else:
        msg = "workflowstep addpic2pdf: could not find 'nodeid' for upload from '%s'" % req.ip
        errors.append(msg)
        logg.error(msg)
        return 404  # not found

    try:
        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)
    except:
        return 403  # forbidden

    if False:  # not access.hasAccess(node, "read"):
        req.params["addpic2pdf_error"] = "%s: %s" % (format_date().replace(
            'T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_no_access"))
        logg.info(
            "workflow step addpic2pdf(%s): no access to node %s for request from user '%s' (%s)",
            current_workflow_step.id, node.id, user.name, req.ip)
        return 403  # forbidden

    pdf_in_filepath = getPdfFilepathForProcessing(current_workflow_step, node)
    pdf_page_image_url = get_pdf_page_image(pdf_in_filepath,
                                            req.params.get("pageno", "0"),
                                            path_only=True)

    s = {'pdf_page_image_url': pdf_page_image_url}

    req.write(
        req.params.get("jsoncallback") + "(%s)" % json.dumps(s, indent=4))

    return 200
Esempio n. 39
0
    def show_workflow_node(self, node, req, data=None):

        check_context()

        user = users.getUserFromRequest(req)

        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)

        FATAL_ERROR = False
        FATAL_ERROR_STR = ""

        if "gotrue" in req.params:

            if not PYPDF_MODULE_PRESENT:
                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            radio_apply_reset_accept = req.params.get(
                'radio_apply_reset_accept', '')

            if radio_apply_reset_accept == 'reset':
                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith(
                            'addpic2pdf_%s_node_%s_' %
                        (unicode(current_workflow_step.id), unicode(
                            node.id))) and f.filetype.startswith('p_document'):
                        logg.info(
                            "workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name,
                            node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        db.session.commit()
                        try:
                            os.remove(f.abspath)
                        except:
                            logg.exception(
                                "exception in workflow setep addpic2pdf, removing file failed, ignoring"
                            )

                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            elif radio_apply_reset_accept == 'accept':

                p_document_files = [
                    f for f in node.files
                    if f.filetype == 'p_document' and f.base_name.startswith(
                        'addpic2pdf_%s_node_%s_' %
                        (unicode(current_workflow_step.id), unicode(node.id)))
                ]

                if len(p_document_files) > 0:

                    p_document_file = p_document_files[0]

                    document_file = [
                        f for f in node.files if f.filetype == 'document'
                    ][0]

                    o_document_file = File(document_file.path, 'o_document',
                                           document_file.mimetype)

                    node.files.remove(document_file)
                    node.files.append(o_document_file)
                    o_document_name = o_document_file.base_name

                    for f in node.files:
                        if f.filetype in [
                                'thumb', 'fileinfo', 'fulltext'
                        ] or f.filetype.startswith('present'):
                            if os.path.splitext(
                                    f.base_name)[0] == os.path.splitext(
                                        o_document_name)[0]:
                                new_f = File(f.path, 'o_' + f.filetype,
                                             f.mimetype)
                                node.files.remove(f)
                                node.files.append(new_f)

                    new_document_file = File(p_document_file.path, 'document',
                                             p_document_file.mimetype)
                    node.files.remove(p_document_file)
                    node.files.append(new_document_file)
                    db.session.commit()
                    node.event_files_changed()

                del req.params['gotrue']
                return self.forwardAndShow(node, True, req)

            elif radio_apply_reset_accept == 'apply':

                drag_logo_fullname = req.params.get("input_drag_logo_fullname",
                                                    None)

                if not drag_logo_fullname:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '),
                        t(lang(req),
                          "admin_wfstep_addpic2pdf_no_logo_selected"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                drag_logo_filepath = [
                    f.abspath for f in current_workflow_step.files
                    if f.base_name == drag_logo_fullname
                ][0]

                pos_cm = req.params.get("input_poffset_cm", "0, 0")
                x_cm, y_cm = [float(x.strip()) for x in pos_cm.split(",")]

                pdf_in_filepath = getPdfFilepathForProcessing(
                    current_workflow_step, node)

                current_pageno = int(
                    req.params.get("input_current_page", "0").strip())

                radio_select_targetpages = req.params.get(
                    "radio_select_targetpages", "").strip()
                input_select_targetpages = req.params.get(
                    "input_select_targetpages", "").strip()

                printer_range = []
                page_count = get_pdf_pagecount(pdf_in_filepath)
                _parser_error = False

                try:
                    if radio_select_targetpages == "current_page":
                        printer_range = [current_pageno]
                    elif radio_select_targetpages == "all":
                        printer_range = range(0, page_count)
                    elif radio_select_targetpages == "pair":
                        printer_range = [
                            x for x in range(0, page_count) if x % 2
                        ]
                        if input_select_targetpages:
                            printer_range = [
                                x for x in printer_range if x in
                                parse_printer_range(input_select_targetpages,
                                                    maximum=page_count + 1)
                            ]
                    elif radio_select_targetpages == "impair":
                        printer_range = [
                            x for x in range(0, page_count) if not x % 2
                        ]
                        if input_select_targetpages:
                            printer_range = [
                                x for x in printer_range if x in
                                parse_printer_range(input_select_targetpages,
                                                    maximum=page_count + 1)
                            ]
                    elif radio_select_targetpages == "range_only" and input_select_targetpages:
                        printer_range = parse_printer_range(
                            input_select_targetpages, maximum=page_count + 1)
                except ValueError as e:
                    _parser_error = True

                if _parser_error:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '),
                        t(lang(req),
                          "admin_wfstep_addpic2pdf_printer_range_error"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                printer_range = map(int, list(printer_range))

                if not printer_range:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '),
                        t(
                            lang(req),
                            "admin_wfstep_addpic2pdf_printer_range_selected_empty"
                        ))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                x = x_cm * cm  # cm = 28.346456692913385
                y = y_cm * cm

                pic_dpi = get_pic_info(drag_logo_filepath).get('dpi', None)

                scale = 1.0

                if pic_dpi:
                    dpi_x, dpi_y = pic_dpi
                    if dpi_x != dpi_y:
                        req.params["addpic2pdf_error"] = "%s: %s" % (
                            format_date().replace('T', ' - '),
                            t(lang(req),
                              "admin_wfstep_addpic2pdf_logo_dpix_dpiy"))
                    dpi = int(dpi_x)
                    if dpi == 72:
                        scale = 1.0
                    else:
                        scale = 1.0 * 72.0 / dpi
                else:
                    dpi = 300
                    scale = 1.0 * 72.0 / dpi
                    #dpi = 72
                    #scale = 1.0

                tmppath = config.get("paths.datadir") + "tmp/"
                date_str = format_date().replace('T',
                                                 '-').replace(' ', '').replace(
                                                     ':', '-')
                filetempname = tmppath + \
                    "temp_addpic_pdf_wfs_%s_node_%s_%s_%s_.pdf" % (
                        unicode(current_workflow_step.id), unicode(node.id), date_str, unicode(random.random()))

                url = req.params.get('input_drag_logo_url', '')

                fn_out = filetempname

                build_logo_overlay_pdf(pdf_in_filepath,
                                       drag_logo_filepath,
                                       fn_out,
                                       x,
                                       y,
                                       scale=scale,
                                       mask='auto',
                                       pages=printer_range,
                                       follow_rotate=True,
                                       url=(" " * ADD_NBSP) + url)

                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith('addpic2pdf_%s_node_%s_' % (
                            unicode(current_workflow_step.id),
                            unicode(node.id),
                    )) and f.filetype.startswith('p_document'):
                        logg.info(
                            "workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name,
                            node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        try:
                            os.remove(f.abspath)
                        except:
                            pass
                        break

                date_str = format_date().replace('T',
                                                 '-').replace(' ', '').replace(
                                                     ':', '-')
                nodeFile = importFileToRealname(
                    "_has_been_processed_%s.pdf" % (date_str),
                    filetempname,
                    prefix='addpic2pdf_%s_node_%s_' % (
                        unicode(current_workflow_step.id),
                        unicode(node.id),
                    ),
                    typeprefix="p_")
                node.files.append(nodeFile)
                db.session.commit()
                try:
                    os.remove(filetempname)
                except:
                    pass

                del req.params['gotrue']
                return self.show_workflow_node(node, req)

        if "gofalse" in req.params:
            return self.forwardAndShow(node, False, req)

        # part of show_workflow_node not handled by "gotrue" and "gofalse"

        try:
            pdf_filepath = [
                f.abspath for f in node.files
                if f.filetype.startswith('document')
            ][0]
            error_no_pdf = False
        except:
            error_no_pdf = t(
                lang(req),
                "admin_wfstep_addpic2pdf_no_pdf_document_for_this_node")

        if not PYPDF_MODULE_PRESENT or error_no_pdf:
            error = ""
            if not PYPDF_MODULE_PRESENT:
                error += t(lang(req), "admin_wfstep_addpic2pdf_no_pypdf")
            if error_no_pdf:
                error += error_no_pdf
            pdf_dimensions = {
                'd_pageno2size': {
                    0: [595.275, 841.889]
                },
                'd_pageno2rotate': {
                    0: 0
                }
            }  # A4
            keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)
            context = {
                "key": req.params.get("key", req.session.get("key", "")),
                "error": error,
                "node": node,
                "files": node.files,
                "wfs": current_workflow_step,
                "wfs_files": [],
                "logo_info": {},
                "logo_info_list": [],
                "getImageSize": lambda x: (0, 0),
                "pdf_page_count": 0,
                "pdf_dimensions": pdf_dimensions,
                "json_pdf_dimensions": json.dumps(pdf_dimensions),
                "keep_params": json.dumps(keep_params),
                "startpageno": 0,
                "FATAL_ERROR": 'true',
                "user": users.getUserFromRequest(req),
                "prefix": self.get("prefix"),
                "buttons": self.tableRowButtons(node)
            }

            return req.getTAL("workflow/addpic2pdf.html",
                              context,
                              macro="workflow_addpic2pdf")
        try:
            pdf_dimensions = get_pdf_dimensions(pdf_filepath)
            pdf_pagecount = get_pdf_pagecount(pdf_filepath)
        except Exception as e:
            logg.exception("exception in workflow step addpic2pdf(%s)",
                           current_workflow_step.id)
            pdf_dimensions = {
                'd_pages': 0,
                'd_pageno2size': (0, 0),
                'd_pageno2rotate': 0
            }
            pdf_pagecount = 0
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - %s" % (unicode(e))

        #wfs_files = [f for f in current_workflow_step.getFiles() if os.path.isfile(f.retrieveFile())]

        wfs_files0, wfs_files = getFilelist(current_workflow_step,
                                            'logoupload')

        url_mapping = [
            line.strip()
            for line in current_workflow_step.get("url_mapping").splitlines()
            if line.strip() and line.find("|") > 0
        ]
        url_mapping = dict(
            map(lambda x: (x[0].strip(), x[1].strip()),
                [line.split("|", 1) for line in url_mapping]))

        logo_info = {}
        logo_info_list = []
        for f in [
                f for f in wfs_files
                if f.base_name.startswith('m_upload_logoupload')
        ]:
            f_path = f.abspath

            try:
                _size = list(get_pic_size(f_path))
                _dpi = get_pic_dpi(f_path)
            except Exception as e:
                logg.exception("exception in workflow step addpic2pdf(%s)",
                               current_workflow_step.id)
                FATAL_ERROR = True
                FATAL_ERROR_STR += (" - ERROR loading logo '%s'" %
                                    f_path) + unicode(e)
                continue

            logo_filename = f.base_name

            logo_url = ""
            for key in url_mapping:
                if logo_filename.find(key) >= 0:
                    logo_url = url_mapping[key]
                    break

            logo_info[logo_filename.encode('utf-8')] = {
                'size': _size,
                'dpi': _dpi,
                'url': logo_url.encode('utf-8')
            }
            if _dpi == 'no-info':
                _dpi = 72.0
            logo_info_list.append({
                'size': _size,
                'dpi': _dpi,
                'url': logo_url.encode('utf-8')
            })

        if len(logo_info) == 0:
            logg.error(
                "workflow step addpic2pdf(%s): Error: no logo images found",
                current_workflow_step.id)
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - Error: no logo images found"

        keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)

        context = {
            "key": req.params.get("key", req.session.get("key", "")),
            "error": req.params.get('addpic2pdf_error', ''),
            "node": node,
            "files": node.files,
            "wfs": current_workflow_step,
            "wfs_files": wfs_files,
            "logo_info": logo_info,
            "logo_info_list": logo_info_list,
            "getImageSize": get_pic_size,
            "pdf_page_count": pdf_pagecount,
            "pdf_dimensions": pdf_dimensions,
            "json_pdf_dimensions": json.dumps(pdf_dimensions),
            "keep_params": json.dumps(keep_params),
            "startpageno": startpageno,
            "FATAL_ERROR": {
                False: 'false',
                True: 'true'
            }[bool(FATAL_ERROR)],
            "user": users.getUserFromRequest(req),
            "prefix": self.get("prefix"),
            "buttons": self.tableRowButtons(node)
        }

        if FATAL_ERROR:
            context["error"] += " - %s" % (FATAL_ERROR_STR)

        return req.getTAL("workflow/addpic2pdf.html",
                          context,
                          macro="workflow_addpic2pdf")
Esempio n. 40
0
def handle_request(req):

    errors = []

    user = users.getUserFromRequest(req)

    if not PYPDF_MODULE_PRESENT:
        return

    if req.path.startswith("/serve_page/"):

        node_id = req.params.get("node_id", None)
        if node_id:
            node = q(Node).get(node_id)
            if node is None:
                return 404  # not found
        else:
            return 404  # not found

        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)

        if not current_workflow_step:
            return 404  # not found
        current_workflow_step_children_ids = [n.id for n in current_workflow_step.children]
        if node.id not in current_workflow_step_children_ids:
            return 403  # forbidden

        # XXX: WTF?!
        if False:  # and not access.hasAccess(node, "read"):
            req.params["addpic2pdf_error"] = "%s: %s" % (
                format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_no_access"))
            logg.info("workflow step addpic2pdf(%s): no access to node %s for request from user '%s' (%s)",
                current_workflow_step.id, node.id, user.name, req.ip)
            return 403  # forbidden

        if req.path == '/serve_page/document.pdf':
            filepath = [f.abspath for f in node.filrd if f.filetype.startswith('document')][0]
            return_code, file_size, abspath = serve_file(req, filepath)
            return return_code

        if req.path == '/serve_page/p_document.pdf':
            filepath = (
                [f.abspath for f in node.files if f.filetype.startswith('p_document') and f.base_name.startswith(
                    'addpic2pdf_%s_node_%s_' % (unicode(current_workflow_step.id), unicode(node.id), )) and f.filetype.startswith('p_document')]
                + [f.abspath for f in node.files if f.filetype.startswith('document')]
            )[0]

            return_code, file_size, abspath = serve_file(req, filepath)
            return return_code

        pageno = req.path.replace("/serve_page/", "")
        pageno = pageno.split('?')[0]

        pdf_in_filepath = getPdfFilepathForProcessing(current_workflow_step, node)

        pdf_page_image_fullpath = get_pdf_page_image(pdf_in_filepath, pageno)

        return_code, file_size, abspath = read_serve_file(req, pdf_page_image_fullpath, remove_after_sending=True)

        return return_code

    if req.path.startswith("/grid"):
        pdf_w = float(req.params.get('pdf_w', 595.275))
        pdf_h = float(req.params.get('pdf_h', 841.890))

        thumb_w = float(req.params.get('thumb_w', 424))
        thumb_h = float(req.params.get('thumb_h', 600))

        dpi_w = float(req.params.get('dpi_w', 72.0))
        dpi_h = float(req.params.get('dpi_h', 72.0))

        thick = int(req.params.get('thick', 5))

        orig = req.params.get('orig', "bottom_left")

        rotate = int(req.params.get('rotate', "0"))

        pdf_size = (pdf_w, pdf_h)
        thumb_size = (thumb_w, thumb_h)
        dpi = (dpi_w, dpi_h)

        orig_message = t(lang(req), "admin_wfstep_addpic2pdf_grid_origin_label")

        f = getGridBuffer(pdf_size, thumb_size, dpi, thick=5, orig=["top_left", "bottom_left"][1], orig_message=orig_message, rotate=rotate)
        s = f.getvalue()
        req.write(s)
        req.write('')
        req.reply_headers['Content-Type'] = "image/png"
        return 200

    # part handle_request not matched by "/serve_page/" and "/grid"

    nodeid = req.params.get("selection_name", None)
    node = None

    if nodeid:
        nodeid = nodeid.replace("pdfpage_select_for_node_", "")
        node = q(Node).get(nodeid)
        if node is None:
            msg = "workflowstep addpic2pdf: nodeid='%s' for non-existant node for upload from '%s'" % (unicode(nodeid), req.ip)
            errors.append(msg)
            logg.error(msg)
            return 404  # not found
    else:
        msg = "workflowstep addpic2pdf: could not find 'nodeid' for upload from '%s'" % req.ip
        errors.append(msg)
        logg.error(msg)
        return 404  # not found

    try:
        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)
    except:
        return 403  # forbidden

    if False:  # not access.hasAccess(node, "read"):
        req.params["addpic2pdf_error"] = "%s: %s" % (format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_no_access"))
        logg.info("workflow step addpic2pdf(%s): no access to node %s for request from user '%s' (%s)",
            current_workflow_step.id, node.id, user.name, req.ip)
        return 403  # forbidden

    pdf_in_filepath = getPdfFilepathForProcessing(current_workflow_step, node)
    pdf_page_image_url = get_pdf_page_image(pdf_in_filepath, req.params.get("pageno", "0"), path_only=True)

    s = {'pdf_page_image_url': pdf_page_image_url}

    req.write(req.params.get("jsoncallback") + "(%s)" % json.dumps(s, indent=4))

    return 200
Esempio n. 41
0
    def show_workflow_node(self, node, req, data=None):

        check_context()

        user = users.getUserFromRequest(req)

        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)

        FATAL_ERROR = False
        FATAL_ERROR_STR = ""

        if "gotrue" in req.params:

            if not PYPDF_MODULE_PRESENT:
                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            radio_apply_reset_accept = req.params.get('radio_apply_reset_accept', '')

            if radio_apply_reset_accept == 'reset':
                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith('addpic2pdf_%s_node_%s_' %
                                         (unicode(current_workflow_step.id), unicode(node.id))) and f.filetype.startswith('p_document'):
                        logg.info("workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name, node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        db.session.commit()
                        try:
                            os.remove(f.abspath)
                        except:
                            logg.exception("exception in workflow setep addpic2pdf, removing file failed, ignoring")

                del req.params['gotrue']
                return self.show_workflow_node(node, req)

            elif radio_apply_reset_accept == 'accept':

                p_document_files = [f for f in node.files if f.filetype == 'p_document' and f.base_name.startswith(
                    'addpic2pdf_%s_node_%s_' % (unicode(current_workflow_step.id), unicode(node.id)))]

                if len(p_document_files) > 0:

                    p_document_file = p_document_files[0]

                    document_file = [f for f in node.files if f.filetype == 'document'][0]

                    o_document_file = File(document_file.path, 'o_document', document_file.mimetype)

                    node.files.remove(document_file)
                    node.files.append(o_document_file)
                    o_document_name = o_document_file.base_name

                    for f in node.files:
                        if f.filetype in ['thumb', 'fileinfo', 'fulltext'] or f.filetype.startswith('present'):
                            if os.path.splitext(f.base_name)[0] == os.path.splitext(o_document_name)[0]:
                                new_f = File(f.path, 'o_' + f.filetype, f.mimetype)
                                node.files.remove(f)
                                node.files.append(new_f)

                    new_document_file = File(p_document_file.path, 'document', p_document_file.mimetype)
                    node.files.remove(p_document_file)
                    node.files.append(new_document_file)
                    db.session.commit()
                    node.event_files_changed()

                del req.params['gotrue']
                return self.forwardAndShow(node, True, req)

            elif radio_apply_reset_accept == 'apply':

                drag_logo_fullname = req.params.get("input_drag_logo_fullname", None)

                if not drag_logo_fullname:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_no_logo_selected"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                drag_logo_filepath = [f.abspath for f in current_workflow_step.files if f.base_name == drag_logo_fullname][0]

                pos_cm = req.params.get("input_poffset_cm", "0, 0")
                x_cm, y_cm = [float(x.strip()) for x in pos_cm.split(",")]

                pdf_in_filepath = getPdfFilepathForProcessing(current_workflow_step, node)

                current_pageno = int(req.params.get("input_current_page", "0").strip())

                radio_select_targetpages = req.params.get("radio_select_targetpages", "").strip()
                input_select_targetpages = req.params.get("input_select_targetpages", "").strip()

                printer_range = []
                page_count = get_pdf_pagecount(pdf_in_filepath)
                _parser_error = False

                try:
                    if radio_select_targetpages == "current_page":
                        printer_range = [current_pageno]
                    elif radio_select_targetpages == "all":
                        printer_range = range(0, page_count)
                    elif radio_select_targetpages == "pair":
                        printer_range = [x for x in range(0, page_count) if x % 2]
                        if input_select_targetpages:
                            printer_range = [x for x in printer_range if x in parse_printer_range(
                                input_select_targetpages, maximum=page_count + 1)]
                    elif radio_select_targetpages == "impair":
                        printer_range = [x for x in range(0, page_count) if not x % 2]
                        if input_select_targetpages:
                            printer_range = [x for x in printer_range if x in parse_printer_range(
                                input_select_targetpages, maximum=page_count + 1)]
                    elif radio_select_targetpages == "range_only" and input_select_targetpages:
                        printer_range = parse_printer_range(input_select_targetpages, maximum=page_count + 1)
                except ValueError as e:
                    _parser_error = True

                if _parser_error:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_printer_range_error"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                printer_range = map(int, list(printer_range))

                if not printer_range:
                    req.params["addpic2pdf_error"] = "%s: %s" % (
                        format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_printer_range_selected_empty"))
                    del req.params['gotrue']
                    return self.show_workflow_node(node, req)

                x = x_cm * cm  # cm = 28.346456692913385
                y = y_cm * cm

                pic_dpi = get_pic_info(drag_logo_filepath).get('dpi', None)

                scale = 1.0

                if pic_dpi:
                    dpi_x, dpi_y = pic_dpi
                    if dpi_x != dpi_y:
                        req.params["addpic2pdf_error"] = "%s: %s" % (
                            format_date().replace('T', ' - '), t(lang(req), "admin_wfstep_addpic2pdf_logo_dpix_dpiy"))
                    dpi = int(dpi_x)
                    if dpi == 72:
                        scale = 1.0
                    else:
                        scale = 1.0 * 72.0 / dpi
                else:
                    dpi = 300
                    scale = 1.0 * 72.0 / dpi
                    #dpi = 72
                    #scale = 1.0

                tmppath = config.get("paths.datadir") + "tmp/"
                date_str = format_date().replace('T', '-').replace(' ', '').replace(':', '-')
                filetempname = tmppath + \
                    "temp_addpic_pdf_wfs_%s_node_%s_%s_%s_.pdf" % (
                        unicode(current_workflow_step.id), unicode(node.id), date_str, unicode(random.random()))

                url = req.params.get('input_drag_logo_url', '')

                fn_out = filetempname

                build_logo_overlay_pdf(pdf_in_filepath, drag_logo_filepath, fn_out, x, y, scale=scale,
                                       mask='auto', pages=printer_range, follow_rotate=True, url=(" " * ADD_NBSP) + url)

                for f in node.files:
                    f_name = f.base_name
                    if f_name.startswith('addpic2pdf_%s_node_%s_' %
                                         (unicode(current_workflow_step.id), unicode(node.id), )) and f.filetype.startswith('p_document'):
                        logg.info("workflow step addpic2pdf(%s): going to remove file '%s' from node '%s' (%s) for request from user '%s' (%s)",
                            current_workflow_step.id, f_name, node.name, node.id, user.login_name, req.ip)
                        node.files.remove(f)
                        with suppress(Exception, warn=False):
                            os.remove(f.abspath)
                        break

                date_str = format_date().replace('T', '-').replace(' ', '').replace(':', '-')
                nodeFile = importFileToRealname("_has_been_processed_%s.pdf" % (date_str), filetempname, prefix='addpic2pdf_%s_node_%s_' % (
                    unicode(current_workflow_step.id), unicode(node.id), ), typeprefix="p_")
                node.files.append(nodeFile)
                db.session.commit()
                with suppress(Exception, warn=False):
                    os.remove(filetempname)
                del req.params['gotrue']
                return self.show_workflow_node(node, req)

        if "gofalse" in req.params:
            return self.forwardAndShow(node, False, req)

        # part of show_workflow_node not handled by "gotrue" and "gofalse"

        try:
            pdf_filepath = [f.abspath for f in node.files if f.filetype.startswith('document')][0]
            error_no_pdf = False
        except:
            error_no_pdf = t(lang(req), "admin_wfstep_addpic2pdf_no_pdf_document_for_this_node")

        if not PYPDF_MODULE_PRESENT or error_no_pdf:
            error = ""
            if not PYPDF_MODULE_PRESENT:
                error += t(lang(req), "admin_wfstep_addpic2pdf_no_pypdf")
            if error_no_pdf:
                error += error_no_pdf
            pdf_dimensions = {'d_pageno2size': {0: [595.275, 841.889]}, 'd_pageno2rotate': {0: 0}}  # A4
            keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)
            context = {"key": req.params.get("key", req.session.get("key", "")),
                       "error": error,

                       "node": node,
                       "files": node.files,
                       "wfs": current_workflow_step,
                       "wfs_files": [],

                       "logo_info": {},
                       "logo_info_list": [],

                       "getImageSize": lambda x: (0, 0),
                       "pdf_page_count": 0,
                       "pdf_dimensions": pdf_dimensions,
                       "json_pdf_dimensions": json.dumps(pdf_dimensions),
                       "keep_params": json.dumps(keep_params),
                       "startpageno": 0,

                       "FATAL_ERROR": 'true',

                       "user": users.getUserFromRequest(req),
                       "prefix": self.get("prefix"),
                       "buttons": self.tableRowButtons(node),
                       "csrf": req.csrf_token.current_token,}

            return req.getTAL("workflow/addpic2pdf.html", context, macro="workflow_addpic2pdf")
        try:
            pdf_dimensions = get_pdf_dimensions(pdf_filepath)
            pdf_pagecount = get_pdf_pagecount(pdf_filepath)
        except Exception as e:
            logg.exception("exception in workflow step addpic2pdf(%s)", current_workflow_step.id)
            pdf_dimensions = {'d_pages': 0, 'd_pageno2size': (0, 0), 'd_pageno2rotate': 0}
            pdf_pagecount = 0
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - %s" % (unicode(e))

        #wfs_files = [f for f in current_workflow_step.getFiles() if os.path.isfile(f.retrieveFile())]

        wfs_files0, wfs_files = getFilelist(current_workflow_step, 'logoupload')

        url_mapping = [line.strip()
                       for line in current_workflow_step.get("url_mapping").splitlines() if line.strip() and line.find("|") > 0]
        url_mapping = dict(map(lambda x: (x[0].strip(), x[1].strip()), [line.split("|", 1) for line in url_mapping]))

        logo_info = {}
        logo_info_list = []
        for f in [f for f in wfs_files if f.base_name.startswith('m_upload_logoupload')]:
            f_path = f.abspath

            try:
                _size = list(get_pic_size(f_path))
                _dpi = get_pic_dpi(f_path)
            except Exception as e:
                logg.exception("exception in workflow step addpic2pdf(%s)", current_workflow_step.id)
                FATAL_ERROR = True
                FATAL_ERROR_STR += (" - ERROR loading logo '%s'" % f_path) + unicode(e)
                continue

            logo_filename = f.base_name

            logo_url = ""
            for key in url_mapping:
                if logo_filename.find(key) >= 0:
                    logo_url = url_mapping[key]
                    break

            logo_info[logo_filename.encode('utf-8')] = {'size': _size, 'dpi': _dpi, 'url': logo_url.encode('utf-8')}
            if _dpi == 'no-info':
                _dpi = 72.0
            logo_info_list.append({'size': _size, 'dpi': _dpi, 'url': logo_url.encode('utf-8')})

        if len(logo_info) == 0:
            logg.error("workflow step addpic2pdf(%s): Error: no logo images found", current_workflow_step.id)
            FATAL_ERROR = True
            FATAL_ERROR_STR += " - Error: no logo images found"

        keep_params = copyDictValues(req.params, {}, KEEP_PARAMS)

        context = {"key": req.params.get("key", req.session.get("key", "")),
                   "error": req.params.get('addpic2pdf_error', ''),

                   "node": node,
                   "files": node.files,
                   "wfs": current_workflow_step,
                   "wfs_files": wfs_files,

                   "logo_info": logo_info,
                   "logo_info_list": logo_info_list,

                   "getImageSize": get_pic_size,
                   "pdf_page_count": pdf_pagecount,
                   "pdf_dimensions": pdf_dimensions,
                   "json_pdf_dimensions": json.dumps(pdf_dimensions),
                   "keep_params": json.dumps(keep_params),
                   "startpageno": startpageno,

                   "FATAL_ERROR": {False: 'false', True: 'true'}[bool(FATAL_ERROR)],

                   "user": users.getUserFromRequest(req),
                   "prefix": self.get("prefix"),
                   "buttons": self.tableRowButtons(node),
                   "csrf": req.csrf_token.current_token,}

        if FATAL_ERROR:
            context["error"] += " - %s" % (FATAL_ERROR_STR)

        return req.getTAL("workflow/addpic2pdf.html", context, macro="workflow_addpic2pdf")
Esempio n. 42
0
def upload_for_html(req):
    user = users.getUserFromRequest(req)
    datatype = req.params.get("datatype", "image")

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

    access = AccessData(req)
    if not (access.hasAccess(node, 'read') and access.hasAccess(node, 'write')
            and access.hasAccess(node, 'data')):
        return 403

    for key in req.params.keys():
        if key.startswith("delete_"):
            filename = key[7:-2]
            for file in n.getFiles():
                if file.getName() == filename:
                    n.removeFile(file)

    if "file" in req.params.keys():  # file

        # file upload via (possibly disabled) upload form in custom image
        # browser
        file = req.params["file"]
        del req.params["file"]
        if hasattr(file, "filesize") and file.filesize > 0:
            try:
                logger.info(user.name + " upload " + file.filename + " (" +
                            file.tempname + ")")
                nodefile = importFile(file.filename, file.tempname)
                node.addFile(nodefile)
                req.request["Location"] = req.makeLink(
                    "nodefile_browser/%s/" % id, {})
            except EncryptionException:
                req.request["Location"] = req.makeLink(
                    "content", {
                        "id": id,
                        "tab": "tab_editor",
                        "error":
                        "EncryptionError_" + datatype[:datatype.find("/")]
                    })
            except:
                logException("error during upload")
                req.request["Location"] = req.makeLink(
                    "content", {
                        "id":
                        id,
                        "tab":
                        "tab_editor",
                        "error":
                        "PostprocessingError_" + datatype[:datatype.find("/")]
                    })
            return send_nodefile_tal(req)

    if "upload" in req.params.keys():  # NewFile
        # file upload via CKeditor Image Properties / Upload tab
        file = req.params["upload"]
        del req.params["upload"]
        if hasattr(file, "filesize") and file.filesize > 0:
            try:
                logger.info(user.name + " upload via ckeditor " +
                            file.filename + " (" + file.tempname + ")")
                nodefile = importFile(file.filename, file.tempname)
                node.addFile(nodefile)
            except EncryptionException:
                req.request["Location"] = req.makeLink(
                    "content", {
                        "id": id,
                        "tab": "tab_editor",
                        "error":
                        "EncryptionError_" + datatype[:datatype.find("/")]
                    })
            except:
                logException("error during upload")
                req.request["Location"] = req.makeLink(
                    "content", {
                        "id":
                        id,
                        "tab":
                        "tab_editor",
                        "error":
                        "PostprocessingError_" + datatype[:datatype.find("/")]
                    })

            url = '/file/' + id + '/' + file.tempname.split('/')[-1]

            res = """<script type="text/javascript">

                // Helper function to get parameters from the query string.
                function getUrlParam(paramName)
                {
                  var reParam = new RegExp('(?:[\?&]|&amp;)' + paramName + '=([^&]+)', 'i') ;
                  var match = window.location.search.match(reParam) ;

                  return (match && match.length > 1) ? match[1] : '' ;
                }
            funcNum = getUrlParam('CKEditorFuncNum');

            window.parent.CKEDITOR.tools.callFunction(funcNum, "%(fileUrl)s","%(customMsg)s");

            </script>;""" % {
                'fileUrl': url.replace('"', '\\"'),
                'customMsg':
                (t(lang(req), "edit_fckeditor_cfm_uploadsuccess")),
            }

            return res

    return send_nodefile_tal(req)
Esempio n. 43
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    node = tree.getNode(ids[0])
    access = acl.AccessData(req)
    if not access.hasWriteAccess(
            node) or "changeschema" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    error = req.params.get("error")
    currentContentType = node.getContentType()

    try:
        currentSchema = node.type.split('/')[1]  # string
    except:
        currentSchema = ''

    currentCategoryName = node.getCategoryName()
    currentTypeAlias = node.getTypeAlias()

    schemes = AccessData(req).filter(loadTypesFromDB())
    _schemes = []
    for scheme in schemes:
        if scheme.isActive():
            _schemes.append(scheme)
    schemes = _schemes

    schemeNames2LongNames = {'': ''}
    for s in schemes:
        schemeNames2LongNames[s.getName()] = s.getLongName()

    try:
        currentSchemaLongName = schemeNames2LongNames[currentSchema]
    except KeyError:
        currentSchemaLongName = ''

    # find out which schema allows which datatype, and hence,
    # which overall data types we should display
    dtypes = []
    datatypes = loadAllDatatypes()
    for scheme in schemes:
        for dtype in scheme.getDatatypes():
            if dtype not in dtypes:
                for t in datatypes:
                    if t.getName() == dtype and not elemInList(
                            dtypes, t.getName()):
                        dtypes.append(t)

    dtypes.sort(lambda x, y: cmp(
        translate(x.getLongName(), request=req).lower(),
        translate(y.getLongName(), request=req).lower()))

    admissible_objtypes = getTypes(datatypes)
    admissible_datatypes = [
        n for n in admissible_objtypes
        if tree.Node('', n.name).getCategoryName() in
        ['document', 'image', 'video', 'audio']
    ]
    admissible_containers = [
        n for n in admissible_objtypes
        if tree.Node('', n.name).getCategoryName() in ['container']
    ]

    admissible_objtypes.sort(lambda x, y: cmp(
        translate(x.getLongName(), request=req).lower(),
        translate(y.getLongName(), request=req).lower()))
    admissible_datatypes.sort(lambda x, y: cmp(
        translate(x.getLongName(), request=req).lower(),
        translate(y.getLongName(), request=req).lower()))
    admissible_containers.sort(lambda x, y: cmp(
        translate(x.getLongName(), request=req).lower(),
        translate(y.getLongName(), request=req).lower()))

    available_schemes = [
        s for s in schemes if currentContentType in s.getDatatypes()
    ]

    # filter schemes for special datatypes
    if req.params.get("objtype", "") != "":
        _schemes = []
        for scheme in schemes:
            if req.params.get("objtype", "") in scheme.getDatatypes():
                _schemes.append(scheme)
        schemes = _schemes
        schemes.sort(lambda x, y: cmp(
            translate(x.getLongName(), request=req).lower(),
            translate(y.getLongName(), request=req).lower()))

        newObjectType = req.params.get("objtype")
        newSchema = req.params.get("schema")
        if not newSchema:
            newSchema = ''

        newType = newObjectType
        if newSchema:
            newType += '/' + newSchema

        oldType = currentContentType
        if currentSchema:
            oldType = oldType + '/' + currentSchema

        if newType != oldType:
            node.setTypeName(newType)
            msg = "%s changed node schema for node %s '%s' from '%s' to '%s'" % (
                user.name, node.id, node.name, oldType, newType)
            logger.info(msg)
            logging.getLogger('usertracing').info(msg)

            node.setDirty()
            # cache clean / reload because object type changed
            tree.remove_from_nodecaches(node)
            node = tree.getNode(node.id)

            currentContentType = node.getContentType()
            currentSchema = newSchema
            currentSchemaLongName = schemeNames2LongNames[currentSchema]
            currentCategoryName = node.getCategoryName()
            currentTypeAlias = node.getTypeAlias()
            available_schemes = [
                s for s in schemes if newObjectType in s.getDatatypes()
            ]

    isContainer = False
    if hasattr(node, "isContainer"):
        isContainer = node.isContainer()

    if "action" in req.params.keys():
        if req.params.get("action").startswith("get_schemes_for_"):
            newObjectType = req.params.get("action").replace(
                "get_schemes_for_", "")
            available_schemes = [
                s for s in schemes if newObjectType in s.getDatatypes()
            ]
            req.writeTAL("web/edit/modules/changeschema.html", {
                'schemes': available_schemes,
                'currentSchema': currentSchema
            },
                         macro="changeschema_selectscheme")
        return ""

    containers = getContainers(datatypes)

    d = {"id": req.params.get("id"), "error": error, "node": node}
    d['currentContentType'] = currentContentType
    d['currentSchema'] = currentSchema
    d['currentSchemaLongName'] = currentSchemaLongName
    d['currentCategoryName'] = currentCategoryName
    d['currentTypeAlias'] = currentTypeAlias
    d['isContainer'] = int(isContainer)
    d['nodes'] = [node]
    if currentContentType in [dtype.name for dtype in containers]:
        d['schemes'] = []
        d['datatypes'] = admissible_containers  # containers
    else:
        d['schemes'] = available_schemes
        d['datatypes'] = admissible_datatypes  # dtypes

    return req.getTAL("web/edit/modules/changeschema.html",
                      d,
                      macro="changeschema_popup")
Esempio n. 44
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    if "lza" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

    v = {}
    v['error'] = ""

    nodes = []
    for id in ids:
        node = tree.getNode(id)

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

        nodes.append(node)
        if "createlza" in req.params:
            # remove old file if existing
            for f in node.getFiles():
                if f.getType() == "lza":
                    node.removeFile(f)
            # create new file
            for f in node.getFiles():
                if f.getType() in ("original", "document"):
                    try:
                        archive = l.LZA(f.retrieveFile())
                        schema = node.getSchema()

                        # test for lza export mask
                        if (getMetaType(schema).getMask("lza")):
                            m = getMetaType(schema).getMask("lza")
                            meta = l.LZAMetadata(m.getViewHTML([node], 8))
                        else:
                            # generate error message
                            meta = l.LZAMetadata("""
        <?xpacket begin="\xef\xbb\xbf" id="mediatum_metadata"?>
                <lza:data> 
                    <lza:error>-definition missing-</lza:error>
                </lza:data><?xpacket end="w"?>
                                """)
                        archive.writeMediatumData(meta)
                        node.addFile(
                            tree.FileNode(archive.buildLZAName(), "lza",
                                          f.getMimeType()))

                    except l.FiletypeNotSupported:
                        v['error'] = "edit_lza_wrongfiletype"

        elif "removelza" in req.params:
            for f in node.getFiles():
                if f.getType() == "lza":
                    node.removeFile(f)

    v['id'] = req.params.get("id", "0")
    v['tab'] = req.params.get("tab", "")
    v['ids'] = ids
    v['nodes'] = nodes
    v['t'] = t
    v['language'] = lang(req)

    meta = {}
    for id in ids:
        node = tree.getNode(id)
        for f in node.getFiles():
            if f.getType() == "lza":
                try:
                    archive = l.LZA(f.retrieveFile(), f.getMimeType())
                    meta[id] = archive.getMediatumData()
                except IOError:
                    v['error'] = "edit_lza_ioerror"

    v['meta'] = meta
    return req.getTAL("web/edit/modules/lza.html", v, macro="edit_lza")
Esempio n. 45
0
def validate(req, op):
    """standard validator"""
    try:

        if "style" in req.params:
            req.write(view(req))
            return ""

        for key in req.params.keys():
            if key.startswith("new"):
                # create new user
                return editUser_mask(req, "")

            elif key.startswith("edit_"):
                # edit user
                return editUser_mask(req, str(key[key.index("_") + 1:-2]))

            elif key.startswith("sendmail_") and req.params.get("form_op", "") != "cancel":
                # send email
                return sendmailUser_mask(req, str(key[key.index("_") + 1:-2]))

            elif key.startswith("delete_"):
                # delete user
                user_from_request = users.getUserFromRequest(req)
                username_from_form = key[7:-2]
                dyn_auths = getDynamicUserAuthenticators()
                isDynamic = False
                for dyn_auth in dyn_auths:
                    if username_from_form.startswith(dyn_auth + "|"):
                        isDynamic = (username_from_form, dyn_auth)
                        break
                if isDynamic:
                    log.info("%r is requesting logout of dynamic user %r (%r)" % (user_from_request.getName(), isDynamic[0], isDynamic[1]))
                    deleteUser(isDynamic[0], isDynamic[1])
                else:
                    usertype = req.params.get("usertype", "intern")
                    usernode = getUser(key[7:-2])
                    if not usertype.strip():
                        usertype = usernode.getUserType()
                        if usertype == 'users':
                            # function deleteUser expects usertype='intern'
                            # for children if root->users, but getUserType()
                            # returns 'users' for those
                            usertype = 'intern'
                    log.info("%r is requesting deletion of user %r (%r, %r)" %
                             (user_from_request.getName(), usernode.name, usernode.id, usertype))
                    deleteUser(usernode, usertype=usertype)
                    del_index = users_cache.index(usernode)

                    del users_cache[del_index]

                searchterm_was = req.params.get("searchterm_was", "")
                if searchterm_was:
                    req.params['action'] = 'search'
                    req.params['searchterm'] = searchterm_was
                    req.params['use_macro'] = 'view'
                    req.params['execute_search'] = searchterm_was

                break

            elif key.startswith("tointern_"):
                moveUserToIntern(key[9:-2])
                break

            elif key.startswith("reset_"):
                # reset password
                if req.params["change_passwd"] != "":
                    getUser(key[6:-2]).resetPassword(req.params["change_passwd"])
                else:
                    getUser(key[6:-2]).resetPassword(config.settings["user.passwd"])
                break

        if "form_op" in req.params.keys():
            _option = ""
            for key in req.params.keys():
                if key.startswith("option_"):
                    _option += key[7]

            if req.params.get("form_op") == "save_new":
                # save user values
                if req.params.get("username", "") == "" or req.params.get("usergroups", "") == "" or req.params.get("email", "") == "":
                    return editUser_mask(req, "", 1)  # no username or group selected
                elif existUser(req.params.get("username")):
                    return editUser_mask(req, "", 2)  # user still existing
                else:
                    create_user(
                        req.params.get("username"),
                        req.params.get("email"),
                        req.params.get("usergroups").replace(
                            ";",
                            ","),
                        pwd=req.params.get(
                            "password",
                            ""),
                        lastname=req.params.get(
                            "lastname",
                            ""),
                        firstname=req.params.get("firstname"),
                        telephone=req.params.get("telephone"),
                        comment=req.params.get("comment"),
                        option=_option,
                        organisation=req.params.get(
                            "organisation",
                            ""),
                        identificator=req.params.get(
                            "identificator",
                            ""),
                        type=req.params.get(
                            "usertype",
                            "intern"))

            elif req.params["form_op"] == "save_edit":
                # update user
                if req.params.get("email", "") == "" or req.params.get("username", "") == "" or req.params.get("usergroups", "") == "":
                    return editUser_mask(req, req.params.get("id"), 1)  # no username, email or group selected
                else:
                    update_user(
                        req.params.get(
                            "id",
                            0),
                        req.params.get(
                            "username",
                            ""),
                        req.params.get(
                            "email",
                            ""),
                        req.params.get(
                            "usergroups",
                            "").replace(
                            ";",
                            ","),
                        lastname=req.params.get("lastname"),
                        firstname=req.params.get("firstname"),
                        telephone=req.params.get("telephone"),
                        comment=req.params.get("comment"),
                        option=_option,
                        organisation=req.params.get(
                            "organisation",
                            ""),
                        identificator=req.params.get(
                            "identificator",
                                ""),
                        type=req.params.get(
                            "usertype",
                            "intern"))

            flush_users_cache()
        return view(req)
    except:
        print "Warning: couldn't load module for type", type
        print sys.exc_info()[0], sys.exc_info()[1]
        traceback.print_tb(sys.exc_info()[2])
Esempio n. 46
0
def validate(req, op):
    """standard validator"""
    user = users.getUserFromRequest(req)

    try:

        if "action" in req.params.keys():
            if req.params.get("action") == "titleinfo":
                group = getGroup(u(req.params.get("group")))
                schema = group.getSchemas()
                req.write('|'.join(schema))
            return ""

        for key in req.params.keys():
            if key.startswith("new"):
                # create new group
                return editGroup_mask(req, "")

            elif key.startswith("edit_"):
                # edit usergroup
                return editGroup_mask(req, str(key[5:-2]))

            elif key.startswith("delete_"):
                # delete group
                log.debug("user %r going to delete group %r" %
                          (user.getName(), key[7:-2]))
                deleteGroup(key[7:-2])
                break

        if "form_op" in req.params.keys():
            _option = ""
            for key in req.params.keys():
                if key.startswith("option_"):
                    _option += key[7]

            if req.params.get("form_op", "") == "save_new":
                # save new group values
                if req.params.get("groupname", "") == "":
                    return editGroup_mask(req, "", 1)  # no groupname selected
                elif existGroup(req.params.get("groupname", "")):
                    return editGroup_mask(req, "", 2)  # group still existing
                else:
                    log.debug(
                        "user %r going to save new group %r" %
                        (user.getName(), req.params.get("groupname", "")))
                    if req.params.get("create_rule", "") == "True":
                        updateAclRule(req.params.get("groupname", ""),
                                      req.params.get("groupname", ""))
                    if req.params.get("checkbox_allow_dynamic",
                                      "") in ["on", "1"]:
                        allow_dynamic = "1"
                    else:
                        allow_dynamic = ""
                    dynamic_users = req.params.get("dynamic_users", "")
                    group = create_group(
                        req.params.get("groupname", ""),
                        description=req.params.get("description", ""),
                        option=str(_option),
                        allow_dynamic=allow_dynamic,
                        dynamic_users=dynamic_users,
                    )
                    group.setHideEdit(req.params.get("leftmodule", "").strip())
                    saveGroupMetadata(
                        group.name,
                        req.params.get("leftmodulemeta", "").strip())

            elif req.params.get("form_op") == "save_edit":
                # save changed values
                groupname = req.params.get("groupname", "")
                oldgroupname = req.params.get("oldgroupname", "")
                group = getGroup(oldgroupname)
                if oldgroupname != groupname:
                    updateAclRule(oldgroupname, groupname)
                group.setName(groupname)
                group.setDescription(req.params.get("description", ""))
                group.setOption(str(_option))
                group.setHideEdit(req.params.get("leftmodule", "").strip())
                saveGroupMetadata(
                    groupname,
                    req.params.get("leftmodulemeta", "").split(";"))

                if ALLOW_DYNAMIC_USERS:
                    allow_dynamic = req.params.get("checkbox_allow_dynamic",
                                                   "")
                    dynamic_users = req.params.get("dynamic_users", "")
                    if allow_dynamic.lower() in ['on', 'true', '1']:
                        group.set("allow_dynamic", "1")
                    else:
                        group.set("allow_dynamic", "")
                    group.set("dynamic_users", dynamic_users)
                if groupname == oldgroupname:
                    log.debug("user %r edited group %r" %
                              (user.getName(), groupname))
                else:
                    log.debug("user %r edited group %r, new groupname: %r" %
                              (user.getName(), oldgroupname, groupname))
            sortUserGroups()
        return view(req)

    except:
        print "Warning: couldn't load module for type", type
        print sys.exc_info()[0], sys.exc_info()[1]
        traceback.print_tb(sys.exc_info()[2])
Esempio n. 47
0
def getContent(req, ids):
    user = users.getUserFromRequest(req)
    node = tree.getNode(ids[0])
    access = AccessData(req)
    
    if not access.hasWriteAccess(node) or "searchmask" in users.getHideMenusForUser(user):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL("web/edit/edit.html", {}, macro="access_error")

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

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

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

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

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

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

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

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

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

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

        elif openfield:  # unfold a new field
            selectedfieldid = openfield

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

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

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

        fields = mask.getChildren()

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

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

    data["schema"] = myschema

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

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

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

    return req.getTAL("web/edit/modules/searchmask.html", data, macro="edit_search")
Esempio n. 48
0
def get_user_id(req):
    import core.users as users
    user = users.getUserFromRequest(req)
    res = "userid=%r|username=%r" % (user.getUserID(), user.getName())
    return res
Esempio n. 49
0
def getContent(req, ids):
    ret = ""
    user = users.getUserFromRequest(req)
    node = tree.getNode(ids[0])
    update_error = False
    access = acl.AccessData(req)

    msg = "%s|web.edit.modules.files.getContend|req.fullpath=%r|req.path=%r|req.params=%r|ids=%r" % (get_user_id(req), req.fullpath, req.path, req.params, ids)
    log.debug(msg)

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

    if 'data' in req.params:
        if req.params.get('data') == 'children':  # get formated list of childnodes of selected directory
            excludeid = req.params.get('excludeid', None)
            if excludeid:
                grandchildren = []
                for child in node.getChildren():
                    for grandchild in child.getChildren():
                        if not grandchild.isContainer():
                            grandchildren.append(grandchild)
                req.writeTAL("web/edit/modules/files.html", {'children': [c for c in node.getChildren() if str(c.id) != excludeid],
                                                             'grandchildren': grandchildren}, macro="edit_files_popup_children")
            else:
                grandchildren = []
                for child in node.getChildren():
                    for grandchild in child.getChildren():
                        if not grandchild.isContainer():
                            grandchildren.append(grandchild)
                req.writeTAL("web/edit/modules/files.html", {'children': [c for c in node.getChildren() if str(c.id) != excludeid],
                                                             'grandchildren': grandchildren}, macro="edit_files_popup_children")
        elif req.params.get('data') =='grandchildren':
            grandchildren = []
            for child in node.getChildren():
                if not child.isContainer():
                    for grandchild in child.getChildren():
                        if not grandchild.isContainer():
                            if not grandchild.isContainer():
                                grandchildren.append(grandchild)

            if len(node.getChildren())==0:
                req.writeTAL("web/edit/modules/files.html", {'grandchildren': []}, macro="edit_files_popup_grandchildren")
            else:
                req.writeTAL("web/edit/modules/files.html", {'grandchildren': grandchildren}, macro="edit_files_popup_grandchildren")

        if req.params.get('data') == 'additems':  # add selected node as children
            for childid in req.params.get('items').split(";"):
                if childid.strip() != "":
                    childnode = tree.getNode(childid.strip())
                    for p in childnode.getParents():
                        if p.isContainer():
                            logging.getLogger('editor').info("Removed childnode: {} from node: {}. - caused by adding".format(childnode.id, node.id))
                            p.removeChild(childnode)
                    node.addChild(childnode)
            req.writeTAL("web/edit/modules/files.html", {'children': node.getChildren(), 'node': node}, macro="edit_files_children_list")

        if req.params.get('data') == 'removeitem':  # remove selected childnode node

            try:
                remnode = tree.getNode(req.params.get('remove'))
                if len(remnode.getParents()) == 1:
                    users.getUploadDir(user).addChild(remnode)
                node.removeChild(remnode)
            except: # node not found
                pass
            req.writeTAL("web/edit/modules/files.html", {'children': node.getChildren(), 'node': node}, macro="edit_files_children_list")

        if req.params.get('data') == 'reorder':
            i = 0
            for id in req.params.get('order').split(","):
                if id != "":
                    n = tree.getNode(id)
                    n.setOrderPos(i)
                    i += 1

        if req.params.get('data') == 'translate':
            req.writeTALstr('<tal:block i18n:translate="" tal:content="msgstr"/>', {'msgstr': req.params.get('msgstr')})
        return ""

    if req.params.get("style") == "popup":
        v = {"basedirs": [tree.getRoot('home'), tree.getRoot('collections')]}
        id = req.params.get("id", tree.getRoot().id)
        v["script"] = "var currentitem = '%s';\nvar currentfolder = '%s';\nvar node = %s;" %(id, req.params.get('parent'), id)
        v["idstr"] = ",".join(ids)
        v["node"] = node

        if node.type != 'directory':
            try:
                if v['current_id'] == None:
                    v['current_id'] = node.id
            except KeyError:
                pass

        req.writeTAL("web/edit/modules/files.html", v, macro="edit_files_popup_selection")
        return ""

    if "operation" in req.params:
        op = req.params.get("operation")
        if op == "delete":
            for key in req.params.keys():  # delete file
                if key.startswith("del|"):
                    filename = key[4:-2].split("|")
                    for file in node.getFiles():
                        if file.getName() == filename[1] and file.type == filename[0]:
                            # remove all files in directory
                            if file.getMimeType() == "inode/directory":
                                for root, dirs, files in os.walk(file.retrieveFile()):
                                    for name in files:
                                        try:
                                            os.remove(root + "/" + name)
                                        except:
                                            pass
                                    os.removedirs(file.retrieveFile()+"/")
                            if len([f for f in node.getFiles() if f.getName()==filename[1] and f.type==filename[0]]) > 1:
                                # remove single file from database if there are duplicates
                                node.removeFile(file, single=True)
                            else:
                                # remove single file
                                node.removeFile(file)
                                try:
                                    os.remove(file.retrieveFile())
                                except:
                                    pass
                            break
                    break
                elif key.startswith("delatt|"):
                    for file in node.getFiles():
                        if file.getMimeType() == "inode/directory":
                            try:
                                os.remove(file.retrieveFile() + "/" + key.split("|")[2][:-2])
                            except:
                                pass
                            break
                    break

        elif op=="change":
            uploadfile = req.params.get("updatefile")

            if uploadfile:
                create_version_error = False
                # Create new version when change file
                if (req.params.get('generate_new_version') and not hasattr(node, "metaFields")):
                    if (req.params.get('version_comment', '').strip()==''
                        or req.params.get('version_comment', '').strip()=='&nbsp;'):
                        create_version_error = True
                        req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
                        ret += req.getTAL("web/edit/modules/files.html", {}, macro="version_error")
                    else:
                        current = node
                        node = node.createNewVersion(user)

                        for attr, value in current.items():
                            if node.get(attr)!="": # do not overwrite attributes
                                pass
                            else:
                                node.set(attr, value)
                        req.setStatus(httpstatus.HTTP_MOVED_TEMPORARILY)
                        ret += req.getTAL("web/edit/modules/metadata.html", {'url':'?id='+node.id+'&tab=files', 'pid':None}, macro="redirect")

                if req.params.get("change_file")=="yes" and not create_version_error: # remove old files
                    if uploadfile.filename:
                        if getMimeType(uploadfile.filename)[0] == 'other':
                            return '<h2 style="width:100%; text-align:center ;color:red">file-format is not supported (upload canceled / use attachment)</h2>'
                    for f in node.getFiles():
                        if f.getType() in node.getSysFiles():
                            node.removeFile(f)
                    node.set("system.version.comment", '('+t(req, "edit_files_new_version_exchanging_comment")+')\n'+req.params.get('version_comment', ''))

                if req.params.get("change_file")=="no" and not create_version_error:
                    node.set("system.version.comment", '('+t(req, "edit_files_new_version_adding_comment")+')\n'+req.params.get('version_comment', ''))

                if req.params.get("change_file") in ["yes", "no"] and not create_version_error:
                    if uploadfile.filename:
                        if getMimeType(uploadfile.filename)[0] == 'other':
                            return '<h2 style="width:100%; text-align:center ;color:red">file-format is not supported (upload canceled / use attachment)</h2>'
                    file = importFile(uploadfile.filename, uploadfile.tempname) # add new file
                    node.addFile(file)
                    logging.getLogger('usertracing').info(user.name+" changed file of node "+node.id+" to "+uploadfile.filename+" ("+uploadfile.tempname+")")

                attpath = ""
                for f in node.getFiles():
                    if f.getMimeType()=="inode/directory":
                        attpath = f.getName()
                        break

                if req.params.get("change_file")=="attdir" and not create_version_error: # add attachmentdir
                    dirname = req.params.get("inputname")

                    if attpath=="": # add attachment directory
                        attpath = req.params.get("inputname")
                        if not os.path.exists(getImportDir() + "/" + attpath):
                            os.mkdir(getImportDir() + "/" + attpath)
                            node.addFile(tree.FileNode(name=getImportDir() + "/" + attpath, mimetype="inode/directory", type="attachment"))

                        file = importFileIntoDir(getImportDir() + "/" + attpath, uploadfile.tempname) # add new file
                    node.set("system.version.comment", '('+t(req, "edit_files_new_version_attachment_directory_comment")+')\n'+req.params.get('version_comment', ''))
                    pass


                if req.params.get("change_file")=="attfile" and not create_version_error: # add file as attachment
                    if attpath=="":
                        # no attachment directory existing
                        file = importFile(uploadfile.filename, uploadfile.tempname) # add new file
                        file.mimetype = "inode/file"
                        file.type = "attachment"
                        node.addFile(file)
                    else:
                        # import attachment file into existing attachment directory
                        file = importFileIntoDir(getImportDir() + "/" + attpath, uploadfile.tempname) # add new file
                    node.set("system.version.comment", '('+t(req, "edit_files_new_version_attachment_comment")+')\n'+req.params.get('version_comment', ''))
                    pass

        elif op == "addthumb":  # create new thumbanil from uploaded file
            uploadfile = req.params.get("updatefile")

            if uploadfile:
                thumbname = os.path.join(getImportDir(), hashlib.md5(str(random.random())).hexdigest()[0:8]) + ".thumb"

                file = importFile(thumbname, uploadfile.tempname)  # add new file
                makeThumbNail(file.retrieveFile(), thumbname)
                makePresentationFormat(file.retrieveFile(), thumbname + "2")

                if os.path.exists(file.retrieveFile()):  # remove uploaded original
                    os.remove(file.retrieveFile())

                for f in node.getFiles():
                    if f.type in ["thumb", "presentation", "presentati"]:
                        if os.path.exists(f.retrieveFile()):
                            os.remove(f.retrieveFile())
                        node.removeFile(f)

                node.addFile(tree.FileNode(name=thumbname, type="thumb", mimetype="image/jpeg"))
                node.addFile(tree.FileNode(name=thumbname + "2", type="presentation", mimetype="image/jpeg"))
                logging.getLogger('usertracing').info(user.name + " changed thumbnail of node " + node.id)

        elif op == "postprocess":
            if hasattr(node, "event_files_changed"):
                try:
                    node.event_files_changed()
                    logging.getLogger('usertracing').info(user.name + " postprocesses node " + node.id)
                except:
                    update_error = True

    v = {"id": req.params.get("id", "0"), "tab": req.params.get("tab", ""), "node": node, "update_error": update_error,
         "user": user, "files": filter(lambda x: x.type != 'statistic', node.getFiles()),
         "statfiles": filter(lambda x: x.type == 'statistic', node.getFiles()),
         "attfiles": filter(lambda x: x.type == 'attachment', node.getFiles()), "att": [], "nodes": [node], "access": access}

    for f in v["attfiles"]:  # collect all files in attachment directory
        if f.getMimeType() == "inode/directory":
            for root, dirs, files in os.walk(f.retrieveFile()):
                for name in files:
                    af = tree.FileNode(root + "/" + name, "attachmentfile", getMimeType(name)[0])
                    v["att"].append(af)

    return req.getTAL("web/edit/modules/files.html", v, macro="edit_files_file")