Exemplo n.º 1
0
def sendmailUser_mask(req, id, err=0):

    v = getAdminStdVars(req)
    v["path"] = req.path[1:]

    if id in["execute", "execu"]:

        userid = req.params.get("userid")
        user = getUser(userid)
        if not user:
            path = req.path[1:].split("/")
            user = getExternalUser(userid, path[-1])

        password = makeRandomPassword()
        user.resetPassword(password)

        text = req.params.get("text")
        text = text.replace("[wird eingesetzt]", password)
        try:
            mail.sendmail(req.params.get("from"), req.params.get("email"), req.params.get("subject"), text)
        except mail.SocketError:
            print "Socket error while sending mail"
            req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
            return req.getTAL("web/admin/modules/user.html", v, macro="sendmailerror")
        return req.getTAL("web/admin/modules/user.html", v, macro="sendmaildone")

    user = getUser(id)
    if not user:
        path = req.path[1:].split("/")
        user = getExternalUser(id, path[-1])

    collections = []
    seen = {}
    access = acl.AccessData(user=user)
    for node in getAllCollections():
        if access.hasReadAccess(node):
            if access.hasWriteAccess(node):
                collections.append(node.name + " (lesen/schreiben)")
                seen[node.id] = None
    for node in tree.getRoot("collections").getChildren():
        if access.hasReadAccess(node) and node.id not in seen:
            collections.append(node.name + " (nur lesen)")
    x = {}
    x["name"] = "%s %s" % (user.getFirstName(), user.getLastName())
    if(x["name"] == ""):
        x["name"] = user.getName()
    x["host"] = config.get("host.name")
    x["login"] = user.getName()
    x["isEditor"] = user.isEditor()
    x["collections"] = list()
    x["groups"] = user.getGroups()
    x["groups"].sort()
    x["language"] = lang(req)
    x["collections"] = collections
    x["collections"].sort()

    v["mailtext"] = req.getTAL("web/admin/modules/user.html", x, macro="emailtext").strip()
    v["email"] = user.getEmail()
    v["userid"] = user.getName()
    return req.getTAL("web/admin/modules/user.html", v, macro="sendmail")
Exemplo n.º 2
0
    def runAction(self, node, op=""):
        attrs = ""
        for k, v in node.attrs.items():
            attrs += v
        if not checkXMLString(u'<?xml version="1.0" encoding="UTF-8"?>' + u'<tag>' + attrs + u'</tag>'):
            with suppress(Exception, warn=False):
                mail.sendmail(self.get('from'), self.get('to'), self.get('subject'), self.get('text'))

        self.forward(node, True)
Exemplo n.º 3
0
    def sendOut(self, node):
        xfrom = node.get("system.mailtmp.from")
        to = node.get("system.mailtmp.to")
        sendcondition = self.get("sendcondition")
        attach_pdf_form = bool(self.get("attach_pdf_form"))
        sendOk = 1

        try:
            if sendcondition.startswith("attr:") and "=" in sendcondition:
                arrname, value = sendcondition[5:].split("=")
                if node.get(arrname) != value:
                    sendOk = 0
            elif (sendcondition.startswith("schema=") and node.schema not in sendcondition[7:].split(";")) or (sendcondition.startswith("type=") and not node.get("type") in sendcondition[5:].split(";")) or (sendcondition == "hasfile" and len(node.files) == 0):
                sendOk = 0
        except:
            logg.exception("syntax error in email condition: %s", sendcondition)

        if sendOk:
            try:
                logg.info("sending mail to %s (%s)", to, self.get("email"))
                if not to:
                    raise MailError("No receiver address defined")
                if not xfrom:
                    raise MailError("No from address defined")
                attachments_paths_and_filenames = []
                if attach_pdf_form:
                    pdf_form_files = [f for f in node.files if f.filetype == 'pdf_form']
                    for i, f in enumerate(pdf_form_files):
                        if not os.path.isfile(f.abspath):
                            raise MailError("Attachment file not found: '%s'" % f.abspath)
                        else:
                            #attachments_paths_and_filenames.append((f.retrieveFile(), 'contract_%s_%s.pdf' %(i, node.id)))
                            attachments_paths_and_filenames.append((f.abspath, '%s' % (f.abspath.split('_')[-1])))
                    pass

                mail.sendmail(xfrom, to, node.get("system.mailtmp.subject"), node.get(
                    "system.mailtmp.text"), attachments_paths_and_filenames=attachments_paths_and_filenames)
            except:
                node.set("system.mailtmp.error", formatException())
                db.session.commit()
                logg.exception("Error while sending mail- node stays in workflowstep %s %s", self.id, self.name)
                return
        else:
            logg.info("sending mail prevented by condition %s " % (sendcondition))
            return
        for s in ["mailtmp.from", "mailtmp.to", "mailtmp.subject", "mailtmp.text",
                  "mailtmp.error", "mailtmp.talerror", "mailtmp.send"]:
            try:
                del node.system_attrs[s]
            except KeyError:
                continue

        db.session.commit()
        return 1
Exemplo n.º 4
0
    def runAction(self, node, op=""):
        attrs = ""
        for k, v in node.attrs.items():
            attrs += v
        if not checkXMLString(u'<?xml version="1.0" encoding="UTF-8"?>' +
                              u'<tag>' + attrs + u'</tag>'):
            with suppress(Exception, warn=False):
                mail.sendmail(self.get('from'), self.get('to'),
                              self.get('subject'), self.get('text'))

        self.forward(node, True)
Exemplo n.º 5
0
    def sendOut(self, node):
        xfrom = node.get("system.mailtmp.from")
        to = node.get("system.mailtmp.to")
        sendcondition = self.get("sendcondition")
        attach_pdf_form = bool(self.get("attach_pdf_form"))
        sendOk = 1

        try:
            if sendcondition.startswith("attr:") and "=" in sendcondition:
                arrname, value = sendcondition[5:].split("=")
                if node.get(arrname) != value:
                    sendOk = 0
            elif (sendcondition.startswith("schema=") and node.schema not in sendcondition[7:].split(";")) or (sendcondition.startswith("type=") and not node.get("type") in sendcondition[5:].split(";")) or (sendcondition == "hasfile" and len(node.files) == 0):
                sendOk = 0
        except:
            logg.exception("syntax error in email condition: %s", sendcondition)

        if sendOk:
            try:
                logg.info("sending mail to %s (%s)", to, self.get("email"))
                if not to:
                    raise MailError("No receiver address defined")
                if not xfrom:
                    raise MailError("No from address defined")
                attachments_paths_and_filenames = []
                if attach_pdf_form:
                    pdf_form_files = [f for f in node.files if f.filetype == 'pdf_form']
                    for i, f in enumerate(pdf_form_files):
                        if not os.path.isfile(f.abspath):
                            raise MailError("Attachment file not found: '%s'" % f.abspath)
                        else:
                            #attachments_paths_and_filenames.append((f.retrieveFile(), 'contract_%s_%s.pdf' %(i, node.id)))
                            attachments_paths_and_filenames.append((f.abspath, '%s' % (f.abspath.split('_')[-1])))
                    pass

                mail.sendmail(xfrom, to, node.get("system.mailtmp.subject"), node.get(
                    "system.mailtmp.text"), attachments_paths_and_filenames=attachments_paths_and_filenames)
            except:
                node.set("system.mailtmp.error", formatException())
                db.session.commit()
                logg.exception("Error while sending mail- node stays in workflowstep %s %s", self.id, self.name)
                return
        else:
            logg.info("sending mail prevented by condition %s " % (sendcondition))
            return
        for s in ["mailtmp.from", "mailtmp.to", "mailtmp.subject", "mailtmp.text",
                  "mailtmp.error", "mailtmp.talerror", "mailtmp.send"]:
            try:
                del node.system_attrs[s]
            except KeyError:
                continue

        db.session.commit()
        return 1
Exemplo n.º 6
0
    def runAction(self, node, op=""):
        attrs = ""
        for k, v in node.items():
            attrs += v

        if not checkXMLString(attrs):
            try:
                mail.sendmail(self.get('from'), self.get('to'), self.get('subject'), self.get('text'))
            except:
                pass

        self.forward(node, True)
Exemplo n.º 7
0
    def runAction(self, node, op=""):
        attrs = ""
        for k, v in node.items():
            attrs += v

        if not checkXMLString(attrs):
            try:
                mail.sendmail(self.get('from'), self.get('to'),
                              self.get('subject'), self.get('text'))
            except:
                pass

        self.forward(node, True)
Exemplo n.º 8
0
import os

# 用例路径
case_path = os.path.join(os.getcwd(), "testcase")
# 报告存放路径
report_path = os.path.join(os.getcwd(), "report")


def all_case():
    discover = unittest.defaultTestLoader.discover(case_path,
                                                   pattern="test*.py",
                                                   top_level_dir=None)
    print(discover)
    return discover


if __name__ == "__main__":
    # html报告文件路径
    now = time.strftime('%Y-%m-%d_%H%M%S')
    report_name = 'testResult_' + now + '.html'
    # report_abspath = os.path.join(report_path, "result.html")
    report_abspath = os.path.join(report_path, report_name)
    fp = open(report_abspath, "wb")
    runner = HTMLTestRunnerChinese.HTMLTestRunner(stream=fp,
                                                  title=u'自动化测试报告,测试结果如下:',
                                                  description=u'用例执行情况:')
    runner.run(all_case())
    fp.close()
    # 发送邮件
    mail.sendmail()
Exemplo n.º 9
0
def getContent(req, ids):
    """
    The standard method,  which has to be implemented by every module.
    It's called in edit.py, where all the modules will be identified.
    """
    raise Exception("ACL must be fixed!")
    user = current_user
    node = q(Node).get(ids[0])

    # first prove if the user has the required rights to call this module
    if 'sortfiles' in user.hidden_edit_functions or not node.has_write_access():
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL('web/edit/edit.html', {}, macro='access_error')

    if node.isContainer():
        nodes = u', '.join(node.children.getIDs())
    else:
        nodes = unicode(node.id)

    v = {'msg': '',
         'urn_institutionid': config.get('urn.institutionid'),
         'urn_pubtypes': config.get('urn.pubtypes').split(';'),
         'namespaces': config.get('urn.namespace').split(';'),
         'user': user,
         'nodes': nodes.split(', '),
         'type': req.params.get('id_type'),
         'show_form': True,
         'namespace': req.params.get('namespace'),
         'urn_type': req.params.get('urn_type'),
         'host': config.get('host.name'),
         'creator': user
         }

    if user.is_admin:
        if 'id_type' in req.params:
            if req.params.get('id_type') == 'urn':
                createUrn(node, req.params.get('namespace'), req.params.get('urn_type'))
            elif req.params.get('id_type') == 'doi':
                try:
                    createDOI(node)
                except:
                    return req.error(500, "doi was not successfully registered")

            db.session.commit()

            if any(identifier in node.attributes for identifier in ('urn', 'doi')):
                if not node.get('system.identifierdate'):
                    node.set('system.identifierdate', unicode(date.now()))
                    db.session.commit()
                if node.get('system.identifierstate') != '2':
                    node.set('system.identifierstate', u'2')
                    db.session.commit()

                    # add nobody ruleset if not set
                    if node.access_rule_assocs.filter_by(ruletype=u'write', invert=True, blocking=True).scalar() is None:
                        everybody_rule = AccessRule()
                        db.session.add(everybody_rule)
                        node.access_rule_assocs.append(NodeToAccessRule(rule=everybody_rule, ruletype=u"write", invert=True, blocking=True))
                        db.session.commit()

                try:
                    mailtext = req.getTAL('web/edit/modules/identifier.html', v, macro='generate_identifier_usr_mail_2')
                    mail.sendmail(config.get('email.admin'),  # email from
                                  "%s;%s" % (config.get('email.admin'), user.getEmail()), # email to
                                  u'Vergabe eines Identifikators / Generation of an Identifier',
                                  mailtext)

                except mail.SocketError:
                    logg.exception('failed to send Autorenvertrag mail to user %r (%s): %r' % (user.login_name, user.getName(), user.getEmail()))
                    v['msg'] = t(lang(req), 'edit_identifier_mail_fail')

        if node.get('system.identifierstate') != '2':
            v['msg'] = t(lang(req), 'edit_identifier_state_0_1_admin')
        else:
            v['msg'] = t(lang(req), 'edit_identifier_state_2_admin')

    else:
        if pathutils.isDescendantOf(node, q(Collections).one()):
            if not node.get('system.identifierstate'):
                if 'id_type' in req.params:
                    try:
                        # fetch autorenvertrag
                        attachment = []
                        autorenvertrag_name = 'formular_autorenvertrag.pdf'
                        autorenvertrag_path = os.path.join(config.get('paths.tempdir'),
                                                           autorenvertrag_name)

                        if not os.path.isfile(autorenvertrag_path):
                            logg.error("Unable to attach Autorenvertrag. Attachment file not found: '%s'", autorenvertrag_path)
                            raise IOError('Autorenvertrag was not located on disk at %s. Please send this error message to %s' %
                                          (autorenvertrag_path, config.get('email.admin')))
                        else:
                            attachment.append((autorenvertrag_path, 'Autorenvertrag.pdf'))

                        # notify user
                        mailtext_user = req.getTAL(
                            'web/edit/modules/identifier.html', v, macro='generate_identifier_usr_mail_1_' + lang(req))
                        mail.sendmail(config.get('email.admin'),
                                      ("%s;%s" % (config.get('email.admin'), user.getEmail())),
                                      unicode(t(lang(req), 'edit_identifier_mail_title_usr_1')),
                                      mailtext_user,
                                      attachments_paths_and_filenames=attachment)

                        # notify admin
                        mailtext_admin = req.getTAL('web/edit/modules/identifier.html', v, macro='generate_identifier_admin_mail')
                        mail.sendmail(config.get('email.admin'),
                                      config.get('email.admin'),
                                      u'Antrag auf Vergabe eines Identifikators',
                                      mailtext_admin)

                        node.set('system.identifierstate', u'1')
                        db.session.commit()

                        # add nobody rule if not set
                        if node.access_rule_assocs.filter_by(ruletype=u'write', invert=True, blocking=True).scalar() is None:
                            everybody_rule = AccessRule()
                            db.session.add(everybody_rule)
                            node.access_rule_assocs.append(NodeToAccessRule(rule=everybody_rule, ruletype=u"write", invert=True, blocking=True))
                            db.session.commit()

                    except mail.SocketError:
                        logg.exception('failed to send identifier request mail')
                        v['msg'] = t(lang(req), 'edit_identifier_mail_fail')
                else:
                    v['msg'] = t(lang(req), 'edit_identifier_state_0_usr')

            if node.get('system.identifierstate') == '1':
                v['show_form'] = False
                v['msg'] = t(lang(req), 'edit_identifier_state_1_usr')
        else:
            v['show_form'] = False
            v['msg'] = t(lang(req), 'edit_identifier_state_published')

    v['urn_val'] = node.get('urn')
    v['doi_val'] = node.get('doi')

    # hides form if all identifier types are already set
    if all(idents != '' for idents in (v['urn_val'], v['doi_val'])):
        v['show_form'] = False
        v['msg'] = t(lang(req), 'edit_identifier_all_types_set')

    v["csrf"] = req.csrf_token.current_token
    return req.getTAL('web/edit/modules/identifier.html', v, macro='set_identifier')
Exemplo n.º 10
0
def pwdforgotten(req):
    if len(req.params) > 3:  # user changed to browsing
        return buildURL(req)

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

    if req.params.get("action", "") == "activate":  # do activation of new password
        id, key = req.params.get("key").replace("/", "").split('-')
        targetuser = users.getUser(id)

        if targetuser.get("newpassword.activation_key") == key:
            newpassword = targetuser.get("newpassword.password")

            if newpassword:
                targetuser.set("password", newpassword)
                print "password reset for user '%s' (id=%s) reset" % (targetuser.getName(), targetuser.id)
                targetuser.removeAttribute("newpassword.password")
                targetuser.set("newpassword.time_activated", date.format_date())
                logging.getLogger('usertracing').info(
                    "new password activated for user: %s - was requested: %s by %s" %
                    (targetuser.getName(),
                     targetuser.get("newpassword.time_requested"),
                        targetuser.get("newpassword.request_ip")))

                navframe.write(
                    req, req.getTAL(
                        theme.getTemplate("login.html"), {
                            "username": targetuser.getName()}, macro="pwdforgotten_password_activated"))
                return httpstatus.HTTP_OK

            else:
                print "invalid key: wrong key or already used key"
                navframe.write(
                    req, req.getTAL(
                        theme.getTemplate("login.html"), {
                            "message": "pwdforgotten_password_invalid_key"}, macro="pwdforgotten_message"))
                return httpstatus.HTTP_OK

    elif "user" in req.params:  # create email with activation information
        username = req.params.get("user", "")

        if username == '':
            req.params['error'] = "pwdforgotten_noentry"

        else:
            targetuser = users.getUser(username)

            if not targetuser or not targetuser.canChangePWD():
                logging.getLogger('usertracing').info("new password requested for non-existing user: "******"pwdforgotten_nosuchuser"

            else:
                password = users.makeRandomPassword()
                randomkey = mkKey()

                targetuser.set("newpassword.password", hashlib.md5(password).hexdigest())
                targetuser.set("newpassword.time_requested", date.format_date())
                targetuser.set("newpassword.activation_key", randomkey)
                targetuser.set("newpassword.request_ip", req.ip)

                v = {}
                v["name"] = targetuser.getName()
                v["host"] = config.get("host.name")
                v["login"] = targetuser.getName()
                v["language"] = lang(req)
                v["activationlink"] = v["host"] + "/pwdforgotten?action=activate&key=%s-%s" % (targetuser.id, randomkey)
                v["email"] = targetuser.getEmail()
                v["userid"] = targetuser.getName()

                # going to send the mail
                try:
                    mailtext = req.getTAL(theme.getTemplate("login.html"), v, macro="emailtext")
                    mailtext = mailtext.strip().replace("[$newpassword]", password).replace("[wird eingesetzt]", password)

                    mail.sendmail(config.get("email.admin"), targetuser.getEmail(), t(lang(req), "pwdforgotten_email_subject"), mailtext)
                    logging.getLogger('usertracing').info("new password requested for user: %s - activation email sent" % username)
                    navframe.write(
                        req, req.getTAL(
                            theme.getTemplate("login.html"), {
                                "message": "pwdforgotten_butmailnowsent"}, macro="pwdforgotten_message"))
                    return httpstatus.HTTP_OK

                except mail.SocketError:
                    print "Socket error while sending mail"
                    logging.getLogger('usertracing').info(
                        "new password requested for user: %s - failed to send activation email" % username)
                    return req.getTAL(
                        theme.getTemplate("login.html"), {"message": "pwdforgotten_emailsenderror"}, macro="pwdforgotten_message")

    # standard operation
    navframe.write(req, req.getTAL(theme.getTemplate("login.html"), {
                   "error": req.params.get("error"), "user": users.getUserFromRequest(req)}, macro="pwdforgotten"))
    return httpstatus.HTTP_OK
Exemplo n.º 11
0
def getContent(req, ids):
    """
    The standard method,  which has to be implemented by every module.
    It's called in edit.py, where all the modules will be identified.
    """
    raise Exception("ACL must be fixed!")
    user = current_user
    node = q(Node).get(ids[0])

    # first prove if the user has the required rights to call this module
    if 'sortfiles' in user.hidden_edit_functions or not node.has_write_access(
    ):
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return req.getTAL('web/edit/edit.html', {}, macro='access_error')

    if node.isContainer():
        nodes = u', '.join(node.children.getIDs())
    else:
        nodes = unicode(node.id)

    v = {
        'msg': '',
        'urn_institutionid': config.get('urn.institutionid'),
        'urn_pubtypes': config.get('urn.pubtypes').split(';'),
        'namespaces': config.get('urn.namespace').split(';'),
        'user': user,
        'nodes': nodes.split(', '),
        'type': req.params.get('id_type'),
        'show_form': True,
        'namespace': req.params.get('namespace'),
        'urn_type': req.params.get('urn_type'),
        'host': config.get('host.name'),
        'creator': user
    }

    if user.is_admin:
        if 'id_type' in req.params:
            if req.params.get('id_type') == 'urn':
                createUrn(node, req.params.get('namespace'),
                          req.params.get('urn_type'))
            elif req.params.get('id_type') == 'doi':
                try:
                    createDOI(node)
                except:
                    return _error(req, 500,
                                  "doi was not successfully registered")

            db.session.commit()

            if any(identifier in node.attributes
                   for identifier in ('urn', 'doi')):
                if not node.get('system.identifierdate'):
                    node.set('system.identifierdate', unicode(date.now()))
                    db.session.commit()
                if node.get('system.identifierstate') != '2':
                    node.set('system.identifierstate', u'2')
                    db.session.commit()

                    # add nobody ruleset if not set
                    if node.access_rule_assocs.filter_by(
                            ruletype=u'write', invert=True,
                            blocking=True).scalar() is None:
                        everybody_rule = AccessRule()
                        db.session.add(everybody_rule)
                        node.access_rule_assocs.append(
                            NodeToAccessRule(rule=everybody_rule,
                                             ruletype=u"write",
                                             invert=True,
                                             blocking=True))
                        db.session.commit()

                try:
                    mailtext = req.getTAL(
                        'web/edit/modules/identifier.html',
                        v,
                        macro='generate_identifier_usr_mail_2')
                    mail.sendmail(
                        config.get('email.admin'),  # email from
                        "%s;%s" % (config.get('email.admin'),
                                   user.getEmail()),  # email to
                        u'Vergabe eines Identifikators / Generation of an Identifier',
                        mailtext)

                except mail.SocketError:
                    logg.exception(
                        'failed to send Autorenvertrag mail to user %r (%s): %r'
                        % (user.login_name, user.getName(), user.getEmail()))
                    v['msg'] = t(lang(req), 'edit_identifier_mail_fail')

        if node.get('system.identifierstate') != '2':
            v['msg'] = t(lang(req), 'edit_identifier_state_0_1_admin')
        else:
            v['msg'] = t(lang(req), 'edit_identifier_state_2_admin')

    else:
        if pathutils.isDescendantOf(node, q(Collections).one()):
            if not node.get('system.identifierstate'):
                if 'id_type' in req.params:
                    try:
                        # fetch autorenvertrag
                        attachment = []
                        autorenvertrag_name = 'formular_autorenvertrag.pdf'
                        autorenvertrag_path = os.path.join(
                            config.get('paths.tempdir'), autorenvertrag_name)

                        if not os.path.isfile(autorenvertrag_path):
                            logg.error(
                                "Unable to attach Autorenvertrag. Attachment file not found: '%s'",
                                autorenvertrag_path)
                            raise IOError(
                                'Autorenvertrag was not located on disk at %s. Please send this error message to %s'
                                % (autorenvertrag_path,
                                   config.get('email.admin')))
                        else:
                            attachment.append(
                                (autorenvertrag_path, 'Autorenvertrag.pdf'))

                        # notify user
                        mailtext_user = req.getTAL(
                            'web/edit/modules/identifier.html',
                            v,
                            macro='generate_identifier_usr_mail_1_' +
                            lang(req))
                        mail.sendmail(
                            config.get('email.admin'),
                            ("%s;%s" %
                             (config.get('email.admin'), user.getEmail())),
                            unicode(
                                t(lang(req),
                                  'edit_identifier_mail_title_usr_1')),
                            mailtext_user,
                            attachments_paths_and_filenames=attachment)

                        # notify admin
                        mailtext_admin = req.getTAL(
                            'web/edit/modules/identifier.html',
                            v,
                            macro='generate_identifier_admin_mail')
                        mail.sendmail(
                            config.get('email.admin'),
                            config.get('email.admin'),
                            u'Antrag auf Vergabe eines Identifikators',
                            mailtext_admin)

                        node.set('system.identifierstate', u'1')
                        db.session.commit()

                        # add nobody rule if not set
                        if node.access_rule_assocs.filter_by(
                                ruletype=u'write', invert=True,
                                blocking=True).scalar() is None:
                            everybody_rule = AccessRule()
                            db.session.add(everybody_rule)
                            node.access_rule_assocs.append(
                                NodeToAccessRule(rule=everybody_rule,
                                                 ruletype=u"write",
                                                 invert=True,
                                                 blocking=True))
                            db.session.commit()

                    except mail.SocketError:
                        logg.exception(
                            'failed to send identifier request mail')
                        v['msg'] = t(lang(req), 'edit_identifier_mail_fail')
                else:
                    v['msg'] = t(lang(req), 'edit_identifier_state_0_usr')

            if node.get('system.identifierstate') == '1':
                v['show_form'] = False
                v['msg'] = t(lang(req), 'edit_identifier_state_1_usr')
        else:
            v['show_form'] = False
            v['msg'] = t(lang(req), 'edit_identifier_state_published')

    v['urn_val'] = node.get('urn')
    v['doi_val'] = node.get('doi')

    # hides form if all identifier types are already set
    if all(idents != '' for idents in (v['urn_val'], v['doi_val'])):
        v['show_form'] = False
        v['msg'] = t(lang(req), 'edit_identifier_all_types_set')

    v["csrf"] = req.csrf_token.current_token
    return req.getTAL('web/edit/modules/identifier.html',
                      v,
                      macro='set_identifier')
Exemplo n.º 12
0
def getContent(req, ids):
    """
    The standard method,  which has to be implemented by every module.
    It's called in edit.py, where all the modules will be identified.
    """
    user = users.getUserFromRequest(req)
    access = acl.AccessData(req)
    node = tree.getNode(ids[0])
    access_nobody = 'nicht Jeder'

    # first prove if the user has the required rights to call this module
    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')

    if node.isContainer():
        nodes = ', '.join(node.getChildren().getIDs())
    else:
        nodes = node.get('node.id')

    v = {
        'msg': '',
        'urn_institutionid': config.get('urn.institutionid'),
        'urn_pubtypes': config.get('urn.pubtypes').split(';'),
        'namespaces': config.get('urn.namespace').split(';'),
        'user': user,
        'nodes': nodes,
        'type': req.params.get('id_type'),
        'show_form': True,
        'namespace': req.params.get('namespace'),
        'urn_type': req.params.get('urn_type'),
        'host': config.get('host.name'),
        'creator': users.getUser(node.get('creator'))
    }

    if user.isAdmin():
        if 'id_type' in req.params:
            if req.params.get('id_type') == 'hash':
                createHash(node)
            if req.params.get('id_type') == 'urn':
                createUrn(node, req.params.get('namespace'),
                          req.params.get('urn_type'))
            if req.params.get('id_type') == 'doi':
                try:
                    createDOI(node)
                except:
                    return req.error(500,
                                     "doi was not successfully registered")

            if any(identifier in node.attributes
                   for identifier in ('hash', 'urn', 'doi')):
                if not node.get('system.identifierdate'):
                    node.set('system.identifierdate', date.now())
                if node.get('system.identifierstate') != '2':
                    node.set('system.identifierstate', '2')

                    # add nobody rule if not set
                    if node.getAccess('write') is None:
                        node.setAccess('write', access_nobody)
                    else:
                        if access_nobody not in node.getAccess('write'):
                            node.setAccess(
                                'write', ','.join(
                                    [node.getAccess('write'), access_nobody]))

                try:
                    mailtext = req.getTAL(
                        'web/edit/modules/identifier.html',
                        v,
                        macro='generate_identifier_usr_mail_2')
                    mail.sendmail(
                        config.get('email.admin'),
                        users.getUser(node.get('creator')).get('email'),
                        'Vergabe eines Idektifikators / Generation of an Identifier',
                        mailtext)

                except mail.SocketError:
                    logging.getLogger('backend').error(
                        'failed to send Autorenvertrag mail to user %s' %
                        node.get('creator'))
                    v['msg'] = t(lang(req), 'edit_identifier_mail_fail')

        if node.get('system.identifierstate') != '2':
            v['msg'] = t(lang(req), 'edit_identifier_state_0_1_admin')
        else:
            v['msg'] = t(lang(req), 'edit_identifier_state_2_admin')

    else:
        if pathutils.isDescendantOf(node, tree.getRoot('collections')):
            if not node.get('system.identifierstate'):
                if 'id_type' in req.params:
                    try:
                        # fetch autorenvertrag
                        attachment = []
                        autorenvertrag_name = 'formular_autorenvertrag.pdf'
                        autorenvertrag_path = os.path.join(
                            config.get('paths.tempdir'), autorenvertrag_name)

                        if not os.path.isfile(autorenvertrag_path):
                            logging.getLogger('backend').error(
                                "Unable to attach Autorenvergrag. Attachment file not found: '%s'"
                                % autorenvertrag_path)
                            raise IOError(
                                'Autorenvertrag was not located on disk at %s. Please send this error message to %s'
                                % (autorenvertrag_path,
                                   config.get('email.admin')))
                        else:
                            attachment.append(
                                (autorenvertrag_path, 'Autorenvertrag.pdf'))

                        # notify user
                        mailtext_user = req.getTAL(
                            'web/edit/modules/identifier.html',
                            v,
                            macro='generate_identifier_usr_mail_1_' +
                            lang(req))
                        mail.sendmail(
                            config.get('email.admin'),
                            user.get('email'),
                            t(lang(req), 'edit_identifier_mail_title_usr_1'),
                            mailtext_user,
                            attachments_paths_and_filenames=attachment)

                        # notify admin
                        mailtext_admin = req.getTAL(
                            'web/edit/modules/identifier.html',
                            v,
                            macro='generate_identifier_admin_mail')
                        mail.sendmail(
                            config.get('email.admin'),
                            config.get('email.admin'),
                            'Antrag auf Vergabe eines Identifikators',
                            mailtext_admin)

                        node.set('system.identifierstate', '1')

                        # add nobody rule
                        print node.getAccess('write')
                        if node.getAccess('write') is None:
                            node.setAccess('write', access_nobody)
                        else:
                            if access_nobody not in node.getAccess('write'):
                                node.setAccess(
                                    'write', ','.join([
                                        node.getAccess('write'), access_nobody
                                    ]))

                    except mail.SocketError:
                        logging.getLogger('backend').error(
                            'failed to send identifier request mail')
                        v['msg'] = t(lang(req), 'edit_identifier_mail_fail')
                else:
                    v['msg'] = t(lang(req), 'edit_identifier_state_0_usr')

            if node.get('system.identifierstate') == '1':
                v['show_form'] = False
                v['msg'] = t(lang(req), 'edit_identifier_state_1_usr')
        else:
            v['show_form'] = False
            v['msg'] = t(lang(req), 'edit_identifier_state_published')

    v['hash_val'] = node.get('hash')
    v['urn_val'] = node.get('urn')
    v['doi_val'] = node.get('doi')

    # hides form if all identifier types are already set
    if all(idents != ''
           for idents in (v['hash_val'], v['urn_val'], v['doi_val'])):
        v['show_form'] = False
        v['msg'] = t(lang(req), 'edit_identifier_all_types_set')

    return req.getTAL('web/edit/modules/identifier.html',
                      v,
                      macro='set_identifier')
Exemplo n.º 13
0
def sendmailUser_mask(req, id, err=0):

    v = getAdminStdVars(req)
    v["path"] = req.path[1:]

    if id in ["execute", "execu"]:

        userid = req.params.get("userid")
        user = getUser(userid)
        if not user:
            path = req.path[1:].split("/")
            user = getExternalUser(userid, path[-1])

        password = makeRandomPassword()
        user.resetPassword(password)

        text = req.params.get("text")
        text = text.replace("[wird eingesetzt]", password)
        try:
            mail.sendmail(req.params.get("from"), req.params.get("email"),
                          req.params.get("subject"), text)
        except mail.SocketError:
            print "Socket error while sending mail"
            req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
            return req.getTAL("web/admin/modules/user.html",
                              v,
                              macro="sendmailerror")
        return req.getTAL("web/admin/modules/user.html",
                          v,
                          macro="sendmaildone")

    user = getUser(id)
    if not user:
        path = req.path[1:].split("/")
        user = getExternalUser(id, path[-1])

    collections = []
    seen = {}
    access = acl.AccessData(user=user)
    for node in getAllCollections():
        if access.hasReadAccess(node):
            if access.hasWriteAccess(node):
                collections.append(node.name + " (lesen/schreiben)")
                seen[node.id] = None
    for node in tree.getRoot("collections").getChildren():
        if access.hasReadAccess(node) and node.id not in seen:
            collections.append(node.name + " (nur lesen)")
    x = {}
    x["name"] = "%s %s" % (user.getFirstName(), user.getLastName())
    if (x["name"] == ""):
        x["name"] = user.getName()
    x["host"] = config.get("host.name")
    x["login"] = user.getName()
    x["isEditor"] = user.isEditor()
    x["collections"] = list()
    x["groups"] = user.getGroups()
    x["groups"].sort()
    x["language"] = lang(req)
    x["collections"] = collections
    x["collections"].sort()

    v["mailtext"] = req.getTAL("web/admin/modules/user.html",
                               x,
                               macro="emailtext").strip()
    v["email"] = user.getEmail()
    v["userid"] = user.getName()
    return req.getTAL("web/admin/modules/user.html", v, macro="sendmail")
Exemplo n.º 14
0
def notify(subject, log_file = None):
    if log_file is None:
        log_file = PathMgr.get_log_path('%s.log'%str(datetime.date.today()))
    mail_config = ConfigMgr.get_mail_config()
    sendmail(mail_config['smtp_server'], mail_config['sender'], mail_config['sender_password'], mail_config['receiver'], subject, log_file)
Exemplo n.º 15
0
def main():
    """
    This script attempts to give an overview of the completeness and correctness of the
    search databases. The report will be generated by the script and sent to the emails
    which are set in the EMAIL_RECIPIENTS variable.
    """
    t = time.time()
    published_nodes = set([
        int(node.id) for node in tree.getNode(604993).getAllChildren()
        if hasattr(node, 'isContainer') and not node.isContainer()
    ])

    for schema in searcher.schemas:
        published_schema = published_nodes.intersection(
            set([
                int(nid[0]) for nid in tree.db.runQuery(
                    """select distinct(id) from node where type like "%{}%" """
                    .format(schema))
            ]))
        if len(published_schema) == 0:
            search_full_ratio = 0
            search_text_ratio = 0
            search_ext_ratio = 0
            search_ext_field_ratio = 0

        else:
            search_full_ratio = len(
                published_schema.intersection(
                    set([
                        int(nid[0]) for nid in searcher.execute(
                            get_search_sql('full_indexed'), schema, 'full')
                    ]))) / len(published_schema)

            search_text_ratio = len(
                published_schema.intersection(
                    set([
                        int(nid[0]) for nid in searcher.execute(
                            get_search_sql('text_indexed'), schema, 'text')
                    ]))) / len(published_schema)

            ext_content = searcher.execute(
                get_search_sql('ext_content') % (', '.join(['id'] + [
                    'field' + db_field.position
                    for db_field in get_schema_fields(schema)
                ])), schema, 'ext')

            if not ext_content:
                ext_processed = {}
            else:
                ext_processed = {
                    node[0]: node[1:]
                    for node in ext_content if int(node[0]) in published_schema
                }

            search_ext_ratio = len(ext_processed) / len(published_schema)

            ext_field_ratios = []
            for nid in ext_processed:
                ext_field_ratios.append(
                    get_extended_field_ratio(schema, tree.getNode(nid),
                                             ext_processed[nid]))

            if len(ext_field_ratios) == 0:
                search_ext_field_ratio = 0
            else:
                search_ext_field_ratio = sum(ext_field_ratios) / len(
                    ext_field_ratios)

        schema_summary[schema] = {
            'ext': {
                'ratio': search_ext_ratio,
                'field_ratio': search_ext_field_ratio
            },
            'full': search_full_ratio,
            'text': search_text_ratio
        }

    result = all_schemas_summary()
    print '%s sec to complete' % (time.time() - t)
    print result

    try:
        mailtext = result
        mail.sendmail('*****@*****.**', MAIL_RECIPIENTS,
                      'Schema Analysis is Finished', mailtext)

    except mail.SocketError:
        logging.getLogger('backend').error(
            'failed to send Schema Analysis Results')
Exemplo n.º 16
0
def main():
    """
    This script attempts to give an overview of the completeness and correctness of the
    search databases. The report will be generated by the script and sent to the emails
    which are set in the EMAIL_RECIPIENTS variable.
    """
    t = time.time()
    published_nodes = set([int(node.id) for node in tree.getNode(604993).getAllChildren() if hasattr(node,
                                                                                                     'isContainer')
                           and not node.isContainer()])

    for schema in searcher.schemas:
        published_schema = published_nodes.intersection(set([int(nid[0]) for nid in
                                                             tree.db.runQuery(
                                                                 """select distinct(id) from node where type like "%{}%" """.format(
                                                                     schema))]))
        if len(published_schema) == 0:
            search_full_ratio = 0
            search_text_ratio = 0
            search_ext_ratio = 0
            search_ext_field_ratio = 0

        else:
            search_full_ratio = len(published_schema.intersection(
                set([int(nid[0]) for nid in searcher.execute(get_search_sql('full_indexed'),
                                                             schema,
                                                             'full')]))) / len(published_schema)

            search_text_ratio = len(published_schema.intersection(
                set([int(nid[0]) for nid in searcher.execute(get_search_sql('text_indexed'),
                                                             schema,
                                                             'text')]))) / len(published_schema)

            ext_content = searcher.execute(get_search_sql('ext_content') %
                                           (', '.join(['id'] + ['field' + db_field.position for
                                                                db_field in
                                                                get_schema_fields(schema)])),
                                           schema,
                                           'ext')

            if not ext_content:
                ext_processed = {}
            else:
                ext_processed = {node[0]: node[1:] for node in ext_content if int(node[0]) in published_schema}

            search_ext_ratio = len(ext_processed) / len(published_schema)

            ext_field_ratios = []
            for nid in ext_processed:
                ext_field_ratios.append(get_extended_field_ratio(schema, tree.getNode(nid), ext_processed[nid]))

            if len(ext_field_ratios) == 0:
                search_ext_field_ratio = 0
            else:
                search_ext_field_ratio = sum(ext_field_ratios) / len(ext_field_ratios)

        schema_summary[schema] = {'ext': {'ratio': search_ext_ratio,
                                          'field_ratio': search_ext_field_ratio},
                                  'full': search_full_ratio,
                                  'text': search_text_ratio}

    result = all_schemas_summary()
    print '%s sec to complete' % (time.time() - t)
    print result

    try:
        mailtext = result
        mail.sendmail('*****@*****.**',
                      MAIL_RECIPIENTS,
                      'Schema Analysis is Finished',
                      mailtext)

    except mail.SocketError:
        logging.getLogger('backend').error('failed to send Schema Analysis Results')
Exemplo n.º 17
0
def pwdforgotten(req):
    if len(req.params) > 3:  # user changed to browsing
        return buildURL(req)

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

    if req.params.get("action",
                      "") == "activate":  # do activation of new password
        id, key = req.params.get("key").replace("/", "").split('-')
        targetuser = users.getUser(id)

        if targetuser.get("newpassword.activation_key") == key:
            newpassword = targetuser.get("newpassword.password")

            if newpassword:
                targetuser.set("password", newpassword)
                print "password reset for user '%s' (id=%s) reset" % (
                    targetuser.getName(), targetuser.id)
                targetuser.removeAttribute("newpassword.password")
                targetuser.set("newpassword.time_activated",
                               date.format_date())
                logging.getLogger('usertracing').info(
                    "new password activated for user: %s - was requested: %s by %s"
                    % (targetuser.getName(),
                       targetuser.get("newpassword.time_requested"),
                       targetuser.get("newpassword.request_ip")))

                navframe.write(
                    req,
                    req.getTAL(theme.getTemplate("login.html"),
                               {"username": targetuser.getName()},
                               macro="pwdforgotten_password_activated"))
                return httpstatus.HTTP_OK

            else:
                print "invalid key: wrong key or already used key"
                navframe.write(
                    req,
                    req.getTAL(
                        theme.getTemplate("login.html"),
                        {"message": "pwdforgotten_password_invalid_key"},
                        macro="pwdforgotten_message"))
                return httpstatus.HTTP_OK

    elif "user" in req.params:  # create email with activation information
        username = req.params.get("user", "")

        if username == '':
            req.params['error'] = "pwdforgotten_noentry"

        else:
            targetuser = users.getUser(username)

            if not targetuser or not targetuser.canChangePWD():
                logging.getLogger('usertracing').info(
                    "new password requested for non-existing user: "******"pwdforgotten_nosuchuser"

            else:
                password = users.makeRandomPassword()
                randomkey = mkKey()

                targetuser.set("newpassword.password",
                               hashlib.md5(password).hexdigest())
                targetuser.set("newpassword.time_requested",
                               date.format_date())
                targetuser.set("newpassword.activation_key", randomkey)
                targetuser.set("newpassword.request_ip", req.ip)

                v = {}
                v["name"] = targetuser.getName()
                v["host"] = config.get("host.name")
                v["login"] = targetuser.getName()
                v["language"] = lang(req)
                v["activationlink"] = v[
                    "host"] + "/pwdforgotten?action=activate&key=%s-%s" % (
                        targetuser.id, randomkey)
                v["email"] = targetuser.getEmail()
                v["userid"] = targetuser.getName()

                # going to send the mail
                try:
                    mailtext = req.getTAL(theme.getTemplate("login.html"),
                                          v,
                                          macro="emailtext")
                    mailtext = mailtext.strip().replace(
                        "[$newpassword]",
                        password).replace("[wird eingesetzt]", password)

                    mail.sendmail(config.get("email.admin"),
                                  targetuser.getEmail(),
                                  t(lang(req), "pwdforgotten_email_subject"),
                                  mailtext)
                    logging.getLogger('usertracing').info(
                        "new password requested for user: %s - activation email sent"
                        % username)
                    navframe.write(
                        req,
                        req.getTAL(theme.getTemplate("login.html"),
                                   {"message": "pwdforgotten_butmailnowsent"},
                                   macro="pwdforgotten_message"))
                    return httpstatus.HTTP_OK

                except mail.SocketError:
                    print "Socket error while sending mail"
                    logging.getLogger('usertracing').info(
                        "new password requested for user: %s - failed to send activation email"
                        % username)
                    return req.getTAL(
                        theme.getTemplate("login.html"),
                        {"message": "pwdforgotten_emailsenderror"},
                        macro="pwdforgotten_message")

    # standard operation
    navframe.write(
        req,
        req.getTAL(theme.getTemplate("login.html"), {
            "error": req.params.get("error"),
            "user": users.getUserFromRequest(req)
        },
                   macro="pwdforgotten"))
    return httpstatus.HTTP_OK
Exemplo n.º 18
0
def getContent(req, ids):
    """
    The standard method,  which has to be implemented by every module.
    It's called in edit.py, where all the modules will be identified.
    """
    user = users.getUserFromRequest(req)
    access = acl.AccessData(req)
    node = tree.getNode(ids[0])
    access_nobody = 'nicht Jeder'

    # first prove if the user has the required rights to call this module
    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')

    if node.isContainer():
        nodes = ', '.join(node.getChildren().getIDs())
    else:
        nodes = node.get('node.id')

    v = {'msg': '',
         'urn_institutionid': config.get('urn.institutionid'),
         'urn_pubtypes': config.get('urn.pubtypes').split(';'),
         'namespaces': config.get('urn.namespace').split(';'),
         'user': user,
         'nodes': nodes,
         'type': req.params.get('id_type'),
         'show_form': True,
         'namespace': req.params.get('namespace'),
         'urn_type': req.params.get('urn_type'),
         'host': config.get('host.name'),
         'creator': users.getUser(node.get('creator'))
         }

    if user.isAdmin():
        if 'id_type' in req.params:
            if req.params.get('id_type') == 'hash':
                createHash(node)
            if req.params.get('id_type') == 'urn':
                createUrn(node, req.params.get('namespace'), req.params.get('urn_type'))
            if req.params.get('id_type') == 'doi':
                try:
                    createDOI(node)
                except:
                    return req.error(500, "doi was not successfully registered")

            if any(identifier in node.attributes for identifier in ('hash', 'urn', 'doi')):
                if not node.get('system.identifierdate'):
                    node.set('system.identifierdate', date.now())
                if node.get('system.identifierstate') != '2':
                    node.set('system.identifierstate', '2')

                    # add nobody rule if not set
                    if node.getAccess('write') is None:
                        node.setAccess('write', access_nobody)
                    else:
                        if access_nobody not in node.getAccess('write'):
                            node.setAccess('write', ','.join([node.getAccess('write'), access_nobody]))

                try:
                    mailtext = req.getTAL('web/edit/modules/identifier.html', v, macro='generate_identifier_usr_mail_2')
                    mail.sendmail(config.get('email.admin'),
                                  users.getUser(node.get('creator')).get('email'),
                                  'Vergabe eines Idektifikators / Generation of an Identifier',
                                  mailtext)

                except mail.SocketError:
                    logging.getLogger('backend').error('failed to send Autorenvertrag mail to user %s' % node.get('creator'))
                    v['msg'] = t(lang(req), 'edit_identifier_mail_fail')

        if node.get('system.identifierstate') != '2':
            v['msg'] = t(lang(req), 'edit_identifier_state_0_1_admin')
        else:
            v['msg'] = t(lang(req), 'edit_identifier_state_2_admin')

    else:
        if pathutils.isDescendantOf(node, tree.getRoot('collections')):
            if not node.get('system.identifierstate'):
                if 'id_type' in req.params:
                    try:
                        # fetch autorenvertrag
                        attachment = []
                        autorenvertrag_name = 'formular_autorenvertrag.pdf'
                        autorenvertrag_path = os.path.join(config.get('paths.tempdir'),
                                                           autorenvertrag_name)

                        if not os.path.isfile(autorenvertrag_path):
                            logging.getLogger('backend').error(
                                "Unable to attach Autorenvergrag. Attachment file not found: '%s'" % autorenvertrag_path)
                            raise IOError('Autorenvertrag was not located on disk at %s. Please send this error message to %s' %
                                          (autorenvertrag_path, config.get('email.admin')))
                        else:
                            attachment.append((autorenvertrag_path, 'Autorenvertrag.pdf'))

                        # notify user
                        mailtext_user = req.getTAL(
                            'web/edit/modules/identifier.html', v, macro='generate_identifier_usr_mail_1_' + lang(req))
                        mail.sendmail(config.get('email.admin'),
                                      user.get('email'),
                                      t(lang(req), 'edit_identifier_mail_title_usr_1'),
                                      mailtext_user,
                                      attachments_paths_and_filenames=attachment)

                        # notify admin
                        mailtext_admin = req.getTAL('web/edit/modules/identifier.html', v, macro='generate_identifier_admin_mail')
                        mail.sendmail(config.get('email.admin'),
                                      config.get('email.admin'),
                                      'Antrag auf Vergabe eines Identifikators',
                                      mailtext_admin)

                        node.set('system.identifierstate', '1')

                        # add nobody rule
                        print node.getAccess('write')
                        if node.getAccess('write') is None:
                            node.setAccess('write', access_nobody)
                        else:
                            if access_nobody not in node.getAccess('write'):
                                node.setAccess('write', ','.join([node.getAccess('write'), access_nobody]))

                    except mail.SocketError:
                        logging.getLogger('backend').error('failed to send identifier request mail')
                        v['msg'] = t(lang(req), 'edit_identifier_mail_fail')
                else:
                    v['msg'] = t(lang(req), 'edit_identifier_state_0_usr')

            if node.get('system.identifierstate') == '1':
                v['show_form'] = False
                v['msg'] = t(lang(req), 'edit_identifier_state_1_usr')
        else:
            v['show_form'] = False
            v['msg'] = t(lang(req), 'edit_identifier_state_published')

    v['hash_val'] = node.get('hash')
    v['urn_val'] = node.get('urn')
    v['doi_val'] = node.get('doi')

    # hides form if all identifier types are already set
    if all(idents != '' for idents in (v['hash_val'], v['urn_val'], v['doi_val'])):
        v['show_form'] = False
        v['msg'] = t(lang(req), 'edit_identifier_all_types_set')

    return req.getTAL('web/edit/modules/identifier.html', v, macro='set_identifier')