This file is indexed.

/usr/lib/python2.7/dist-packages/TileStache/Mapnik.py is in tilestache 1.49.8-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
""" Mapnik Providers.

ImageProvider is known as "mapnik" in TileStache config, GridProvider is
known as "mapnik grid". Both require Mapnik to be installed; Grid requires
Mapnik 2.0.0 and above.
"""
from time import time
from os.path import exists
from thread import allocate_lock
from urlparse import urlparse, urljoin
from itertools import count
from glob import glob
from tempfile import mkstemp
from urllib import urlopen

import os
import logging
import json

try:
    import mapnik
except ImportError:
    # can still build documentation
    pass

from TileStache.Core import KnownUnknown
from TileStache.Geography import getProjectionByName

try:
    from PIL import Image
except ImportError:
    # On some systems, PIL.Image is known as Image.
    import Image

if 'mapnik' in locals():
    _version = hasattr(mapnik, 'mapnik_version') and mapnik.mapnik_version() or 701
    
    if _version >= 20000:
        Box2d = mapnik.Box2d
    else:
        Box2d = mapnik.Envelope

global_mapnik_lock = allocate_lock()

class ImageProvider:
    """ Built-in Mapnik provider. Renders map images from Mapnik XML files.
    
        This provider is identified by the name "mapnik" in the TileStache config.
        
        Arguments:
        
        - mapfile (required)
            Local file path to Mapnik XML file.
    
        - fonts (optional)
            Local directory path to *.ttf font files.
    
        More information on Mapnik and Mapnik XML:
        - http://mapnik.org
        - http://trac.mapnik.org/wiki/XMLGettingStarted
        - http://trac.mapnik.org/wiki/XMLConfigReference
    """
    
    def __init__(self, layer, mapfile, fonts=None):
        """ Initialize Mapnik provider with layer and mapfile.
            
            XML mapfile keyword arg comes from TileStache config,
            and is an absolute path by the time it gets here.
        """
        maphref = urljoin(layer.config.dirpath, mapfile)
        scheme, h, path, q, p, f = urlparse(maphref)
        
        if scheme in ('file', ''):
            self.mapfile = path
        else:
            self.mapfile = maphref
        
        self.layer = layer
        self.mapnik = None
        
        engine = mapnik.FontEngine.instance()
        
        if fonts:
            fontshref = urljoin(layer.config.dirpath, fonts)
            scheme, h, path, q, p, f = urlparse(fontshref)
            
            if scheme not in ('file', ''):
                raise Exception('Fonts from "%s" can\'t be used by Mapnik' % fontshref)
        
            for font in glob(path.rstrip('/') + '/*.ttf'):
                engine.register_font(str(font))

    @staticmethod
    def prepareKeywordArgs(config_dict):
        """ Convert configured parameters to keyword args for __init__().
        """
        kwargs = {'mapfile': config_dict['mapfile']}

        if 'fonts' in config_dict:
            kwargs['fonts'] = config_dict['fonts']
        
        return kwargs
    
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
        """
        """
        start_time = time()
        
        #
        # Mapnik can behave strangely when run in threads, so place a lock on the instance.
        #
        if global_mapnik_lock.acquire():
            try:
                if self.mapnik is None:
                    self.mapnik = get_mapnikMap(self.mapfile)
                    logging.debug('TileStache.Mapnik.ImageProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile)

                self.mapnik.width = width
                self.mapnik.height = height
                self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax))
            
                img = mapnik.Image(width, height)
                mapnik.render(self.mapnik, img) 
            except:
                self.mapnik = None
                raise
            finally:
                # always release the lock
                global_mapnik_lock.release()

        if hasattr(Image, 'frombytes'):
            # Image.fromstring is deprecated past Pillow 2.0
            img = Image.frombytes('RGBA', (width, height), img.tostring())
        else:
            # PIL still uses Image.fromstring
            img = Image.fromstring('RGBA', (width, height), img.tostring())
        
        logging.debug('TileStache.Mapnik.ImageProvider.renderArea() %dx%d in %.3f from %s', width, height, time() - start_time, self.mapfile)
    
        return img

class GridProvider:
    """ Built-in UTF Grid provider. Renders JSON raster objects from Mapnik.
    
        This provider is identified by the name "mapnik grid" in the
        Tilestache config, and uses Mapnik 2.0 (and above) to generate
        JSON UTF grid responses.
        
        Sample configuration for a single grid layer:

          "provider":
          {
            "name": "mapnik grid",
            "mapfile": "world_merc.xml", 
            "fields": ["NAME", "POP2005"]
          }
    
        Sample configuration for multiple overlaid grid layers:

          "provider":
          {
            "name": "mapnik grid",
            "mapfile": "world_merc.xml",
            "layers":
            [
              [1, ["NAME"]],
              [0, ["NAME", "POP2005"]],
              [0, null],
              [0, []]
            ]
          }
    
        Arguments:
        
        - mapfile (required)
          Local file path to Mapnik XML file.
        
        - fields (optional)
          Array of field names to return in the response, defaults to all.
          An empty list will return no field names, while a value of null is
          equivalent to all.
        
        - layer index (optional)
          Which layer from the mapfile to render, defaults to 0 (first layer).
        
        - layers (optional)
          Ordered list of (layer index, fields) to combine; if provided
          layers overrides both layer index and fields arguments.
          An empty fields list will return no field names, while a value of null 
          is equivalent to all fields.
 
        - scale (optional)
          Scale factor of output raster, defaults to 4 (64x64).
        
        - layer id key (optional)
          If set, each item in the 'data' property will have its source mapnik
          layer name added, keyed by this value. Useful for distingushing
          between data items.
        
        Information and examples for UTF Grid:
        - https://github.com/mapbox/utfgrid-spec/blob/master/1.2/utfgrid.md
        - http://mapbox.github.com/wax/interaction-leaf.html
    """
    def __init__(self, layer, mapfile, fields=None, layers=None, layer_index=0, scale=4, layer_id_key=None):
        """ Initialize Mapnik grid provider with layer and mapfile.
            
            XML mapfile keyword arg comes from TileStache config,
            and is an absolute path by the time it gets here.
        """
        self.mapnik = None
        self.layer = layer

        maphref = urljoin(layer.config.dirpath, mapfile)
        scheme, h, path, q, p, f = urlparse(maphref)

        if scheme in ('file', ''):
            self.mapfile = path
        else:
            self.mapfile = maphref

        self.scale = scale
        self.layer_id_key = layer_id_key
        
        if layers:
            self.layers = layers
        else:
            self.layers = [[layer_index or 0, fields]]

    @staticmethod
    def prepareKeywordArgs(config_dict):
        """ Convert configured parameters to keyword args for __init__().
        """
        kwargs = {'mapfile': config_dict['mapfile']}

        for key in ('fields', 'layers', 'layer_index', 'scale', 'layer_id_key'):
            if key in config_dict:
                kwargs[key] = config_dict[key]
        
        return kwargs
    
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
        """
        """
        start_time = time()
        
        #
        # Mapnik can behave strangely when run in threads, so place a lock on the instance.
        #
        if global_mapnik_lock.acquire():
            try:
                if self.mapnik is None:
                    self.mapnik = get_mapnikMap(self.mapfile)
                    logging.debug('TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile)

                self.mapnik.width = width
                self.mapnik.height = height
                self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax))
            
                if self.layer_id_key is not None:
                    grids = []
    
                    for (index, fields) in self.layers:
                        datasource = self.mapnik.layers[index].datasource
                        fields = (type(fields) is list) and map(str, fields) or datasource.fields()
                    
                        grid = mapnik.render_grid(self.mapnik, index, resolution=self.scale, fields=fields)
    
                        for key in grid['data']:
                            grid['data'][key][self.layer_id_key] = self.mapnik.layers[index].name
    
                        grids.append(grid)
        
                    # global_mapnik_lock.release()
                    outgrid = reduce(merge_grids, grids)
           
                else:
                    grid = mapnik.Grid(width, height)
    
                    for (index, fields) in self.layers:
                        datasource = self.mapnik.layers[index].datasource
                        fields = (type(fields) is list) and map(str, fields) or datasource.fields()
    
                        mapnik.render_layer(self.mapnik, grid, layer=index, fields=fields)
    
                    # global_mapnik_lock.release()
                    outgrid = grid.encode('utf', resolution=self.scale, features=True)
            except:
                self.mapnik = None
                raise
            finally:
                global_mapnik_lock.release()

        logging.debug('TileStache.Mapnik.GridProvider.renderArea() %dx%d at %d in %.3f from %s', width, height, self.scale, time() - start_time, self.mapfile)

        return SaveableResponse(outgrid, self.scale)

    def getTypeByExtension(self, extension):
        """ Get mime-type and format by file extension.

            This only accepts "json".
        """
        if extension.lower() != 'json':
            raise KnownUnknown('MapnikGrid only makes .json tiles, not "%s"' % extension)

        return 'application/json; charset=utf-8', 'JSON'

class SaveableResponse:
    """ Wrapper class for JSON response that makes it behave like a PIL.Image object.

        TileStache.getTile() expects to be able to save one of these to a buffer.
    """
    def __init__(self, content, scale):
        self.content = content
        self.scale = scale

    def save(self, out, format):
        if format != 'JSON':
            raise KnownUnknown('MapnikGrid only saves .json tiles, not "%s"' % format)

        bytes = json.dumps(self.content, ensure_ascii=False).encode('utf-8')
        out.write(bytes)
    
    def crop(self, bbox):
        """ Return a cropped grid response.
        """
        minchar, minrow, maxchar, maxrow = [v/self.scale for v in bbox]

        keys, data = self.content['keys'], self.content.get('data', None)
        grid = [row[minchar:maxchar] for row in self.content['grid'][minrow:maxrow]]
        
        cropped = dict(keys=keys, data=data, grid=grid)
        return SaveableResponse(cropped, self.scale)

def merge_grids(grid1, grid2):
    """ Merge two UTF Grid objects.
    """
    #
    # Concatenate keys and data, assigning new indexes along the way.
    #

    keygen, outkeys, outdata = count(1), [], dict()
    
    for ingrid in [grid1, grid2]:
        for (index, key) in enumerate(ingrid['keys']):
            if key not in ingrid['data']:
                outkeys.append('')
                continue
        
            outkey = '%d' % keygen.next()
            outkeys.append(outkey)
    
            datum = ingrid['data'][key]
            outdata[outkey] = datum
    
    #
    # Merge the two grids, one on top of the other.
    #
    
    offset, outgrid = len(grid1['keys']), []
    
    def newchar(char1, char2):
        """ Return a new encoded character based on two inputs.
        """
        id1, id2 = decode_char(char1), decode_char(char2)
        
        if grid2['keys'][id2] == '':
            # transparent pixel, use the bottom character
            return encode_id(id1)
        
        else:
            # opaque pixel, use the top character
            return encode_id(id2 + offset)
    
    for (row1, row2) in zip(grid1['grid'], grid2['grid']):
        outrow = [newchar(c1, c2) for (c1, c2) in zip(row1, row2)]
        outgrid.append(''.join(outrow))
    
    return dict(keys=outkeys, data=outdata, grid=outgrid)

def encode_id(id):
    id += 32
    if id >= 34:
        id = id + 1
    if id >= 92:
        id = id + 1
    if id > 127:
        return unichr(id)
    return chr(id)

def decode_char(char):
    id = ord(char)
    if id >= 93:
        id = id - 1
    if id >= 35:
        id = id - 1
    return id - 32

def get_mapnikMap(mapfile):
    """ Get a new mapnik.Map instance for a mapfile
    """
    mmap = mapnik.Map(0, 0)
    
    if exists(mapfile):
        mapnik.load_map(mmap, str(mapfile))
    
    else:
        handle, filename = mkstemp()
        os.write(handle, urlopen(mapfile).read())
        os.close(handle)

        mapnik.load_map(mmap, filename)
        os.unlink(filename)
    
    return mmap