Esempio n. 1
0
    def check_valid(self):
        """Performs validity check and sets self.valid"""
        self.valid = False
        if self.type not in RECIPIENT_TYPE.values():
            self.report_error("missing/invalid type: {}".format(self.type))
            return
        if not self.primary_idnum and self.using_hl7():
            self.report_error("missing primary_idnum")
            return
        if self.primary_idnum < 1 or self.primary_idnum > NUMBER_OF_IDNUMS:
            self.report_error("invalid primary_idnum: {}".format(
                self.primary_idnum))
            return
        if self.primary_idnum and self.require_idnum_mandatory:
            # (a) ID number must be mandatory in finalized records
            if not cc_policy.is_idnum_mandatory_in_finalize_policy(
                    self.primary_idnum):
                self.report_error(
                    "primary_idnum ({}) not mandatory in finalizing policy, "
                    "but needs to be".format(self.primary_idnum))
                return
            if not self.finalized_only:
                # (b) ID number must also be mandatory in uploaded,
                # non-finalized records
                if not cc_policy.is_idnum_mandatory_in_upload_policy(
                        self.primary_idnum):
                    self.report_error(
                        "primary_idnum ({}) not mandatory in upload policy, "
                        "but needs to be".format(self.primary_idnum))
                    return
        if not self.task_format or \
                self.task_format not in [
                    VALUE.OUTPUTTYPE_PDF,
                    VALUE.OUTPUTTYPE_HTML,
                    VALUE.OUTPUTTYPE_XML,
                ]:
            self.report_error(
                "missing/invalid task_format: {}".format(self.task_format))
            return
        if not self.task_format == VALUE.OUTPUTTYPE_XML:
            self.xml_field_comments = None
        # HL7
        if self.type == RECIPIENT_TYPE.HL7:
            if not self.divert_to_file:
                if not self.host:
                    self.report_error("missing host")
                    return
                if not self.port or self.port <= 0:
                    self.report_error(
                        "missing/invalid port: {}".format(self.port))
                    return
            if not self.idnum_type_list[self.primary_idnum - 1]:
                self.report_error(
                    "missing IDNUM_TYPE_{} (for primary ID)".format(
                        self.primary_idnum))
                return
        # File
        if self.type == RECIPIENT_TYPE.FILE:
            if not self.patient_spec_if_anonymous:
                self.report_error("missing patient_spec_if_anonymous")
                return
            if not self.patient_spec:
                self.report_error("missing patient_spec")
                return
            if not cc_filename.patient_spec_for_filename_is_valid(
                    self.patient_spec):
                self.report_error(
                    "invalid patient_spec: {}".format(self.patient_spec))
                return
            if not self.filename_spec:
                self.report_error("missing filename_spec")
                return
            if not cc_filename.filename_spec_is_valid(self.filename_spec):
                self.report_error(
                    "invalid filename_spec: {}".format(self.filename_spec))
                return
            # RiO metadata
            if self.rio_metadata:
                if not (1 <= self.rio_idnum <= NUMBER_OF_IDNUMS):
                    # ... test handles None values; 1 < None < 3 is False
                    self.report_error(
                        "invalid rio_idnum: {}".format(self.rio_idnum))
                    return
                if (not self.rio_uploading_user
                        or " " in self.rio_uploading_user
                        or len(self.rio_uploading_user) > RIO_MAX_USER_LEN):
                    self.report_error(
                        "missing/invalid rio_uploading_user: {} (must be "
                        "present, contain no spaces, and max length "
                        "{})".format(
                            self.rio_uploading_user,
                            RIO_MAX_USER_LEN))
                    return
                if not self.rio_document_type:
                    self.report_error("missing rio_document_type")
                    return

        # This section would be BETTER with a try/raise/except block, rather
        # than a bunch of return statements.

        # Done
        self.valid = True
Esempio n. 2
0
    def set_webview(self, environ, config):
        # ---------------------------------------------------------------------
        # Delayed imports
        # ---------------------------------------------------------------------
        import cgi
        import operator
        import os
        import urllib

        import cc_filename
        import cc_html  # caution, circular import
        import cc_policy
        import cc_namedtuples
        import cc_recipdef
        import cc_version

        logger = cc_logger.logger

        # ---------------------------------------------------------------------
        # Read from the environment
        # ---------------------------------------------------------------------
        # http://www.zytrax.com/tech/web/env_var.htm
        # Apache standard CGI variables:
        self.SCRIPT_NAME = environ.get("SCRIPT_NAME", "")
        self.SERVER_NAME = environ.get("SERVER_NAME")

        # Reconstruct URL:
        # http://www.python.org/dev/peps/pep-0333/#url-reconstruction
        url = environ.get("wsgi.url_scheme", "") + "://"
        if environ.get("HTTP_HOST"):
            url += environ.get("HTTP_HOST")
        else:
            url += environ.get("SERVER_NAME", "")
        if environ.get("wsgi.url_scheme") == "https":
            if environ.get("SERVER_PORT") != "443":
                url += ":" + environ.get("SERVER_PORT", "")
        else:
            if environ.get("SERVER_PORT") != "80":
                url += ":" + environ.get("SERVER_PORT", "")
        url += urllib.quote(environ.get("SCRIPT_NAME", ""))
        url += urllib.quote(environ.get("PATH_INFO", ""))
        # But not the query string:
        # if environ.get("QUERY_STRING"):
        #    url += "?" + environ.get("QUERY_STRING")

        self.SCRIPT_PUBLIC_URL_ESCAPED = cgi.escape(url)

        # ---------------------------------------------------------------------
        # Read from the config file:
        # ---------------------------------------------------------------------
        section = CONFIG_FILE_MAIN_SECTION
        self.MYSQL = get_config_parameter(config, section, "MYSQL", str, DEFAULT_MYSQL)
        self.MYSQLDUMP = get_config_parameter(config, section, "MYSQLDUMP", str, DEFAULT_MYSQLDUMP)

        self.LOCAL_INSTITUTION_URL = get_config_parameter(
            config, section, "LOCAL_INSTITUTION_URL", str, DEFAULT_LOCAL_INSTITUTION_URL
        )
        # note order dependency: RESOURCES_DIRECTORY, LOCAL_LOGO_FILE_ABSOLUTE
        self.RESOURCES_DIRECTORY = get_config_parameter(
            config, section, "RESOURCES_DIRECTORY", str, DEFAULT_RESOURCES_DIRECTORY
        )
        self.LOCAL_LOGO_FILE_ABSOLUTE = get_config_parameter(
            config,
            section,
            "LOCAL_LOGO_FILE_ABSOLUTE",
            str,
            os.path.join(self.RESOURCES_DIRECTORY, LOCAL_LOGO_FILE_WEBREF),
        )
        self.INTROSPECTION_DIRECTORY = get_config_parameter(
            config, section, "INTROSPECTION_DIRECTORY", str, DEFAULT_INTROSPECTION_DIRECTORY
        )
        self.INTROSPECTION = get_config_parameter_boolean(config, section, "INTROSPECTION", True)
        self.HL7_LOCKFILE = get_config_parameter(config, section, "HL7_LOCKFILE", str, None)
        self.SUMMARY_TABLES_LOCKFILE = get_config_parameter(config, section, "SUMMARY_TABLES_LOCKFILE", str, None)

        self.PASSWORD_CHANGE_FREQUENCY_DAYS = get_config_parameter(
            config, section, "PASSWORD_CHANGE_FREQUENCY_DAYS", int, DEFAULT_PASSWORD_CHANGE_FREQUENCY_DAYS
        )
        self.LOCKOUT_THRESHOLD = get_config_parameter(
            config, section, "LOCKOUT_THRESHOLD", int, DEFAULT_LOCKOUT_THRESHOLD
        )
        self.LOCKOUT_DURATION_INCREMENT_MINUTES = get_config_parameter(
            config, section, "LOCKOUT_DURATION_INCREMENT_MINUTES", int, DEFAULT_LOCKOUT_DURATION_INCREMENT_MINUTES
        )
        self.DISABLE_PASSWORD_AUTOCOMPLETE = get_config_parameter_boolean(
            config, section, "DISABLE_PASSWORD_AUTOCOMPLETE", True
        )

        self.PATIENT_SPEC_IF_ANONYMOUS = get_config_parameter(
            config, section, "PATIENT_SPEC_IF_ANONYMOUS", str, "anonymous"
        )
        self.PATIENT_SPEC = get_config_parameter(config, section, "PATIENT_SPEC", str, None)
        self.TASK_FILENAME_SPEC = get_config_parameter(config, section, "TASK_FILENAME_SPEC", str, None)
        self.TRACKER_FILENAME_SPEC = get_config_parameter(config, section, "TRACKER_FILENAME_SPEC", str, None)
        self.CTV_FILENAME_SPEC = get_config_parameter(config, section, "CTV_FILENAME_SPEC", str, None)

        self.WEBVIEW_LOGLEVEL = get_config_parameter_loglevel(config, section, "WEBVIEW_LOGLEVEL", logging.INFO)
        logger.setLevel(self.WEBVIEW_LOGLEVEL)

        self.SEND_ANALYTICS = get_config_parameter_boolean(config, section, "SEND_ANALYTICS", True)

        self.EXPORT_CRIS_DATA_DICTIONARY_TSV_FILE = get_config_parameter(
            config, section, "EXPORT_CRIS_DATA_DICTIONARY_TSV_FILE", str, None
        )

        # http://stackoverflow.com/questions/335695/lists-in-configparser
        try:
            hl7_items = config.items(CONFIG_FILE_RECIPIENTLIST_SECTION)
            for key, recipientdef_name in hl7_items:
                logger.debug(u"HL7 config: key={}, recipientdef_name=" "{}".format(key, recipientdef_name))
                h = cc_recipdef.RecipientDefinition(config, recipientdef_name)
                if h.valid:
                    self.HL7_RECIPIENT_DEFS.append(h)
        except ConfigParser.NoSectionError:
            logger.info("No config file section [{}]".format(CONFIG_FILE_RECIPIENTLIST_SECTION))

        # ---------------------------------------------------------------------
        # Built from the preceding:
        # ---------------------------------------------------------------------

        self.INTROSPECTION_FILES = []
        if self.INTROSPECTION:
            rootdir = self.INTROSPECTION_DIRECTORY
            for d in INTROSPECTABLE_DIRECTORIES:
                searchdir = os.sep.join([rootdir, d]) if d else rootdir
                for fname in os.listdir(searchdir):
                    junk, ext = os.path.splitext(fname)
                    if ext not in INTROSPECTABLE_EXTENSIONS:
                        continue
                    fullpath = os.sep.join([searchdir, fname])
                    prettypath = os.sep.join([d, fname]) if d else fname
                    self.INTROSPECTION_FILES.append(
                        cc_namedtuples.IntrospectionFileDetails(
                            fullpath=fullpath, prettypath=prettypath, searchterm=fname, ext=ext
                        )
                    )
            self.INTROSPECTION_FILES = sorted(self.INTROSPECTION_FILES, key=operator.attrgetter("prettypath"))

        # Cache tokenized ID policies
        cc_policy.tokenize_upload_id_policy(self.ID_POLICY_UPLOAD_STRING)
        cc_policy.tokenize_finalize_id_policy(self.ID_POLICY_FINALIZE_STRING)
        # Valid?
        if not cc_policy.upload_id_policy_valid():
            raise RuntimeError("UPLOAD_POLICY invalid in config")
        if not cc_policy.finalize_id_policy_valid():
            raise RuntimeError("FINALIZE_POLICY invalid in config")

        if self.RESOURCES_DIRECTORY is not None:
            self.CAMCOPS_STRINGS_FILE_ABSOLUTE = os.path.join(self.RESOURCES_DIRECTORY, CAMCOPS_STRINGS_FILE)
            self.CAMCOPS_LOGO_FILE_ABSOLUTE = os.path.join(self.RESOURCES_DIRECTORY, CAMCOPS_LOGO_FILE_WEBREF)

        # Note: HTML4 uses <img ...>; XHTML uses <img ... />;
        # HTML5 is happy with <img ... />

        # IE float-right problems: http://stackoverflow.com/questions/1820007
        # Tables are a nightmare in IE (table max-width not working unless you
        # also specify it for image size, etc.)
        self.WEB_LOGO = u"""
            <div class="web_logo_header">
                <a href="{}"><img class="logo_left" src="{}" alt="" /></a>
                <a href="{}"><img class="logo_right" src="{}" alt="" /></a>
            </div>
        """.format(
            self.SCRIPT_NAME, CAMCOPS_LOGO_FILE_WEBREF, self.LOCAL_INSTITUTION_URL, LOCAL_LOGO_FILE_WEBREF
        )

        self.WEBSTART = cc_html.WEB_HEAD + self.WEB_LOGO

        if cc_version.PDF_ENGINE in ["weasyprint", "pdfkit"]:
            # weasyprint: div with floating img does not work properly
            self.PDF_LOGO_LINE = u"""
                <div class="pdf_logo_header">
                    <table>
                        <tr>
                            <td class="image_td">
                                <img class="logo_left" src="file://{}" />
                            </td>
                            <td class="centregap_td"></td>
                            <td class="image_td">
                                <img class="logo_right" src="file://{}" />
                            </td>
                        </tr>
                    </table>
                </div>
            """.format(
                self.CAMCOPS_LOGO_FILE_ABSOLUTE, self.LOCAL_LOGO_FILE_ABSOLUTE
            )
        elif cc_version.PDF_ENGINE in ["pdfkit"]:
            self.PDF_LOGO_LINE = u"""
                <div class="pdf_logo_header">
                    <table>
                        <tr>
                            <td class="image_td">
                                <img class="logo_left" src="file://{}" />
                            </td>
                            <td class="centregap_td"></td>
                            <td class="image_td">
                                <img class="logo_right" src="file://{}" />
                            </td>
                        </tr>
                    </table>
                </div>
            """.format(
                self.CAMCOPS_LOGO_FILE_ABSOLUTE, self.LOCAL_LOGO_FILE_ABSOLUTE
            )
            # self.PDF_LOGO_LINE = u"""
            #     <div class="pdf_logo_header">
            #         <img class="logo_left" src="file://{}" />
            #         <img class="logo_right" src="file://{}" />
            #     </div>
            # """.format(
            #     self.CAMCOPS_LOGO_FILE_ABSOLUTE,
            #     self.LOCAL_LOGO_FILE_ABSOLUTE,
            # )
        elif cc_version.PDF_ENGINE in ["xhtml2pdf"]:
            # xhtml2pdf
            # hard to get logos positioned any other way than within a table
            self.PDF_LOGO_LINE = u"""
                <div class="header">
                    <table class="noborder">
                        <tr class="noborder">
                            <td class="noborderphoto" width="45%">
                                <img src="file://{}" height="{}"
                                        align="left" />
                            </td>
                            <td class="noborderphoto" width="10%"></td>
                            <td class="noborderphoto" width="45%">
                                <img src="file://{}" height="{}"
                                        align="right" />
                            </td>
                        </tr>
                    </table>
                </div>
            """.format(
                self.CAMCOPS_LOGO_FILE_ABSOLUTE,
                cc_html.PDF_LOGO_HEIGHT,
                self.LOCAL_LOGO_FILE_ABSOLUTE,
                cc_html.PDF_LOGO_HEIGHT,
            )
        else:
            raise AssertionError("Invalid PDF engine")

        if not self.PATIENT_SPEC_IF_ANONYMOUS:
            raise RuntimeError("Blank PATIENT_SPEC_IF_ANONYMOUS in [server] " "section of config file")

        if not self.PATIENT_SPEC:
            raise RuntimeError("Missing/blank PATIENT_SPEC in [server] section" " of config file")
        if not cc_filename.patient_spec_for_filename_is_valid(self.PATIENT_SPEC):
            raise RuntimeError("Invalid PATIENT_SPEC in [server] section of " "config file")

        if not self.TASK_FILENAME_SPEC:
            raise RuntimeError("Missing/blank TASK_FILENAME_SPEC in " "[server] section of config file")
        if not cc_filename.filename_spec_is_valid(self.TASK_FILENAME_SPEC):
            raise RuntimeError("Invalid TASK_FILENAME_SPEC in " "[server] section of config file")

        if not self.TRACKER_FILENAME_SPEC:
            raise RuntimeError("Missing/blank TRACKER_FILENAME_SPEC in " "[server] section of config file")
        if not cc_filename.filename_spec_is_valid(self.TRACKER_FILENAME_SPEC):
            raise RuntimeError("Invalid TRACKER_FILENAME_SPEC in " "[server] section of config file")

        if not self.CTV_FILENAME_SPEC:
            raise RuntimeError("Missing/blank CTV_FILENAME_SPEC in " "[server] section of config file")
        if not cc_filename.filename_spec_is_valid(self.CTV_FILENAME_SPEC):
            raise RuntimeError("Invalid CTV_FILENAME_SPEC in " "[server] section of config file")