예제 #1
0
    def runAction(self, node, op=""):
        fnode = None
        for fnode in node.files:
            if fnode.filetype == "document":
                break

        def reformatAuthors(s):
            authors = s.strip().split(";")
            if len(authors) > 1:
                authors = ", ".join(authors[:-1]) + " and " + authors[-1]
            else:
                authors = authors[0]
            return authors

        # get pdf form appended to this workflow step through upload field 'upload_pdfform'
        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)
        formfilelist, formfilelist2 = getFilelist(current_workflow_step,
                                                  'upload_pdfform')

        pdf_fields_editable = current_workflow_step.get("pdf_fields_editable")
        pdf_form_separate = current_workflow_step.get("pdf_form_separate")
        pdf_form_overwrite = current_workflow_step.get("pdf_form_overwrite")

        if pdf_fields_editable.lower() in ["1", "true"]:
            pdf_fields_editable = True
        else:
            pdf_fields_editable = False

        if pdf_form_separate.lower() in ["1", "true"]:
            pdf_form_separate = True
        else:
            pdf_form_separate = False

        fields = []
        f_retrieve_path = None

        schema = getMetaType(node.schema)

        if formfilelist:
            # take newest (mtime)
            f_mtime, f_name, f_mimetype, f_size, f_type, f_retrieve_path, f = formfilelist[
                -1]

            for field_dict in parse_pdftk_fields_dump(
                    get_pdftk_fields_dump(f_retrieve_path)):
                fieldname = field_dict.get('FieldName', None)
                if fieldname:
                    value = ''
                    if fieldname in dict(node.attrs.items()):
                        schemafield = schema.children.filter_by(
                            name=fieldname).first()
                        value = schemafield.getFormattedValue(node)[1]
                        if fieldname.find('author') >= 0:
                            value = reformatAuthors(value)
                    elif fieldname.lower() == 'node.schema':
                        value = getMetaType(node.schema).getLongName()
                    elif fieldname.lower() == 'node.id':
                        value = unicode(node.id)
                    elif fieldname.lower() == 'node.type':
                        value = node.type
                    elif fieldname.lower() == 'date()':
                        value = format_date(now(), format='%d.%m.%Y')
                    elif fieldname.lower() == 'time()':
                        value = format_date(now(), format='%H:%M:%S')
                    elif fieldname.find("+") > 0:
                        for _fn in fieldname.split('+'):
                            value = node.get(_fn)
                            if value:
                                break
                    elif '[att:' in fieldname:
                        value = fieldname
                        while '[att:' in value:
                            m = re.search('(?<=\[att:)([^&\]]+)', value)
                            if m:
                                if m.group(0) == 'id':
                                    v = unicode(node.id)
                                elif m.group(0) == 'type':
                                    v = node.type
                                elif m.group(0) == 'schema':
                                    v = getMetaType(node.schema).getLongName()
                                else:
                                    schemafield = schema.children.filter_by(
                                        name=m.group(0)).first()
                                    v = schemafield.getFormattedValue(node)[0]
                                value = value.replace(
                                    '[att:%s]' % (m.group(0)), v)
                    else:
                        logg.warning(
                            "workflowstep %s (%s): could not find attribute for pdf form field '%s' - node: '%s' (%s)",
                            current_workflow_step.name,
                            current_workflow_step.id, fieldname, node.name,
                            node.id)
                    fields.append((fieldname, remove_tags(desc(value))))

        if not pdf_form_separate and fnode and f_retrieve_path and os.path.isfile(
                f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path,
                                fields,
                                input_is_fullpath=True,
                                editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error(
                    "workflowstep %s (%s): could not create pdf file - node: '%s' (%s)"
                    % (current_workflow_step.name, current_workflow_step.id,
                       node.name, node.id))
                self.forward(node, False)
                return
            origname = fnode.abspath
            outfile = addPagesToPDF(pages, origname)

            for f in node.files:
                node.files.remove(f)
            fnode.path = outfile.replace(config.get("paths.datadir"), "")
            node.files.append(fnode)
            node.files.append(
                File(origname, 'upload',
                     'application/pdf'))  # store original filename
            node.event_files_changed()
            db.session.commit()
            logg.info(
                "workflow '%s' (%s), workflowstep '%s' (%s): added pdf form to pdf (node '%s' (%s)) fields: %s",
                current_workflow.name, current_workflow.id,
                current_workflow_step.name, current_workflow_step.id,
                node.name, node.id, fields)

        elif pdf_form_separate and f_retrieve_path and os.path.isfile(
                f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path,
                                fields,
                                input_is_fullpath=True,
                                editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error(
                    "workflowstep %s (%s): could not create pdf file - node: '%s' (%s)"
                    % (current_workflow_step.name, current_workflow_step.id,
                       node.name, node.id))
                self.forward(node, False)
                return
            importdir = getImportDir()
            try:
                new_form_path = join_paths(importdir,
                                           "%s_%s" % (node.id, f_name))
                counter = 0
                if not pdf_form_overwrite:  # build correct filename
                    while os.path.isfile(new_form_path):
                        counter += 1
                        new_form_path = join_paths(
                            importdir, "%s_%s_%s" % (node.id, counter, f_name))
                # copy new file and remove tmp
                shutil.copy(pages, new_form_path)
                if os.path.exists(pages):
                    os.remove(pages)
            except Exception:
                logg.exception(
                    "workflowstep %s (%s): could not copy pdf form to import directory - node: '%s' (%s), import directory: '%s'",
                    current_workflow_step.name, current_workflow_step.id,
                    node.name, node.id, importdir)
            found = 0
            for fn in node.files:
                if fn.abspath == new_form_path:
                    found = 1
                    break
            if found == 0 or (found == 1 and not pdf_form_overwrite):
                node.files.append(
                    File(new_form_path, 'pdf_form', 'application/pdf'))
                db.session.commit()

            logg.info(
                "workflow '%s' (%s), workflowstep '%s' (%s): added separate pdf form to node (node '%s' (%s)) fields: %s, path: '%s'",
                current_workflow.name, current_workflow.id,
                current_workflow_step.name, current_workflow_step.id,
                node.name, node.id, fields, new_form_path)
        else:
            logg.warning(
                "workflowstep %s (%s): could not process pdf form - node: '%s' (%s)",
                current_workflow_step.name, current_workflow_step.id,
                node.name, node.id)

        self.forward(node, True)
예제 #2
0
    def replaceVars(self, s, node, attrnode=None, field_value="", options=[], mask=None, raw=0, default=""):
        # if attrnode and node:
        for var in re.findall(r"\[(.+?)\]", s):
            if var.startswith("att:field|replacestring"):
                s2 = self.replaceStr(attrnode.getName(), var[24:])
                s = s.replace("[" + var + "]", s2)

            elif var.startswith("att:field|substring"):
                s2 = self.subStr(attrnode.getName(), var[20:])
                s = s.replace("[" + var + "]", s2)

            elif var == "field":
                s = s.replace("[field]", field_value)

            elif var == ("cmd:getTAL"):
                s = exportutils.handleCommand("cmd:getTAL", var, s, node, attrnode, field_value, options, mask)

            elif var.startswith("value|formatdate"):
                date_from = format_date(parse_date(node.get(attrnode.getName())), var[18:-1])
                s = s.replace("[" + var + "]", date_from)

            elif var.startswith("value|replacestring"):
                s2 = self.replaceStr(node.get(attrnode.getName()), var[20:])
                s = s.replace("[" + var + "]", s2)

            elif var.startswith("value|substring"):
                s2 = self.subStr(node.get(attrnode.getName()), var[16:])
                s = s.replace("[" + var + "]", s2)

            elif var.startswith("value|nodename"):
                try:
                    s2 = tree.getNode(node.get(attrnode.getName())).getName()
                except:
                    s2 = node.getName()
                s = s.replace("[" + var + "]", s2)

            elif var == "value":
                v = getMetadataType(attrnode.getFieldtype()).getFormatedValue(attrnode, node)[1]
                if v == "":
                    v = node.get(attrnode.getName())
                if v == "" and default != "":
                    v = default
                if "t" in options and not v.isdigit():
                    v = '"' + v + '"'
                s = s.replace("[value]", v)

            elif var == "ns":
                ns = ""
                for mapping in attrnode.get("exportmapping").split(";"):
                    n = tree.getNode(mapping)
                    if n.getNamespace() != "" and n.getNamespaceUrl() != "":
                        ns += "xmlns:" + n.getNamespace() + '="' + n.getNamespaceUrl() + '" '
                s = s.replace("[" + var + "]", ns)

            for ext in self.extensions:
                s = ext.func(s, var, node, attrnode)
        if raw == 1:
            return s

        ret = ""
        for i in range(0, len(s)):
            if s[i - 1] == "\\":
                if s[i] == "r":
                    ret += "\r"
                elif s[i] == "n":
                    ret += "\n"
                elif s[i] == "t":
                    ret += "\t"
            elif s[i] == "\\":
                pass
            else:
                ret += s[i]
        return desc(ret)
예제 #3
0
    def runAction(self, node, op=""):
        fnode = None
        for fnode in node.files:
            if fnode.filetype == "document":
                break

        def reformatAuthors(s):
            authors = s.strip().split(";")
            if len(authors) > 1:
                authors = ", ".join(authors[:-1]) + " and " + authors[-1]
            else:
                authors = authors[0]
            return authors

        # get pdf form appended to this workflow step through upload field 'upload_pdfform'
        current_workflow = getNodeWorkflow(node)
        current_workflow_step = getNodeWorkflowStep(node)
        formfilelist, formfilelist2 = getFilelist(current_workflow_step, 'upload_pdfform')

        pdf_fields_editable = current_workflow_step.get("pdf_fields_editable")
        pdf_form_separate = current_workflow_step.get("pdf_form_separate")
        pdf_form_overwrite = current_workflow_step.get("pdf_form_overwrite")

        if pdf_fields_editable.lower() in ["1", "true"]:
            pdf_fields_editable = True
        else:
            pdf_fields_editable = False

        if pdf_form_separate.lower() in ["1", "true"]:
            pdf_form_separate = True
        else:
            pdf_form_separate = False

        fields = []
        f_retrieve_path = None

        schema = getMetaType(node.schema)

        if formfilelist:
            # take newest (mtime)
            f_mtime, f_name, f_mimetype, f_size, f_type, f_retrieve_path, f = formfilelist[-1]

            for field_dict in parse_pdftk_fields_dump(get_pdftk_fields_dump(f_retrieve_path)):
                fieldname = field_dict.get('FieldName', None)
                if fieldname:
                    value = ''
                    if fieldname in dict(node.attrs.items()):
                        schemafield = schema.children.filter_by(name=fieldname).first()
                        value = schemafield.getFormattedValue(node)[1]
                        if fieldname.find('author') >= 0:
                            value = reformatAuthors(value)
                    elif fieldname.lower() == 'node.schema':
                        value = getMetaType(node.schema).getLongName()
                    elif fieldname.lower() == 'node.id':
                        value = unicode(node.id)
                    elif fieldname.lower() == 'node.type':
                        value = node.type
                    elif fieldname.lower() == 'date()':
                        value = format_date(now(), format='%d.%m.%Y')
                    elif fieldname.lower() == 'time()':
                        value = format_date(now(), format='%H:%M:%S')
                    elif fieldname.find("+") > 0:
                        for _fn in fieldname.split('+'):
                            value = node.get(_fn)
                            if value:
                                break
                    elif '[att:' in fieldname:
                        value = fieldname
                        while '[att:' in value:
                            m = re.search('(?<=\[att:)([^&\]]+)', value)
                            if m:
                                if m.group(0) == 'id':
                                    v = unicode(node.id)
                                elif m.group(0) == 'type':
                                    v = node.type
                                elif m.group(0) == 'schema':
                                    v = getMetaType(node.schema).getLongName()
                                else:
                                    schemafield = schema.children.filter_by(name=m.group(0)).first()
                                    v = schemafield.getFormattedValue(node)[0]
                                value = value.replace('[att:%s]' % (m.group(0)), v)
                    else:
                        logg.warning("workflowstep %s (%s): could not find attribute for pdf form field '%s' - node: '%s' (%s)",
                                       current_workflow_step.name, current_workflow_step.id, fieldname, node.name, node.id)
                    fields.append((fieldname, remove_tags(desc(value))))

        if not pdf_form_separate and fnode and f_retrieve_path and os.path.isfile(f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path, fields, input_is_fullpath=True, editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error("workflowstep %s (%s): could not create pdf file - node: '%s' (%s)" %
                           (current_workflow_step.name, current_workflow_step.id, node.name, node.id))
                self.forward(node, False)
                return
            origname = fnode.abspath
            outfile = addPagesToPDF(pages, origname)

            for f in node.files:
                node.files.remove(f)
            fnode.path = outfile.replace(config.get("paths.datadir"), "")
            node.files.append(fnode)
            node.files.append(File(origname, 'upload', 'application/pdf'))  # store original filename
            node.event_files_changed()
            db.session.commit()
            logg.info("workflow '%s' (%s), workflowstep '%s' (%s): added pdf form to pdf (node '%s' (%s)) fields: %s",
                current_workflow.name, current_workflow.id, current_workflow_step.name, current_workflow_step.id, node.name, node.id, fields)
            
        elif pdf_form_separate and f_retrieve_path and os.path.isfile(f_retrieve_path):
            pages = fillPDFForm(f_retrieve_path, fields, input_is_fullpath=True, editable=pdf_fields_editable)
            if pages == "":  # error in pdf creation -> forward to false operation
                logg.error("workflowstep %s (%s): could not create pdf file - node: '%s' (%s)" %
                           (current_workflow_step.name, current_workflow_step.id, node.name, node.id))
                self.forward(node, False)
                return
            importdir = getImportDir()
            try:
                new_form_path = join_paths(importdir, "%s_%s" % (node.id, f_name))
                counter = 0
                if not pdf_form_overwrite:  # build correct filename
                    while os.path.isfile(new_form_path):
                        counter += 1
                        new_form_path = join_paths(importdir, "%s_%s_%s" % (node.id, counter, f_name))
                # copy new file and remove tmp
                shutil.copy(pages, new_form_path)
                if os.path.exists(pages):
                    os.remove(pages)
            except Exception:
                logg.exception("workflowstep %s (%s): could not copy pdf form to import directory - node: '%s' (%s), import directory: '%s'",
                             current_workflow_step.name, current_workflow_step.id, node.name, node.id, importdir)
            found = 0
            for fn in node.files:
                if fn.abspath == new_form_path:
                    found = 1
                    break
            if found == 0 or (found == 1 and not pdf_form_overwrite):
                node.files.append(File(new_form_path, 'pdf_form', 'application/pdf'))
                db.session.commit()

            logg.info(
                "workflow '%s' (%s), workflowstep '%s' (%s): added separate pdf form to node (node '%s' (%s)) fields: %s, path: '%s'",
                current_workflow.name, current_workflow.id, current_workflow_step.name,
                current_workflow_step.id, node.name, node.id, fields, new_form_path)
        else:
            logg.warning("workflowstep %s (%s): could not process pdf form - node: '%s' (%s)",
                           current_workflow_step.name, current_workflow_step.id, node.name, node.id)

        self.forward(node, True)
예제 #4
0
    def replaceVars(self,
                    s,
                    node,
                    attrnode=None,
                    field_value="",
                    options=[],
                    mask=None,
                    raw=0,
                    default=""):
        # if attrnode and node:
        for var in re.findall(r'\[(.+?)\]', s):
            if var.startswith("att:field|replacestring"):
                s2 = self.replaceStr(attrnode.getName(), var[24:])
                s = s.replace("[" + var + "]", s2)

            elif var.startswith("att:field|substring"):
                s2 = self.subStr(attrnode.getName(), var[20:])
                s = s.replace("[" + var + "]", s2)

            elif var == "field":
                s = s.replace("[field]", field_value)

            elif var == ("cmd:getTAL"):
                s = exportutils.handleCommand('cmd:getTAL', var, s, node,
                                              attrnode, field_value, options,
                                              mask)

            elif var.startswith("value|formatdate"):
                date_from = format_date(
                    parse_date(node.get(attrnode.getName())), var[18:-1])
                s = s.replace("[" + var + "]", date_from)

            elif var.startswith("value|replacestring"):
                s2 = self.replaceStr(node.get(attrnode.getName()), var[20:])
                s = s.replace("[" + var + "]", s2)

            elif var.startswith("value|substring"):
                s2 = self.subStr(node.get(attrnode.getName()), var[16:])
                s = s.replace("[" + var + "]", s2)

            elif var.startswith("value|nodename"):
                try:
                    s2 = tree.getNode(node.get(attrnode.getName())).getName()
                except:
                    s2 = node.getName()
                s = s.replace("[" + var + "]", s2)

            elif var == "value":
                v = getMetadataType(attrnode.getFieldtype()).getFormatedValue(
                    attrnode, node)[1]
                if v == "":
                    v = node.get(attrnode.getName())
                if v == "" and default != "":
                    v = default
                if "t" in options and not v.isdigit():
                    v = '"' + v + '"'
                s = s.replace("[value]", v)

            elif var == "ns":
                ns = ""
                for mapping in attrnode.get("exportmapping").split(";"):
                    n = tree.getNode(mapping)
                    if n.getNamespace() != "" and n.getNamespaceUrl() != "":
                        ns += 'xmlns:' + n.getNamespace(
                        ) + '="' + n.getNamespaceUrl() + '" '
                s = s.replace("[" + var + "]", ns)

            for ext in self.extensions:
                s = ext.func(s, var, node, attrnode)
        if raw == 1:
            return s

        ret = ""
        for i in range(0, len(s)):
            if s[i - 1] == '\\':
                if s[i] == 'r':
                    ret += "\r"
                elif s[i] == 'n':
                    ret += "\n"
                elif s[i] == 't':
                    ret += "\t"
            elif s[i] == '\\':
                pass
            else:
                ret += s[i]
        return desc(ret)