예제 #1
0
 def get_forum_email_id(self, forum_id):
     # Generate a predictable, but sufficiently unique topic ID.
     s = 'f.%s.%08d' % (self.config.get('project', 'url'), int(forum_id))
     digest = md5(s).hexdigest()
     host = self.from_email[self.from_email.find('@') + 1:]
     email_id = '<%03d.%s@%s>' % (len(s), digest, host)
     return email_id
예제 #2
0
 def _message_id(self, event, event_id, modtime):
     """Generate a predictable, but sufficiently unique message ID."""
     s = '%s.%s.%d' % (self.env.project_url, event_id, modtime)
     dig = md5(s).hexdigest()
     host = self.smtp_from[self.smtp_from.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #3
0
파일: macro.py 프로젝트: nyuhuhuu/trachacks
    def _get_coords(self, address):
        m = md5()
        m.update(address)
        hash = m.hexdigest()

        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute("SELECT lon,lat,acc FROM googlemapmacro WHERE id='%s';" % hash)
        for row in cursor:
            if len(row) == 3:
                self.env.log.debug("Reusing coordinates from database")
                return ( str(row[0]), str(row[1]), str(row[2]) )

        response = None
        url = r'http://maps.google.com/maps/geo?output=csv&q=' + quote_plus(address)
        try:
            response = urlopen(url).read()
        except:
            raise TracError("Google Maps could not be contacted to resolve address!");
        self.env.log.debug("Google geocoding response: '%s'" % response)
        resp = response.split(',')
        if len(resp) != 4 or not resp[0] == "200":
            raise TracError("Given address '%s' couldn't be resolved by Google Maps!" % address);
        acc, lon, lat = resp[1:4]

        cursor.execute(
            "INSERT INTO googlemapmacro (id, lon, lat, acc) VALUES ('%s', %s, %s, %s);" %
            (hash, lon, lat, acc))
        db.commit()
        self.env.log.debug("Saving coordinates to database")

        return (lon, lat, acc)
예제 #4
0
    def do_auth(self, environ, start_response):
        header = environ.get("HTTP_AUTHORIZATION")
        if not header or not header.startswith("Digest"):
            self.send_auth_request(environ, start_response)
            return None

        auth = self.parse_auth_header(header[7:])
        required_keys = ["username", "realm", "nonce", "uri", "response", "nc", "cnonce"]
        # Invalid response?
        for key in required_keys:
            if not auth.has_key(key):
                self.send_auth_request(environ, start_response)
                return None
        # Unknown user?
        self.check_reload()
        if not self.hash.has_key(auth["username"]):
            self.send_auth_request(environ, start_response)
            return None

        kd = lambda x: md5(":".join(x)).hexdigest()
        a1 = self.hash[auth["username"]]
        a2 = kd([environ["REQUEST_METHOD"], auth["uri"]])
        # Is the response correct?
        correct = kd([a1, auth["nonce"], auth["nc"], auth["cnonce"], auth["qop"], a2])
        if auth["response"] != correct:
            self.send_auth_request(environ, start_response)
            return None
        # Is the nonce active, if not ask the client to use a new one
        if not auth["nonce"] in self.active_nonces:
            self.send_auth_request(environ, start_response, stale="true")
            return None
        self.active_nonces.remove(auth["nonce"])
        return auth["username"]
예제 #5
0
    def expand_macro(self, formatter, name, content, args={}):
        "Produces XHTML code to display mindmaps"

        # Test if this is the long or short version of a macro call
        try:
            # Starting from Trac 0.12 the `args` argument should be set for long
            # macros with arguments. However, it can be still empty and is not
            # used at all in 0.11.
            if not args:
                # Check for multi-line content, i.e. long macro form
                args, content = content.split("\n", 1)
        except:  # Short macro
            largs, kwargs = parse_args(content)
            if not largs:
                raise TracError("File name missing!")
            file = largs[0]
            url = extract_url(self.env, formatter.context, file, raw=True)
        else:  # Long macro
            largs, kwargs = parse_args(args)
            digest = md5()
            digest.update(unicode(content).encode('utf-8'))
            hash = digest.hexdigest()
            if not self._check_cache(hash):
                mm = MindMap(content)
                self._set_cache(hash, mm)
            url = formatter.context.href.mindmap(hash + '.mm')
        return self.produce_html(formatter.context, url, kwargs)
예제 #6
0
 def _message_id(self, event, event_id, modtime):
     """Generate a predictable, but sufficiently unique message ID."""
     s = '%s.%s.%d' % (self.env.project_url, event_id, modtime)
     dig = md5(s).hexdigest()
     host = self.smtp_from[self.smtp_from.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #7
0
파일: macro.py 프로젝트: nyuhuhuu/trachacks
    def expand_macro(self, formatter, name, content, args={}):
        "Produces XHTML code to display mindmaps"

        # Test if this is the long or short version of a macro call
        try:
          # Starting from Trac 0.12 the `args` argument should be set for long 
          # macros with arguments. However, it can be still empty and is not
          # used at all in 0.11.
          if not args:
            # Check for multi-line content, i.e. long macro form
            args, content = content.split("\n",1)
        except: # Short macro
          largs, kwargs = parse_args( content )
          if not largs:
            raise TracError("File name missing!")
          file = largs[0]
          url = extract_url (self.env, formatter.context, file, raw=True)
        else: # Long macro
          largs, kwargs = parse_args( args )
          digest = md5()
          digest.update(unicode(content).encode('utf-8'))
          hash = digest.hexdigest()
          if not self._check_cache(hash):
            mm = MindMap(content)
            self._set_cache(hash, mm)
          url = formatter.context.href.mindmap(hash + '.mm')
        return self.produce_html(formatter.context, url, kwargs)
예제 #8
0
파일: api.py 프로젝트: wiraqutra/photrackjp
    def check_modified(self, datetime, extra=''):
        """Check the request "If-None-Match" header against an entity tag.

        The entity tag is generated from the specified last modified time
        (`datetime`), optionally appending an `extra` string to
        indicate variants of the requested resource.

        That `extra` parameter can also be a list, in which case the MD5 sum
        of the list content will be used.

        If the generated tag matches the "If-None-Match" header of the request,
        this method sends a "304 Not Modified" response to the client.
        Otherwise, it adds the entity tag as an "ETag" header to the response
        so that consecutive requests can be cached.
        """
        if isinstance(extra, list):
            m = md5()
            for elt in extra:
                m.update(repr(elt))
            extra = m.hexdigest()
        etag = 'W/"%s/%s/%s"' % (self.authname, http_date(datetime), extra)
        inm = self.get_header('If-None-Match')
        if (not inm or inm != etag):
            self.send_header('ETag', etag)
        else:
            self.send_response(304)
            self.send_header('Content-Length', 0)
            self.end_headers()
            raise RequestDone
예제 #9
0
 def get_forum_email_id(self, forum_id):
     # Generate a predictable, but sufficiently unique topic ID.
     s = "f.%s.%08d" % (self.config.get("project", "url"), int(forum_id))
     digest = md5(s).hexdigest()
     host = self.from_email[self.from_email.find("@") + 1 :]
     email_id = "<%03d.%s@%s>" % (len(s), digest, host)
     return email_id
예제 #10
0
파일: auth.py 프로젝트: zjj/trac_hack
    def do_auth(self, environ, start_response):
        header = environ.get('HTTP_AUTHORIZATION')
        if not header or not header.startswith('Digest'):
            self.send_auth_request(environ, start_response)
            return None

        auth = self.parse_auth_header(header[7:])
        required_keys = ['username', 'realm', 'nonce', 'uri', 'response',
                         'nc', 'cnonce']
        # Invalid response?
        for key in required_keys:
            if not auth.has_key(key):
                self.send_auth_request(environ, start_response)
                return None
        # Unknown user?
        self.check_reload()
        if not self.hash.has_key(auth['username']):
            self.send_auth_request(environ, start_response)
            return None

        kd = lambda x: md5(':'.join(x)).hexdigest()
        a1 = self.hash[auth['username']]
        a2 = kd([environ['REQUEST_METHOD'], auth['uri']])
        # Is the response correct?
        correct = kd([a1, auth['nonce'], auth['nc'],
                      auth['cnonce'], auth['qop'], a2])
        if auth['response'] != correct:
            self.send_auth_request(environ, start_response)
            return None
        # Is the nonce active, if not ask the client to use a new one
        if not auth['nonce'] in self.active_nonces:
            self.send_auth_request(environ, start_response, stale='true')
            return None
        self.active_nonces.remove(auth['nonce'])
        return auth['username']
예제 #11
0
 def get_forum_email_id(self, forum_id):
     # Generate a predictable, but sufficiently unique topic ID.
     s = 'f.%s.%08d' % (self.config.get('project', 'url'), int(forum_id))
     digest = md5(s).hexdigest()
     host = self.from_email[self.from_email.find('@') + 1:]
     email_id = '<%03d.%s@%s>' % (len(s), digest, host)
     return email_id
예제 #12
0
 def get_message_id(self, rcpt, modtime=None):
     """Generate a predictable, but sufficiently unique message ID."""
     s = '%s.%08d.%d.%s' % (self.env.project_url.encode('utf-8'),
                            int(self.ticket.id), to_utimestamp(modtime),
                            rcpt.encode('ascii', 'ignore'))
     dig = md5(s).hexdigest()
     host = self.from_email[self.from_email.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #13
0
 def _message_id(self, realm):
     """Generate an unique message ID."""
     modtime = time.time()
     s = '%s.%d.%s' % (self.env.project_url, modtime,
                       realm.encode('ascii', 'ignore'))
     dig = md5(s).hexdigest()
     host = self.email_from[self.email_from.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #14
0
 def get_message_id(self, rcpt, modtime=None):
     """Generate a predictable, but sufficiently unique message ID."""
     s = '%s.%08d.%d.%s' % (self.env.project_url.encode('utf-8'),
                            int(self.ticket.id), to_utimestamp(modtime),
                            rcpt.encode('ascii', 'ignore'))
     dig = md5(s).hexdigest()
     host = self.from_email[self.from_email.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #15
0
 def _message_id(self, realm, id, modtime=None):
     """Generate a predictable, but sufficiently unique message ID."""
     s = '%s.%s.%d.%s' % (self.env.project_url, 
                            id, to_timestamp(modtime),
                            realm.encode('ascii', 'ignore'))
     dig = md5(s).hexdigest()
     host = self.smtp_from[self.smtp_from.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #16
0
파일: mail.py 프로젝트: lkraav/trachacks
 def _message_id(self, realm):
     """Generate an unique message ID."""
     modtime = time.time()
     s = '%s.%d.%s' % (self.env.project_url, modtime,
                       realm.encode('ascii', 'ignore'))
     dig = md5(s).hexdigest()
     host = self.email_from[self.email_from.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #17
0
 def _message_id(self, realm):
     """Generate a predictable, but sufficiently unique message ID."""
     modtime = time.time()
     rand = random.randint(0,32000)
     s = '%s.%d.%d.%s' % (self.env.project_url,
                       modtime, rand,
                       realm.encode('ascii', 'ignore'))
     dig = md5(s).hexdigest()
     host = self.email_from[self.email_from.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #18
0
 def _message_id(self, realm):
     """Generate a predictable, but sufficiently unique message ID."""
     modtime = time.time()
     rand = random.randint(0,32000)
     s = '%s.%d.%d.%s' % (self.env.project_url,
                       modtime, rand,
                       realm.encode('ascii', 'ignore'))
     dig = md5(s).hexdigest()
     host = self.email_from[self.email_from.find('@') + 1:]
     msgid = '<%03d.%s@%s>' % (len(s), dig, host)
     return msgid
예제 #19
0
 def get_message_id(self, rcpt, modtime=None):
     """Generate a predictable, but sufficiently unique message ID."""
     s = "%s.%08d.%d.%s" % (
         self.env.project_url.encode("utf-8"),
         int(self.ticket.id),
         to_utimestamp(modtime),
         rcpt.encode("ascii", "ignore"),
     )
     dig = md5(s).hexdigest()
     host = self.from_email[self.from_email.find("@") + 1 :]
     msgid = "<%03d.%s@%s>" % (len(s), dig, host)
     return msgid
예제 #20
0
    def _get_coords(self, address):
        m = md5()
        m.update(address)
        hash = m.hexdigest()

        db = self.env.get_db_cnx()
        cursor = db.cursor()
        cursor.execute(
            "SELECT lon,lat,acc FROM googlemapmacro WHERE id='%s';" % hash)
        for row in cursor:
            if len(row) == 3:
                self.env.log.debug("Reusing coordinates from database")
                return (str(row[0]), str(row[1]), str(row[2]))

        response = None
        url = r'http://maps.google.com/maps/geo?output=csv&q=' + quote_plus(
            address)
        try:
            response = urlopen(url).read()
        except:
            raise TracError(
                "Google Maps could not be contacted to resolve address!")
        self.env.log.debug("Google geocoding response: '%s'" % response)
        resp = response.split(',')
        if len(resp) != 4 or not resp[0] == "200":
            raise TracError(
                "Given address '%s' couldn't be resolved by Google Maps!" %
                address)
        acc, lon, lat = resp[1:4]

        cursor.execute(
            "INSERT INTO googlemapmacro (id, lon, lat, acc) VALUES ('%s', %s, %s, %s);"
            % (hash, lon, lat, acc))
        db.commit()
        self.env.log.debug("Saving coordinates to database")

        return (lon, lat, acc)
예제 #21
0
    def do_auth(self, environ, start_response):
        header = environ.get('HTTP_AUTHORIZATION')
        if not header or not header.startswith('Digest'):
            self.send_auth_request(environ, start_response)
            return None

        auth = self.parse_auth_header(header[7:])
        required_keys = [
            'username', 'realm', 'nonce', 'uri', 'response', 'nc', 'cnonce'
        ]
        # Invalid response?
        for key in required_keys:
            if not auth.has_key(key):
                self.send_auth_request(environ, start_response)
                return None
        # Unknown user?
        self.check_reload()
        if not self.hash.has_key(auth['username']):
            self.send_auth_request(environ, start_response)
            return None

        kd = lambda x: md5(':'.join(x)).hexdigest()
        a1 = self.hash[auth['username']]
        a2 = kd([environ['REQUEST_METHOD'], auth['uri']])
        # Is the response correct?
        correct = kd(
            [a1, auth['nonce'], auth['nc'], auth['cnonce'], auth['qop'], a2])
        if auth['response'] != correct:
            self.send_auth_request(environ, start_response)
            return None
        # Is the nonce active, if not ask the client to use a new one
        if not auth['nonce'] in self.active_nonces:
            self.send_auth_request(environ, start_response, stale='true')
            return None
        self.active_nonces.remove(auth['nonce'])
        return auth['username']