Source

django-swingcms / swingcms / cms / code.py

Full commit
  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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import htmlentitydefs, os, csv, random, re, shutil
from StringIO import StringIO
from PIL import Image as PilImage
from zipfile import ZipFile

from django.db.models import CharField, TextField, DateTimeField, Q
from django.utils.hashcompat import sha_constructor, md5_constructor
from django.utils.translation import ugettext as _
from django.shortcuts import get_object_or_404
from django.contrib.contenttypes.models import ContentType
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.exceptions import ObjectDoesNotExist

from modules.crypt import crypt

import settings
from loading import swingcache
from custodian.models import Permission
from swingexceptions import SwingException



__all__ = ('get_model_from_model_name',
           'get_obj_or_none',
           'get_obj_or_404',
           'get_form_from_model_or_model_name',
           'get_template_path',
           'ALL_TEMPLATES',
           'search_content',

           'encrypt',
           'decrypt',
           'make_random_key',
           'get_hexdigest',

           'initialize_templates',
           'install_templates',
           'install_statics',

           'lists_to_csv',
           'csv_to_lists',
           'dicts_to_csv',
           'csv_to_dicts',
           'zipper',
           'list_to_choices',
           'unslugify',
           'thumbify',
           'simple_search'

           'ALL_TAGS',

           'entityref2character',
           'character2entityref',
           'ref_to_char',

           'character_reference_re',
           'start_tag_without_attrs_re',
           'start_tag_with_attrs_re',
           'end_tag_re',
           'self_included_tag_re',
           'newline_tag_re',
           'all_tag_re',

           'strip_tags',
           'decode_char_reference',
           'html_to_text',

           'DOM')


###############################################################
##                        SHORTHANDS                         ##
###############################################################


def get_model_from_model_name(model_name):

    return ContentType.objects.get(model=model_name).model_class()


def get_obj_or_none(obj_model_name, obj_id):

    try:
        return get_model_from_model_name(obj_model_name).objects.get(id=obj_id)
    except ObjectDoesNotExist:
        return None


def get_obj_or_404(obj_model_name, obj_id):

    return get_object_or_404(get_model_from_model_name(obj_model_name), id=obj_id)


def get_form_from_model_or_model_name(model_or_model_name, action=''):
    """
    Return form class from model (name or class) and optional action verb.
    Conventionally form's name must be camelcase notated, with only first letter of model
    name capitalized: for examples ObjectmodelnameFormAction and ObjectmodelnameForm.
    """
    if isinstance(model_or_model_name, basestring):
        Model = get_model_from_model_name(model_or_model_name)
        model_name = model_or_model_name
    else:
        Model = model_or_model_name
        model_name = Model.__name__
    try:
        forms = __import__(Model.__module__.replace('models', 'forms'), {}, {}, 'forms')
        return getattr(forms, '%sForm%s' % (model_name.capitalize(), action.capitalize()))
    except ImportError:
        raise
    except AttributeError:
        raise


def get_template_path(action, obj_or_model_name):

    if not isinstance(obj_or_model_name, basestring):
        if action == 'view':
            template = getattr(obj_or_model_name, 'template', None)
            if template:
                return template
        model_name = obj_or_model_name.model_name
    else:
        model_name = obj_or_model_name
    try:
        return settings.TEMPLATES[model_name][action][0][0]
    except KeyError:
        raise SwingException("No template available for %s %s." % (action, model_name))


def _get_all_templates():

    templates = ()
    for d1 in settings.TEMPLATES.values():
        for d2 in d1.values():
            templates += d2
    return templates

ALL_TEMPLATES = _get_all_templates()


def search_content(model_names=None,
                   content=None,
                   name=None,
                   parent=None,
                   language=None,
                   check_alternative=False):
    """
    Find content using different strategies depending of arguments,
    settings and language policy. Return None if find nothing.
    """
    # USE CASE: search version of provided content in language
    if content and language:
        if content.language and not content.language == language:
            return search_content(model_names=content.model_name,
                                  name=content.name,
                                  parent=parent,
                                  language=language,
                                  check_alternative=check_alternative)
        return content

    # USE CASE: search in parent one content version with specified name, eventually in
    # language (or default language as alternative) and return first if exist
    elif name and parent and language:
        content = None
        for c in parent.get_children():
            if c.name == name and c.language:
                if c.language == language:
                    content = c
                    break
                elif check_alternative and c.language == settings.LANGUAGE_CODE:
                    content = c
        return content

    # USE CASE: search everywhere in language version with specified name,
    # eventually with model name provided and return first if exist
    elif name:
        if isinstance(model_names, basestring):
            model_names = (model_names,)
        elif model_names:
            pass
        else:
            model_names = swingcache.CONTENTS_NAMES

        for m in model_names:
            contents = get_model_from_model_name(m).objects.filter(name=name)
            if language:
                contents = contents.filter(Q(language=language)|Q(language=None))
            if not contents.exists():
                if check_alternative and not settings.LANGUAGE_CODE == language:
                    content = search_content(model_names=model_names,
                                             name=name,
                                             parent=parent,
                                             language=settings.LANGUAGE_CODE,
                                             check_alternative=False)
                    if content:
                        return content
            else:
                return contents[0]
        else:
            return None

    # USE CASE NOT SUPPORTED
    else:
        raise SwingException("Search content case not supported.")


###############################################################
##               ENCRYPT, DIGESTS AND KEYS                   ##
###############################################################


def encrypt(s, key=settings.SECRET_KEY):

    return crypt(key[:16], s, 'xxxxxxxx')


def decrypt(s, key=settings.SECRET_KEY):

    return crypt(key[:16], s, 'xxxxxxxx')


def get_hexdigest(algo='sha1', *args):
    """
    Returns a string of the hexdigest of arguments (using default sha algorithm).
    """
    string = "".join(args)
    if algo == 'sha1':
        return sha_constructor(string).hexdigest()
    elif algo == 'md5':
        return md5_constructor(string).hexdigest()
    else:
        raise ValueError("Got unknown algorithm type.")


MAX_TOKEN = 18446744073709551616L     # 2**63

def make_random_key():

    return get_hexdigest('sha1', str(random.randrange(0, MAX_TOKEN)), settings.SECRET_KEY)


###############################################################
##                        OTHER                              ##
###############################################################


def lists_to_csv(table, csv_file_name, put_field_names=False):

    f = open(csv_file_name, 'wb')
    writer = csv.writer(f,
                        delimiter=',',
                        quotechar='"',
                        quoting=csv.QUOTE_ALL)
    for r in table:
        writer.writerow(r)
    f.close()


def csv_to_lists(csv_file_name, guess_field_names=False):

    table = []
    f = open(csv_file_name, 'rb')
    reader = csv.reader(f,
                        delimiter=',',
                        quotechar='"',
                        quoting=csv.QUOTE_ALL)
    for r in reader:
        table.append(r)
    f.close()
    return table


def dicts_to_csv(table, csv_file_name, field_names=None, put_field_names=False):
    """
    A wrapper around csv.DictWriter method.
    """
    field_names = field_names or table[0].keys()
    f = open(csv_file_name, 'wb')
    if put_field_names:
        table.insert(0, dict(zip(field_names,field_names)))
    writer = csv.DictWriter(f,
                            fieldnames=field_names,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_ALL)
    for r in table:
        writer.writerow(r)
    f.close()


def csv_to_dicts(csv_file_name, field_names=None):
    """
    A wrapper around csv.DictReader method.
    """
    table = []
    f = open(csv_file_name, 'rb')
    reader = csv.DictReader(f,
                            fieldnames=field_names,
                            delimiter=',',
                            quotechar='"',
                            quoting=csv.QUOTE_ALL)
    for r in reader:
        table.append(r)
    f.close()
    return table


def zipper(path_source, path_destination):

    def _zip(path_source, path_destination):

        ld = os.listdir(path_source)
        for f in ld:
            path = os.path.join(path_source, f)
            if os.path.isfile(path):
                zf.write(path)
            else:
                _zip(path, path_destination)

    zf = ZipFile(path_destination, 'w')
    _zip(path_source, path_destination)
    return zf


def list_to_choices(list_):
    """
    Build choices tuples from list.
    """
    return tuple((i,i) for i in list_)


def slugify(value):

    value = unicode(re.sub("[^\w\s-]", "", value).strip().lower())
    value = re.sub("[-\s]+", "-", value)
    return value


def unslugify(words):

    return words.replace('-',' ')


def thumbify(file_field_instance):

    im = PilImage.open(file_field_instance.file)
    im.thumbnail(settings.THUMB_SIZE, PilImage.ANTIALIAS)
    imuf = InMemoryUploadedFile(StringIO(), 'thumb', 'thumbnail.' + file_field_instance.name, 'image/jpeg', 0, None)
    im.save(imuf.file , 'JPEG')
    imuf.size = imuf.file.tell()
    return imuf


def simple_search(query_raw):

    # check parity of quote character
    if query_raw.count('"') % 2:
        raise SwingException(_("Number of double quote character cannot be odd."))

    # extract quoted phrases
    pattern = re.compile(r'"[^"]*"')
    phrases = pattern.findall(query_raw)
    phrases = [p.replace('"', '').strip(" ") for p in phrases if p]

    # extract no quoted words
    words = pattern.sub("", query_raw)
    words = [r for r in words.split(" ") if r]

    # combine phrases and words
    query_list = phrases + words

    # commit query
    items = set()
    for model_name in settings.COLLECTIBLE:
        ct = ContentType.objects.get(model=model_name)
        Model = ct.model_class()
        items_for_model = set()
        for s in query_list:
            items_for_word_or_phrase = set()
            for f in Model._meta.fields:
                if isinstance(f, (CharField, TextField)):
                    # OR-ing items with word or phrase in almost one field
                    sql_raw = "SELECT * FROM " + ct.app_label + "_" + model_name + " WHERE " + f.name + " LIKE '%%" + s + "%%';"
                    items_for_word_or_phrase = items_for_word_or_phrase.union(Model.objects.raw(sql_raw))
            # AND-ing items for each word or phrase
            if items_for_model:
                items_for_model = items_for_model.intersection(items_for_word_or_phrase)
            else:
                items_for_model = items_for_word_or_phrase
        items.update(items_for_model)
    return items


###############################################################
##                      HTML UTILITIES                       ##
###############################################################


##### definitions #####


ALL_TAGS = ('!--', '!DOCTYPE', 'a', 'abbr', 'acronym', 'address', 'applet', 'area', 'b', 'base',
            'basefont', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'caption', 'center',
            'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt',
            'em', 'fieldset', 'font', 'form', 'frame', 'frameset', 'head', 'h1', 'h2', 'h3', 'h4',
            'h5', 'h6', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'label',
            'legend', 'li', 'link', 'map', 'menu', 'meta', 'noframes', 'noscript', 'object', 'ol',
            'optgroup', 'option', 'p', 'param', 'pre', 'q', 's', 'samp', 'script', 'select',
            'small', 'span', 'strike', 'strong', 'style', 'sub', 'sup', 'table', 'tbody', 'td',
            'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'tt', 'u', 'ul', 'var')

# xhtml character entity references encoding/decoding facilities
_name2codepoint = htmlentitydefs.name2codepoint
_name2codepoint['apos'] = 39
entityref2character = {k:unichr(v) for k,v in _name2codepoint.iteritems()}
character2entityref = {v:k for k,v in entityref2character.iteritems()}


def ref_to_char(ref):
    """
    Replace reference (numeric or entity) with the corresponding character.
    If reference not in dictionary return reference itself.
    """
    if ref[0] == '#':
        # is numeric reference
        ref = ref[1:]
        try:
            if ref[0] in ['x','X']:
                # is base 16
                codepoint = int(ref[1:], 16)
            else:
                # is base 10
                codepoint = int(ref)
            return unichr(codepoint)
        except ValueError:
            # un-recognizable
            return '&#%s;' % ref
    else:
        # is entity reference or un-recognizable
        return entityref2character.get(ref, '&%s;' % ref)


# patterns for character reference
character_reference_re = re.compile(r"&(?P<ref>#\d+|#x[0-9a-fA-F]+|\w+);")

# patterns for tag
start_tag_without_attrs_re = re.compile(r"<(?P<name>[a-zA-Z0-9]+) *>", re.IGNORECASE)
start_tag_with_attrs_re = re.compile(r"<(?P<name>[a-zA-Z0-9]+) (?P<attrs>[^<>]+)>", re.IGNORECASE)
end_tag_re = re.compile(r"</(?P<name>[a-zA-Z0-9]+) *>", re.IGNORECASE)
self_included_tag_re = re.compile(r"<(?P<name>[a-zA-Z0-9]+)(?P<attrs> [^<>]*| *)/>", re.IGNORECASE)
newline_tag_re = re.compile(r"<br */>|<p>|<p [^<>]*>|<p */>|<h[0-6]>|<h[0-6] [^<>]*>|<h[0-6] */>", re.IGNORECASE)
all_tag_re = re.compile(r"<[^<>]*>", re.IGNORECASE)


##### html cleaning #####


def decode_char_reference(html):
    """
    Take unicode html string and replace all references
    (numeric or entity) with the corresponding special chars.
    """
    def _reference_replace(mo):
        return ref_to_char(mo.group('ref'))

    return character_reference_re.sub(_reference_replace, html)


def strip_tags(html, permitted_tags=settings.PERMITTED_TAGS5):
    """
    Take unicode html string and remove all tags except those specified as permitted.
    """
    def _conditional_replace(mo):
        return mo.group('name') in permitted_tags and mo.group(0) or ''

    if permitted_tags == 'ALL':
        return all_tag_re.sub("", html)

    for re in (start_tag_without_attrs_re,
               start_tag_with_attrs_re,
               end_tag_re,
               self_included_tag_re):
        html = re.sub(_conditional_replace, html)

    return html


def html_to_text(html):

    # 1: replace/manage endline cases
    html = newline_tag_re.sub("\n", html)

    # 2: remove all remaining tags and attributes
    html = strip_tags(html, 'ALL')

    # 3: decode char references
    html = decode_char_reference(html)

    return html


##### html parsing and dom management class #####

try:
    import BeautifulSoup

    class DOM(BeautifulSoup.BeautifulSoup):

        def __init__(self, *args, **kwargs):

            kwargs.setdefault('convertEntities', BeautifulSoup.BeautifulStoneSoup.XHTML_ENTITIES)
            super(DOM, self).__init__(*args, **kwargs)

        def handle_data(self, data):

            super(DOM, self).handle_data(data)

        def handle_charref(self, ref):

            super(DOM, self).handle_charref(ref)

        def handle_entityref(self, ref):

            super(DOM, self).handle_entityref(ref)

except ImportError:
    pass