2 # -*- coding: utf-8 -*-
 
  13 # Limit maximum CPU time
 
  14 # The Postscript output format can sometimes take hours
 
  15 resource.setrlimit(resource.RLIMIT_CPU,(180,180))
 
  18 # Some odd requests can cause extreme memory usage
 
  19 resource.setrlimit(resource.RLIMIT_AS,(4000000000, 4000000000))
 
  21 # Routine to output HTTP headers
 
  22 def output_headers(content_type, filename = "", length = 0):
 
  23   print "Content-Type: %s" % content_type
 
  25     print "Content-Disposition: attachment; filename=\"%s\"" % filename
 
  27     print "Content-Length: %d" % length
 
  30 # Routine to output the contents of a file
 
  31 def output_file(file):
 
  33   shutil.copyfileobj(file, sys.stdout)
 
  35 # Routine to get the size of a file
 
  37   return os.fstat(file.fileno()).st_size
 
  39 # Routine to report an error
 
  40 def output_error(message):
 
  41   output_headers("text/html")
 
  44   print "<title>Error</title>"
 
  47   print "<h1>Error</h1>"
 
  48   print "<p>%s</p>" % message
 
  52 # Parse CGI parameters
 
  53 form = cgi.FieldStorage()
 
  55 # Make sure we have a user agent
 
  56 if not os.environ.has_key('HTTP_USER_AGENT'):
 
  57   os.environ['HTTP_USER_AGENT'] = 'NONE'
 
  59 # Get the load average
 
  60 loadavg = float(open("/proc/loadavg").readline().split(" ")[0])
 
  64   # Abort if the load average on the machine is too high
 
  65   print "Status: 503 Service Unavailable"
 
  66   output_error("The load average on the server is too high at the moment. Please wait a few minutes before trying again.")
 
  67 <% @blocks["user_agents"].each do |user_agent| -%>
 
  68 elif os.environ['HTTP_USER_AGENT'] == '<%= user_agent %>':
 
  70   print "Status: 503 Service Unavailable"
 
  71   output_error("The load average on the server is too high at the moment. Please wait a few minutes before trying again.")
 
  73 elif not form.has_key("bbox"):
 
  74   # No bounding box specified
 
  75   output_error("No bounding box specified")
 
  76 elif not form.has_key("scale"):
 
  78   output_error("No scale specified")
 
  79 elif not form.has_key("format"):
 
  81   output_error("No format specified")
 
  83   # Create projection object
 
  84   prj = mapnik.Projection("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over");
 
  86   # Get the bounds of the area to render
 
  87   bbox = [float(x) for x in form.getvalue("bbox").split(",")]
 
  89   if bbox[0] >= bbox[2] or bbox[1] >= bbox[3]:
 
  91     output_error("Invalid bounding box")
 
  93     # Project the bounds to the map projection
 
  94     bbox = mapnik.forward_(mapnik.Box2d(*bbox), prj)
 
  96     # Get the style to use
 
  97     style = form.getvalue("style", "default")
 
  99     # Calculate the size of the final rendered image
 
 100     scale = float(form.getvalue("scale"))
 
 101     width = int(bbox.width() / scale / 0.00028)
 
 102     height = int(bbox.height() / scale / 0.00028)
 
 104     # Limit the size of map we are prepared to produce
 
 105     if width * height > 4000000:
 
 106       # Map is too large (limit is approximately A2 size)
 
 107       output_error("Map too large")
 
 110       map = mapnik.Map(width, height)
 
 112       # Load map configuration
 
 113       mapnik.load_map(map, "/srv/tile.openstreetmap.org/styles/%s/project.xml" % style)
 
 115       # Zoom the map to the bounding box
 
 116       map.zoom_to_box(bbox)
 
 119       if form.getvalue("format") == "png":
 
 120         image = mapnik.Image(map.width, map.height)
 
 121         mapnik.render(map, image)
 
 122         png = image.tostring("png")
 
 123         output_headers("image/png", "map.png", len(png))
 
 124         sys.stdout.write(png)
 
 125       elif form.getvalue("format") == "jpeg":
 
 126         image = mapnik.Image(map.width, map.height)
 
 127         mapnik.render(map, image)
 
 128         jpeg = image.tostring("jpeg")
 
 129         output_headers("image/jpeg", "map.jpg", len(jpeg))
 
 130         sys.stdout.write(jpeg)
 
 131       elif form.getvalue("format") == "svg":
 
 132         file = tempfile.NamedTemporaryFile(prefix = "export")
 
 133         surface = cairo.SVGSurface(file.name, map.width, map.height)
 
 134         mapnik.render(map, surface)
 
 136         output_headers("image/svg+xml", "map.svg", file_size(file))
 
 138       elif form.getvalue("format") == "pdf":
 
 139         file = tempfile.NamedTemporaryFile(prefix = "export")
 
 140         surface = cairo.PDFSurface(file.name, map.width, map.height)
 
 141         mapnik.render(map, surface)
 
 143         output_headers("application/pdf", "map.pdf", file_size(file))
 
 145       elif form.getvalue("format") == "ps":
 
 146         file = tempfile.NamedTemporaryFile(prefix = "export")
 
 147         surface = cairo.PSSurface(file.name, map.width, map.height)
 
 148         mapnik.render(map, surface)
 
 150         output_headers("application/postscript", "map.ps", file_size(file))
 
 153         output_error("Unknown format '%s'" % form.getvalue("format"))