Example #1
0
 def __print_field(self, msg, field):
     value = msg.get(field)
     if value:
         value = mime_decode_header(value)
         value = value.decode('iso8859-1').encode('utf-8')
         return field.capitalize()+': '+value
     else:
         return ''
def mime_decode_header(header):
    """ Returns the unfolded and undecoded header
    """
    # unfold the header
    header = re.sub(r'\r?\n\s+',' ', header)

    # simple hack around some bugs in mimify.mime_decode_header
    # it checks only for =?iso-8859-1?q?, but there many variants
    # in the wild... so we normalize it here, maybe we loose something,
    # but in most cases we should get better results
    header = re.sub(r'(?i)=\?iso-8859-1[0-9]?\?[a-z]\?',
                               r'=?iso-8859-1?q?', header)
    return mimify.mime_decode_header(header)
Example #3
0
 def do_POST(self, group_name, lines, ip_address, username=''):
     forum_id = self.get_forum(group_name)
     prefix = settings.phpbb_table_prefix
     nuke_prefix = settings.nuke_table_prefix
     # patch by Andreas Wegmann <*****@*****.**> to fix the handling of unusual encodings of messages
     lines = mime_decode_header(
         re.sub(q_quote_multiline, "=?\\1?Q?\\2\\3?=", lines))
     body = self.get_message_body(lines)
     author, email = from_regexp.search(lines, 0).groups()
     subject = subject_regexp.search(lines, 0).groups()[0].strip()
     # get the authentication information now
     if username != '':
         stmt = """
                 SELECT
                     user_id
                 FROM
                     %susers
                 WHERE
                     username='******'""" % (nuke_prefix, username)
         num_rows = self.cursor.execute(stmt)
         if num_rows == 0:
             poster_id = -1
         else:
             poster_id = self.cursor.fetchone()[0]
         post_username = ''
     else:
         poster_id = -1
         post_username = author
     if lines.find('References') != -1:
         # get the 'modifystamp' value from the parent (if any)
         references = references_regexp.search(lines, 0).groups()
         parent_id, void = references[-1].strip().split('@')
         stmt = """
                 SELECT
                     topic_id
                 FROM
                     %sposts
                 WHERE
                     post_id=%s
                 GROUP BY
                     post_id""" % (prefix, parent_id)
         num_rows = self.cursor.execute(stmt)
         if num_rows == 0:
             return None
         thread_id = self.cursor.fetchone()[0]
     else:
         # create a new topic
         stmt = """
                 INSERT INTO
                     %stopics
                 (
                     forum_id,
                     topic_title,
                     topic_poster,
                     topic_time,
                     topic_status,
                     topic_vote,
                     topic_type
                 ) VALUES (
                     %s,
                     '%s',
                     %s,
                     UNIX_TIMESTAMP(),
                     0,
                     0,
                     0
                 )""" % (prefix, forum_id, self.quote_string(subject),
                         poster_id)
         self.cursor.execute(stmt)
         thread_id = self.cursor.insert_id()
     stmt = """
             INSERT INTO
                 %sposts
             (
                 topic_id,
                 forum_id,
                 poster_id,
                 post_time,
                 poster_ip,
                 post_username,
                 enable_bbcode,
                 enable_html,
                 enable_smilies,
                 enable_sig
             ) VALUES (
                 %s,
                 %s,
                 %s,
                 UNIX_TIMESTAMP(),
                 '%s',
                 '%s',
                 1,
                 0,
                 1,
                 0
             )""" % (prefix, thread_id, forum_id, poster_id,
                     self.encode_ip(ip_address), post_username)
     self.cursor.execute(stmt)
     new_id = self.cursor.insert_id()
     if not new_id:
         return None
     else:
         # insert into the '*posts_text' table
         stmt = """
                 INSERT INTO
                     %sposts_text
                 (
                     post_id,
                     bbcode_uid,
                     post_subject,
                     post_text
                 ) VALUES (
                     %s,
                     '%s',
                     '%s',
                     '%s'
                 )""" % (prefix, new_id, self.make_bbcode_uid(),
                         self.quote_string(subject),
                         self.quote_string(body))
         if not self.cursor.execute(stmt):
             # delete from 'topics' and 'posts' tables before returning...
             stmt = """
                     DELETE FROM
                         %stopics
                     WHERE
                         topic_id=%s""" % (prefix, thread_id)
             self.cursor.execute(stmt)
             stmt = """
                     DELETE FROM
                         %sposts
                     WHERE
                         post_id=%s""" % (prefix, new_id)
             self.cursor.execute(stmt)
             return None
         else:
             if lines.find('References') != -1:
                 # update the total number of posts in the forum
                 stmt = """
                         UPDATE
                             %sforums
                         SET
                             forum_posts=forum_posts+1,
                             forum_last_post_id=%s
                         WHERE
                             forum_id=%s
                         """ % (settings.phpbb_table_prefix, new_id,
                                forum_id)
                 self.cursor.execute(stmt)
             else:
                 # update the total number of topics and posts in the forum
                 stmt = """
                         UPDATE
                             %sforums
                         SET
                             forum_topics=forum_topics+1,
                             forum_posts=forum_posts+1,
                             forum_last_post_id=%s
                         WHERE
                             forum_id=%s
                         """ % (settings.phpbb_table_prefix, new_id,
                                forum_id)
                 self.cursor.execute(stmt)
             # update the user's post count, if this is indeed a real user
             if poster_id != -1:
                 stmt = """
                         UPDATE
                             %susers
                         SET
                             user_posts=user_posts+1
                         WHERE
                             user_id=%s""" % (nuke_prefix, poster_id)
                 self.cursor.execute(stmt)
             # setup last post on the topic thread (Patricio Anguita <*****@*****.**>)
             stmt = """
                     UPDATE
                         %stopics
                     SET
                         topic_replies=topic_replies+1,
                         topic_last_post_id=%s
                     WHERE
                         topic_id=%s""" % (prefix, new_id, thread_id)
             self.cursor.execute(stmt)
             # if this is the first post on the thread.. (Patricio Anguita <*****@*****.**>)
             if lines.find('References') == -1:
                 stmt = """
                         UPDATE
                             %stopics
                         SET
                             topic_first_post_id=%s
                         WHERE
                             topic_id=%s AND
                             topic_first_post_id=0""" % (prefix, new_id,
                                                         thread_id)
                 self.cursor.execute(stmt)
             return 1
Example #4
0
 def do_POST(self, group_name, lines, ip_address, username=''):
     table_name = self.get_table_name(group_name)
     body = self.get_message_body(lines)
     author, email = from_regexp.search(lines, 0).groups()
     subject = subject_regexp.search(lines, 0).groups()[0].strip()
     # patch by Andreas Wegmann <*****@*****.**> to fix the handling of unusual encodings of messages
     lines = mime_decode_header(re.sub(q_quote_multiline, "=?\\1?Q?\\2\\3?=", lines))
     if lines.find('References') != -1:
         # get the 'modifystamp' value from the parent (if any)
         references = references_regexp.search(lines, 0).groups()
         parent_id, void = references[-1].strip().split('@')
         stmt = """
                 SELECT
                     IF(MAX(id) IS NULL, 1, MAX(id)+1) AS next_id
                 FROM
                     %s""" % (table_name)
         num_rows = self.cursor.execute(stmt)
         if num_rows == 0:
             new_id = 1
         else:
             new_id = self.cursor.fetchone()[0]
         stmt = """
                 SELECT
                     id,
                     thread,
                     modifystamp
                 FROM
                     %s
                 WHERE
                     approved='Y' AND
                     id=%s
                 GROUP BY
                     id""" % (table_name, parent_id)
         num_rows = self.cursor.execute(stmt)
         if num_rows == 0:
             return None
         parent_id, thread_id, modifystamp = self.cursor.fetchone()
     else:
         stmt = """
                 SELECT
                     IF(MAX(id) IS NULL, 1, MAX(id)+1) AS next_id,
                     UNIX_TIMESTAMP()
                 FROM
                     %s""" % (table_name)
         self.cursor.execute(stmt)
         new_id, modifystamp = self.cursor.fetchone()
         parent_id = 0
         thread_id = new_id
     stmt = """
             INSERT INTO
                 %s
             (
                 id,
                 datestamp,
                 thread,
                 parent,
                 author,
                 subject,
                 email,
                 host,
                 email_reply,
                 approved,
                 msgid,
                 modifystamp,
                 userid
             ) VALUES (
                 %s,
                 NOW(),
                 %s,
                 %s,
                 '%s',
                 '%s',
                 '%s',
                 '%s',
                 'N',
                 'Y',
                 '',
                 %s,
                 0
             )
             """ % (table_name, new_id, thread_id, parent_id, self.quote_string(author.strip()), self.quote_string(subject), self.quote_string(email), ip_address, modifystamp)
     if not self.cursor.execute(stmt):
         return None
     else:
         # insert into the '*_bodies' table
         stmt = """
                 INSERT INTO
                     %s_bodies
                 (
                     id,
                     body,
                     thread
                 ) VALUES (
                     %s,
                     '%s',
                     %s
                 )""" % (table_name, new_id, self.quote_string(body), thread_id)
         if not self.cursor.execute(stmt):
             # delete from 'table_name' before returning..
             stmt = """
                     DELETE FROM
                         %s
                     WHERE
                         id=%s""" % (table_name, new_id)
             self.cursor.execute(stmt)
             return None
         else:
             # alert forum moderators
             self.send_notifications(group_name, new_id, thread_id, parent_id, author.strip(), email, subject, body)
             return 1
Example #5
0
 def do_POST(self, group_name, lines, ip_address, username=''):
     forum_id = self.get_forum(group_name)
     prefix = settings.phpbb_table_prefix
     # patch by Andreas Wegmann <*****@*****.**> to fix the handling of unusual encodings of messages
     lines = mime_decode_header(re.sub(q_quote_multiline, "=?\\1?Q?\\2\\3?=", lines))
     body = self.get_message_body(lines)
     author, email = from_regexp.search(lines, 0).groups()
     subject = subject_regexp.search(lines, 0).groups()[0].strip()
     # get the authentication information now
     if username != '':
         stmt = """
                 SELECT
                     user_id
                 FROM
                     %susers
                 WHERE
                     username='******'""" % (prefix, username)
         num_rows = self.cursor.execute(stmt)
         if num_rows == 0:
             poster_id = -1
         else:
             poster_id = self.cursor.fetchone()[0]
         post_username = ''
     else:
         poster_id = -1
         post_username = author
     if lines.find('References') != -1:
         # get the 'modifystamp' value from the parent (if any)
         references = references_regexp.search(lines, 0).groups()
         parent_id, void = references[-1].strip().split('@')
         stmt = """
                 SELECT
                     topic_id
                 FROM
                     %sposts
                 WHERE
                     post_id=%s
                 GROUP BY
                     post_id""" % (prefix, parent_id)
         num_rows = self.cursor.execute(stmt)
         if num_rows == 0:
             return None
         thread_id = self.cursor.fetchone()[0]
     else:
         # create a new topic
         stmt = """
                 INSERT INTO
                     %stopics
                 (
                     forum_id,
                     topic_title,
                     topic_poster,
                     topic_time,
                     topic_status,
                     topic_vote,
                     topic_type
                 ) VALUES (
                     %s,
                     '%s',
                     %s,
                     UNIX_TIMESTAMP(),
                     0,
                     0,
                     0
                 )""" % (prefix, forum_id, self.quote_string(subject), poster_id)
         self.cursor.execute(stmt)
         thread_id = self.cursor.insert_id()
     stmt = """
             INSERT INTO
                 %sposts
             (
                 topic_id,
                 forum_id,
                 poster_id,
                 post_time,
                 poster_ip,
                 post_username,
                 enable_bbcode,
                 enable_html,
                 enable_smilies,
                 enable_sig
             ) VALUES (
                 %s,
                 %s,
                 %s,
                 UNIX_TIMESTAMP(),
                 '%s',
                 '%s',
                 1,
                 0,
                 1,
                 0
             )""" % (prefix, thread_id, forum_id, poster_id, self.encode_ip(ip_address), post_username)
     self.cursor.execute(stmt)
     new_id = self.cursor.insert_id()
     if not new_id:
         return None
     else:
         # insert into the '*posts_text' table
         stmt = """
                 INSERT INTO
                     %sposts_text
                 (
                     post_id,
                     bbcode_uid,
                     post_subject,
                     post_text
                 ) VALUES (
                     %s,
                     '%s',
                     '%s',
                     '%s'
                 )""" % (prefix, new_id, self.make_bbcode_uid(), self.quote_string(subject), self.quote_string(body))
         if not self.cursor.execute(stmt):
             # delete from 'topics' and 'posts' tables before returning...
             stmt = """
                     DELETE FROM
                         %stopics
                     WHERE
                         topic_id=%s""" % (prefix, thread_id)
             self.cursor.execute(stmt)
             stmt = """
                     DELETE FROM
                         %sposts
                     WHERE
                         post_id=%s""" % (prefix, new_id)
             self.cursor.execute(stmt)
             return None
         else:
             if lines.find('References') != -1:
                 # update the total number of posts in the forum
                 stmt = """
                         UPDATE
                             %sforums
                         SET
                             forum_posts=forum_posts+1,
                             forum_last_post_id=%s
                         WHERE
                             forum_id=%s
                         """ % (settings.phpbb_table_prefix, new_id, forum_id)
                 self.cursor.execute(stmt)
             else:
                 # update the total number of topics and posts in the forum
                 stmt = """
                         UPDATE
                             %sforums
                         SET
                             forum_topics=forum_topics+1,
                             forum_posts=forum_posts+1,
                             forum_last_post_id=%s
                         WHERE
                             forum_id=%s
                         """ % (settings.phpbb_table_prefix, new_id, forum_id)
                 self.cursor.execute(stmt)
             # update the user's post count, if this is indeed a real user
             if poster_id != -1:
                 stmt = """
                         UPDATE
                             %susers
                         SET
                             user_posts=user_posts+1
                         WHERE
                             user_id=%s""" % (prefix, poster_id)
                 self.cursor.execute(stmt)
             # setup last post on the topic thread (Patricio Anguita <*****@*****.**>)
             stmt = """
                     UPDATE
                         %stopics
                     SET
                         topic_replies=topic_replies+1,
                         topic_last_post_id=%s
                     WHERE
                         topic_id=%s""" % (prefix, new_id, thread_id)
             self.cursor.execute(stmt)
             # if this is the first post on the thread.. (Patricio Anguita <*****@*****.**>)
             if lines.find('References') == -1:
                 stmt = """
                         UPDATE
                             %stopics
                         SET
                             topic_first_post_id=%s
                         WHERE
                             topic_id=%s AND
                             topic_first_post_id=0""" % (prefix, new_id, thread_id)
                 self.cursor.execute(stmt)
             return 1
Example #6
0
File: mbot.py Project: nah-ko/MBot
def main():
	""" Here we do the job """
	global RELEASE, MBOT_ADDRESS, CONFIG_FILE, LOG_LEVEL, log

	from optparse import OptionParser

	# Define usage and give command line options to parser object
	Usage  = "usage: %prog [options]"
	Ver    = "%prog " + RELEASE
	Parser = OptionParser(usage = Usage, version = Ver)
	Parser.add_option("-c", "--configfile", action="store", type="string",
	                  dest="ConfFile", metavar="FILE",
			  default=CONFIG_FILE,
			  help="Configuration file location")
	(options, args) = Parser.parse_args()
	confErrMsg      = ""

	if os.path.exists(options.ConfFile):
	    config_file = options.ConfFile
	else:
	    confErrMsg  = "Sorry, %s file doesn't exists using " \
	                  "default one instead" % options.ConfFile
	    config_file = CONFIG_FILE

	Conf = read_defaults(config_file)
	log  = Logger.Logger(LOG_LEVEL)
	
	if confErrMsg != "":
	    log.err(confErrMsg)
	log.notice("Using config file %s\n" % config_file)
	log.debug("Configuration values: MBOT_ADDRESS='%s'" \
		      % MBOT_ADDRESS + \
		      "LOG_LEVEL='%s'" \
		      % LOG_LEVEL)

	# we read the mail
	mesg = read_email()

	sender  = mesg.get('From')
	subject = mime_decode_header(mesg.get('Subject'))
	mesg_id = mesg.get('Message-Id')
	date    = time.strftime('%Y-%m-%d %H:%M:%S',
				rfc822.parsedate(mesg.get('Date')))
	dest    = mesg.get('To')
	
	log.notice("Incoming mail: the %s, from '%s' [%s] to '%s' " \
		   % (date, sender, mesg_id, dest) + \
		   "with subject '%s'" % subject)

	log.notice("message: %s %s %s \n" % (mesg_id, sender, subject))

	# we prepare the response
	resp = MIMEMultipart()
	resp['Subject']     = 'Re: %s' % subject
	resp['To']          = sender
	resp['In-Reply-To'] = mesg_id
	resp['Date']        = formatdate(time.mktime(time.localtime()), True)
	resp['From']        = dest

	# we initialize a handler corresponding to the given subject
	# first we create a dict hs which associate handler with subject
	# hs = {subject: [section, handler], ...}
	hs = {}
	for section in SECTIONS:
		log.debug("section: %s" % section)
		subjects = section.split(',')
		handler  = Conf.get(section, 'handler')
		log.debug("subjects: %s for handler: %s" % (subjects,
                                                            handler))
		for s in subjects:
			hs[s] = [section, handler]
			log.debug("subject: %s" % s)
	log.debug("Modules by subject: %s" % hs)

	# now we can try to import appropriate module and use it
	h = None
	for s in hs:
		if subject.find(s) == 0:
			section = hs[s][0]
			handler = hs[s][1]
			log.debug("using handler: %s" % handler)
			try:
				handlerModule = __import__(handler)
				log.notice("Using handler: %s" % handler)

				handlerClass = getattr(handlerModule, handler)
				log.debug("handlerClass: %s" % handlerClass)

				h = handlerClass(section, log,
						 subject[len(s):],
						 dest, sender, date,
						 mesg.is_multipart())
				
				log.debug("Instanciate handler %s for '%s'" \
					  % (handler, subject[len(s):]))
			except:
				log.err("Impossible to load handler: %s" \
					  % handler)
				log.err("%s: %s" \
					  % (sys.exc_type, sys.exc_value))
			break

	# If we have no handler, we send an error mail
	if h is None:
		log.err("No handler found for '%s'" % subject)
		mesg = "Sorry, mbot is not configured to handle your request"
		resp.attach(MIMEText(mesg))

	# Check if user is authorized to use mbot handler
	elif not h.check_lists(Conf):
		log.err("%s is not allowed to use mbot handler '%s'" \
			% (sender, handler))
		mesg = "Sorry, mbot is not allowed to handle your request"
		resp.attach(MIMEText(mesg))

	# Here we apply the found handler
	else:
		# then we read the handler config
		h.read_conf(Conf)

		if mesg.is_multipart():
			# Give each part of message to handler
			for part in mesg.walk():
				# Consider all responses we may have
				for response in h.handle(part):
					attach(resp, response)
				
		else:
			# Call handle just once with message payload
			for response in h.handle(mesg):
				attach(resp, response)

	# Then we send the mail
	log.notice("Sending from %s to  %s \n" % (MBOT_ADDRESS, sender))
	s = smtplib.SMTP()
	s.connect()
	s.sendmail(MBOT_ADDRESS, sender, resp.as_string())
	s.close()
ca_names = opensslcnf.sectionkeys.get('ca', [])
MailRelay = pyca_section.get('MailRelay', 'localhost')
caCertReqMailAdr = pyca_section.get('caCertReqMailAdr', '')
caInternalCertTypes = pyca_section.get('caInternalCertTypes', [])
caInternalDomains = pyca_section.get('caInternalDomains', '')
if type(caInternalDomains) != type([]):
    caInternalDomains = [caInternalDomains]

m = rfc822.Message(sys.stdin)

if len(m["subject"]) > 80:
    LogWrite(logfile, 'Error', m, 'Subject too long.')
    sys.exit(0)

if m.has_key('from'):
    from_addr = mime_decode_header(string.strip(m["from"]))
    from_name, from_mail = rfc822.AddressList(from_addr).addresslist[0]
else:
    from_mail = ''

subject = string.strip(m["subject"])
subjectstart = string.find(subject, 'cert-req-')

try:
    prefix, ca_name, caChallengeId = string.split(
        subject[subjectstart:len(subject)], '.', 2)
except ValueError:
    LogWrite(logfile, 'Error', m, 'Subject has wrong format.')
    sys.exit(0)

if prefix == 'cert-req-SPKAC':
Example #8
0
def process_mailbox(M):
    """
    Do something with emails messages in the folder.
    For the sake of this example, print some headers.
    """

    rv, data = M.search(None, "ALL")
    if rv != 'OK':
        print("No messages found!")
        return

    msg_ids = ','.join(data[0].split(' '))
    emaildata = list()
    for num in data[0].split():
        rv, data = M.fetch(num, '(RFC822)')
        if rv != 'OK':
            print("ERROR getting message"), num
            return

        default_charset = 'latin1'
        # Get data from OJ! email
        outermsg = data[0][1]
        outmsg = ''.join(outermsg)
        outermsg = decode_email_s(outmsg)
        outermessageid = str(
            outermsg["header"]["header"]["message-id"][0]).translate(
                None, ",<,>")
        outerdate = str(outermsg["header"]["header"]["date"][0])
        outerFromFix = str(outermsg['header']['header']['from'][0]).replace(
            '"', '').translate(None, ",<,>")
        outerFrom = mimify.mime_decode_header(outerFromFix).decode("latin1")
        outemailTo = str(outermsg["header"]["header"]["to"][0]).replace(
            "*****@*****.**", '')
        outfixTo = str(outemailTo).replace('"', '').translate(None, "<,>")
        outerTo = ' '.join(outfixTo.split())
        outersubjectFix = str(outermsg["header"]["header"]["subject"][0])
        outersubject = mimify.mime_decode_header(outersubjectFix).decode(
            "latin1")

        # Get data from OJ! email attachment
        inneremail = email.message_from_string(data[0][1])
        attachments = get_mail_contents(inneremail)
        #print attachments[5]
        for attach in attachments:
            # dont forget to be careful to sanitize 'filename' and be carefull
            # for filename collision, to before to save :
            #print '\tfilename=%r is_body=%s type=%s charset=%s desc=%s size=%d' % (attach.filename, attach.is_body, attach.type, attach.charset, attach.description, 0 if attach.payload==None else len(attach.payload))
            if attach.type == ('message/rfc822'):
                innmsg = attach.payload

                position = re.search("Received: from", innmsg)
                position2 = re.search("From:", innmsg)
                if position:
                    position2 = re.search("From:", innmsg)
                    index = position.start(0)
                    innmsg = innmsg[index:]
                    innermsg = decode_email_s(innmsg)
                    metadata = ' '.join(
                        map(str, innermsg["header"]["header"]["received"]))

                else:
                    if position2:
                        index = position2.start(0)
                        innmsg = innmsg[index:]
                        metadata = None
                        innermsg = decode_email_s(innmsg)

                bodyfix = str(innermsg["body"]).translate(
                    None, ",<,>,[,],{,},'")
                body = bodyfix.replace("\\r", "").replace("\\n", " ")

                emaildatas = {
                    'outermessageid': outermessageid,
                    'outerdate': outerdate,
                    'outerFrom': outerFrom,
                    'outerTo': outerTo,
                    'outersubject': outersubject,
                    'metadata': metadata,
                    'body': body,
                }

                check_list = str(innermsg["header"]).encode("utf-8")
                header_list = innermsg["header"]["header"]

                data_mapinner = {
                    'received_domain': "received_domain",
                    'received_ip': "received_ip",
                    'received_foremail': "received_foremail",
                    'received_email': "received_email",
                }

                for each_elem in check_list:
                    if each_elem not in [
                            "received_domain", "received_ip",
                            "received_foremail", "received_email"
                    ]:
                        data_mapinner[each_elem.replace("-", "")] = each_elem

                for each_elem in data_mapinner:
                    if innermsg["header"].has_key(data_mapinner[each_elem]):
                        emaildatas[each_elem] = ', '.join(
                            innermsg["header"][data_mapinner[each_elem]])
                emaildata.append(emaildatas)

                data_map = {
                    'innermessageid': "message-id",
                    'innerdate': "date",
                    'innerFrom': "from",
                    'innerTo': "to",
                    'innersubject': "subject",
                }

                for each_elem in header_list:
                    if each_elem not in [
                            "subject", "to", "from", "date", "message-id",
                            "received"
                    ]:
                        data_map[each_elem.replace("-", "")] = each_elem

                for each_elem in data_map:
                    if innermsg["header"]["header"].has_key(
                            data_map[each_elem]):
                        emaildatas[each_elem] = ', '.join([
                            unicode(t[0], t[1] or default_charset)
                            for t in decode_header(
                                str(innermsg["header"]["header"][
                                    data_map[each_elem]][0]).replace(
                                        '"', '').translate(None, ",<,>,[,]"))
                        ])
                emaildata.append(emaildatas)

                mongoData = emaildatas
                mongoDb.insert(mongoData)

    if emaildata:
        print dumps(emaildata)
    # Move processed email to Inbox.Processed
    if msg_ids:
        if moveEmailsOnComplete:
            result, copy = M.copy(msg_ids, 'Inbox.Processed')
            if result == 'OK':
                M.store(msg_ids, '+FLAGS', '\\Deleted')
                M.expunge()
        pass
    else:
        print("No emails available")
Example #9
0
    def do_POST(self, group_name, lines, ip_address, username=''):
        forum_id = self.get_forum(group_name)
        prefix = settings.phpbb_table_prefix
        # patch by Andreas Wegmann <*****@*****.**> to fix the handling of unusual encodings of messages
        lines = mime_decode_header(
            re.sub(q_quote_multiline, "=?\\1?Q?\\2\\3?=", lines))
        body = self.get_message_body(lines)
        author, email = from_regexp.search(lines, 0).groups()
        subject = subject_regexp.search(lines, 0).groups()[0].strip()
        # get the authentication information now
        if username != '':
            stmt = """
                    SELECT
                        user_id
                    FROM
                        %susers
                    WHERE
                        username_clean='%s'""" % (
                prefix, self.quote_string(username.lower().strip()))
            num_rows = self.query(stmt)
            if num_rows == 0:
                poster_id = 0
                post_username = username
            else:
                poster_id = self.cursor.fetchone()[0]
                # use name and email provided by news client
                if email != '':
                    post_username = "******" % (author, email)
                else:
                    post_username = author
                # post_username = ''
        else:
            poster_id = 0
            if email != '':
                post_username = "******" % (author, email)
            else:
                post_username = author

        # check if user can post
        if self.ip_allowed(ip_address) == 0:
            return 2

        if self.check_permission(forum_id, poster_id, 'f_post') == 0:
            return 2

        postercolor = self.get_poster_color(poster_id)

        replying = lines.find('References') != -1

        if replying:
            # get the 'modifystamp' value from the parent (if any)
            references = references_regexp.search(lines, 0).groups()
            parent_id, void = references[-1].strip().split('@')
            stmt = """
                    SELECT
                        topic_id
                    FROM
                        %sposts
                    WHERE
                        post_id=%s
                    GROUP BY
                        post_id""" % (prefix, self.quote_string(parent_id))
            num_rows = self.query(stmt)
            if num_rows == 0:
                return None
            thread_id = self.cursor.fetchone()[0]

            # check if topic locked
            stmt = """
                    SELECT topic_status
                    FROM %stopics
                    WHERE topic_id=%s AND topic_status=0
                   """ % (prefix, thread_id)
            if self.query(stmt) == 0:
                # create new topic instead
                replying = 0

        if not replying:
            # create a new topic
            stmt = """
                    INSERT INTO
                        %stopics
                    (
                        forum_id,
                        topic_title,
                        topic_poster,
                        topic_time,
                        topic_status,
                        topic_type
                    ) VALUES (
                        %s,
                        '%s',
                        %s,
                        UNIX_TIMESTAMP(),
                        0,
                        0
                    )""" % (prefix, forum_id, self.quote_string(subject),
                            poster_id)
            self.query(stmt)
            thread_id = self.cursor.lastrowid

        stmt = """
                INSERT INTO
                    %sposts
                (
                    topic_id,
                    forum_id,
                    poster_id,
                    post_time,
                    poster_ip,
                    post_username,
                    post_subject,
                    post_text,
                    enable_magic_url,
                    enable_sig,
                    bbcode_uid
                ) VALUES (
                    %s,
                    %s,
                    %s,
                    UNIX_TIMESTAMP(),
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    0,
                    0,
                    '%s'
                )""" % (prefix, thread_id, forum_id, poster_id, ip_address,
                        self.quote_string(post_username),
                        self.quote_string(subject), self.quote_string(body),
                        self.make_bbcode_uid())
        self.query(stmt)
        new_id = self.cursor.lastrowid
        if not new_id:
            if not replying:
                # delete from 'topics' and 'posts' tables before returning...
                stmt = """
                        DELETE FROM
                            %stopics
                        WHERE
                            topic_id=%s""" % (prefix, thread_id)
                self.query(stmt)
            return None
        else:
            if replying:
                # update the total number of posts in the forum
                stmt = """
                        UPDATE
                            %sforums
                        SET
                            forum_posts=forum_posts+1,
                            forum_last_post_id=%s,
                            forum_last_poster_id=%s,
                            forum_last_post_subject='%s',
                            forum_last_post_time=UNIX_TIMESTAMP(),
                            forum_last_poster_name='%s',
                            forum_last_poster_colour='%s'
                        WHERE
                            forum_id=%s
                        """ % (
                    prefix, new_id, poster_id, self.quote_string(subject),
                    self.quote_string(post_username), postercolor, forum_id)
                self.query(stmt)
            else:
                # create the topics posted record
                stmt = """
                        INSERT INTO
                            %stopics_posted
                       (
                            user_id,
                            topic_id,
                            topic_posted
                       ) VALUES (
                            %s,
                            %s,
                            1
                       )""" % (prefix, poster_id, thread_id)
                self.query(stmt)

                # update the total number of topics and posts in the forum
                stmt = """
                        UPDATE
                            %sforums
                        SET
                            forum_topics=forum_topics+1,
                            forum_topics_real=forum_topics_real+1,
                            forum_posts=forum_posts+1,
                            forum_last_post_id=%s,
                            forum_last_poster_id=%s,
                            forum_last_post_subject='%s',
                            forum_last_post_time=UNIX_TIMESTAMP(),
                            forum_last_poster_name='%s',
                            forum_last_poster_colour='%s'
                        WHERE
                            forum_id=%s
                        """ % (
                    prefix, new_id, poster_id, self.quote_string(subject),
                    self.quote_string(post_username), postercolor, forum_id)
                self.query(stmt)
            # update the user's post count, if this is indeed a real user
            if poster_id != -1:
                stmt = """
                        UPDATE
                            %susers
                        SET
                            user_posts=user_posts+1,
                            user_lastpost_time=UNIX_TIMESTAMP()
                        WHERE
                            user_id=%s""" % (prefix, poster_id)
                self.query(stmt)
            # setup last post on the topic thread (Patricio Anguita <*****@*****.**>)
            if replying:
                incval = '1'
            else:
                incval = '0'

            stmt = """
                    UPDATE
                        %stopics
                    SET
                        topic_replies=topic_replies+%s,
                        topic_replies_real=topic_replies_real+%s,
                        topic_last_post_id=%s,
                        topic_last_poster_id=%s,
                        topic_last_poster_name='%s',
                        topic_last_poster_colour='%s',
                        topic_last_post_subject='%s',
                        topic_last_post_time=UNIX_TIMESTAMP()
                    WHERE
                        topic_id=%s""" % (
                prefix, incval, incval, new_id, poster_id,
                self.quote_string(post_username), postercolor,
                self.quote_string(subject), thread_id)
            self.query(stmt)
            # if this is the first post on the thread.. (Patricio Anguita <*****@*****.**>)
            if not replying:
                stmt = """
                        UPDATE
                            %stopics
                        SET
                            topic_first_post_id=%s,
                            topic_first_poster_name='%s',
                            topic_first_poster_colour='%s'
                        WHERE
                            topic_id=%s AND
                            topic_first_post_id=0""" % (
                    prefix, new_id, self.quote_string(post_username),
                    postercolor, thread_id)
                self.query(stmt)
            return 1
ca_names = opensslcnf.sectionkeys.get('ca',[])
MailRelay           = pyca_section.get('MailRelay','localhost')
caCertReqMailAdr    = pyca_section.get('caCertReqMailAdr','')
caInternalCertTypes = pyca_section.get('caInternalCertTypes',[])
caInternalDomains   = pyca_section.get('caInternalDomains','')
if type(caInternalDomains)!=type([]):
  caInternalDomains = [caInternalDomains]

m=rfc822.Message(sys.stdin)

if len(m["subject"])>80:
  LogWrite(logfile,'Error',m,'Subject too long.')
  sys.exit(0)

if m.has_key('from'):
  from_addr = mime_decode_header(string.strip(m["from"]))
  from_name, from_mail = rfc822.AddressList(from_addr).addresslist[0]
else:
  from_mail = ''

subject = string.strip(m["subject"])
subjectstart = string.find(subject,'cert-req-')

try:
  prefix,ca_name,caChallengeId = string.split(subject[subjectstart:len(subject)],'.',2)
except ValueError:
  LogWrite(logfile,'Error',m,'Subject has wrong format.')
  sys.exit(0)

if prefix=='cert-req-SPKAC':
  request_filenamesuffix = 'spkac'
Example #11
0
    def do_POST(self, group_name, lines, ip_address, username=''):
        forum_id = self.get_forum(group_name)
        prefix = settings.phpbb_table_prefix
        # patch by Andreas Wegmann <*****@*****.**> to fix the handling of unusual encodings of messages
        lines = mime_decode_header(re.sub(q_quote_multiline, "=?\\1?Q?\\2\\3?=", lines))
        body = self.get_message_body(lines)
        author, email = from_regexp.search(lines, 0).groups()
        subject = subject_regexp.search(lines, 0).groups()[0].strip()
        # get the authentication information now
        if username != '':
            stmt = """
                    SELECT
                        user_id
                    FROM
                        %susers
                    WHERE
                        username_clean='%s'""" % (prefix, self.quote_string(username.lower().strip()))
            num_rows = self.query(stmt)
            if num_rows == 0:
                poster_id = 0
                post_username = username
            else:
                poster_id = self.cursor.fetchone()[0]
                # use name and email provided by news client
                if email!='':
                  post_username = "******" % (author, email)
                else:
                  post_username = author
                # post_username = ''
        else:
            poster_id = 0
            if email!='':
              post_username = "******" % (author, email)
            else:
              post_username = author

        # check if user can post
        if self.ip_allowed(ip_address)==0:
            return 2

        if self.check_permission(forum_id, poster_id, 'f_post')==0:
            return 2

        postercolor=self.get_poster_color(poster_id)

        replying=lines.find('References') != -1

        if replying:
            # get the 'modifystamp' value from the parent (if any)
            references = references_regexp.search(lines, 0).groups()
            parent_id, void = references[-1].strip().split('@')
            stmt = """
                    SELECT
                        topic_id
                    FROM
                        %sposts
                    WHERE
                        post_id=%s
                    GROUP BY
                        post_id""" % (prefix, self.quote_string(parent_id))
            num_rows = self.query(stmt)
            if num_rows == 0:
                return None
            thread_id = self.cursor.fetchone()[0]

            # check if topic locked
            stmt = """
                    SELECT topic_status
                    FROM %stopics
                    WHERE topic_id=%s AND topic_status=0
                   """ % (prefix, thread_id)
            if self.query(stmt) == 0:
                # create new topic instead
                replying=0

        if not replying:
            # create a new topic
            stmt = """
                    INSERT INTO
                        %stopics
                    (
                        forum_id,
                        topic_title,
                        topic_poster,
                        topic_time,
                        topic_status,
                        topic_type
                    ) VALUES (
                        %s,
                        '%s',
                        %s,
                        UNIX_TIMESTAMP(),
                        0,
                        0
                    )""" % (prefix, forum_id, self.quote_string(subject), poster_id)
            self.query(stmt)
            thread_id = self.cursor.lastrowid

        stmt = """
                INSERT INTO
                    %sposts
                (
                    topic_id,
                    forum_id,
                    poster_id,
                    post_time,
                    poster_ip,
                    post_username,
                    post_subject,
                    post_text,
                    enable_magic_url,
                    enable_sig,
                    bbcode_uid
                ) VALUES (
                    %s,
                    %s,
                    %s,
                    UNIX_TIMESTAMP(),
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    0,
                    0,
                    '%s'
                )""" % (prefix, thread_id, forum_id, poster_id, ip_address, self.quote_string(post_username), self.quote_string(subject),self.quote_string(body), self.make_bbcode_uid())
        self.query(stmt)
        new_id = self.cursor.lastrowid
        if not new_id:
            if not replying:
                # delete from 'topics' and 'posts' tables before returning...
                stmt = """
                        DELETE FROM
                            %stopics
                        WHERE
                            topic_id=%s""" % (prefix, thread_id)
                self.query(stmt)
            return None
        else:
            if replying:
                # update the total number of posts in the forum
                stmt = """
                        UPDATE
                            %sforums
                        SET
                            forum_posts=forum_posts+1,
                            forum_last_post_id=%s,
                            forum_last_poster_id=%s,
                            forum_last_post_subject='%s',
                            forum_last_post_time=UNIX_TIMESTAMP(),
                            forum_last_poster_name='%s',
                            forum_last_poster_colour='%s'
                        WHERE
                            forum_id=%s
                        """ % (prefix, new_id, poster_id, self.quote_string(subject), self.quote_string(post_username), postercolor, forum_id)
                self.query(stmt)
            else:
                # create the topics posted record
                stmt = """
                        INSERT INTO
                            %stopics_posted
                       (
                            user_id,
                            topic_id,
                            topic_posted
                       ) VALUES (
                            %s,
                            %s,
                            1
                       )""" % (prefix, poster_id, thread_id)
                self.query(stmt)


                # update the total number of topics and posts in the forum
                stmt = """
                        UPDATE
                            %sforums
                        SET
                            forum_topics=forum_topics+1,
                            forum_topics_real=forum_topics_real+1,
                            forum_posts=forum_posts+1,
                            forum_last_post_id=%s,
                            forum_last_poster_id=%s,
                            forum_last_post_subject='%s',
                            forum_last_post_time=UNIX_TIMESTAMP(),
                            forum_last_poster_name='%s',
                            forum_last_poster_colour='%s'
                        WHERE
                            forum_id=%s
                        """ % (prefix, new_id, poster_id, self.quote_string(subject), self.quote_string(post_username), postercolor, forum_id)
                self.query(stmt)
            # update the user's post count, if this is indeed a real user
            if poster_id != -1:
                stmt = """
                        UPDATE
                            %susers
                        SET
                            user_posts=user_posts+1,
                            user_lastpost_time=UNIX_TIMESTAMP()
                        WHERE
                            user_id=%s""" % (prefix, poster_id)
                self.query(stmt)
            # setup last post on the topic thread (Patricio Anguita <*****@*****.**>)
            if replying:
                incval='1'
            else:
                incval='0'

            stmt = """
                    UPDATE
                        %stopics
                    SET
                        topic_replies=topic_replies+%s,
                        topic_replies_real=topic_replies_real+%s,
                        topic_last_post_id=%s,
                        topic_last_poster_id=%s,
                        topic_last_poster_name='%s',
                        topic_last_poster_colour='%s',
                        topic_last_post_subject='%s',
                        topic_last_post_time=UNIX_TIMESTAMP()
                    WHERE
                        topic_id=%s""" % (prefix, incval, incval, new_id, poster_id, self.quote_string(post_username), postercolor, self.quote_string(subject), thread_id)
            self.query(stmt)
            # if this is the first post on the thread.. (Patricio Anguita <*****@*****.**>)
            if not replying:
                stmt = """
                        UPDATE
                            %stopics
                        SET
                            topic_first_post_id=%s,
                            topic_first_poster_name='%s',
                            topic_first_poster_colour='%s'
                        WHERE
                            topic_id=%s AND
                            topic_first_post_id=0""" % (prefix, new_id, self.quote_string(post_username), postercolor, thread_id)
                self.query(stmt)
            return 1