Source

django-swingcms / swingcms / cms / models.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
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import datetime, time, os
from sys import getsizeof # required python 2.6 or higher
try:
    import cPickle as pickle
except ImportError:
    import pickle

from django.db import models
from django.db.models.loading import AppCache
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned, ValidationError
from django.core.cache import cache
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.core.validators import RegexValidator

import settings
from swingexceptions import SelfInclusion, LockError, PartiallyExecuted, PermissionDenied
from cms.code import get_obj_or_none, get_obj_or_404, get_template_path, list_to_choices
from custodian.models import User
from custodian.code import get_user, calculate_user_specific_perms, grant_specific_perm, \
                           has_perm, remove_all_specific_perm, inherit_perms



class BlobField(models.TextField):

    description = "Blob field for python objects."

    __metaclass__ = models.SubfieldBase

    def get_internal_type(self):

        return "TextField"

    def to_python(self, value):

        try:
            # is a pickled object: unpickle in format 0 (ascii-encoded)
            value = pickle.loads(value.encode('ascii', 'ignore'))
        except:
            # is a python object: let
            pass
        return value

    def get_db_prep_save(self, value, connection):

        try:
            # pickle in format 0 (ascii-encoded)
            value = pickle.dumps(value, 0)
        except pickle.PicklingError:
            # unpickable object
            raise
        return value


class MinimalField(models.CharField):

    description = "A field containing only lowercase chars."

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

        super(MinimalField, self).__init__(*args, **kwargs)
        self.validators = [RegexValidator(r"^[a-z]+$", message=_("Only lowercase chars permitted."))]


class SmartFileField(models.FileField):

    description = "A field containing sized file and providing smart file uploading in form."

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

        self.max_size = kwargs.pop('max_size', None)
        super(SmartFileField, self).__init__(*args, **kwargs)

    def formfield(self, **kwargs):

        from cms.forms import SmartFileFormField

        defaults = {'form_class': SmartFileFormField,
                    'max_size': self.max_size}
        defaults.update(kwargs)
        return super(SmartFileField, self).formfield(**defaults)


class SmartImageField(models.ImageField):

    description = "A field containing sized image and providing smart image uploading in form."

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

        self.max_size = kwargs.pop('max_size', None)
        super(SmartImageField, self).__init__(*args, **kwargs)

    def formfield(self, **kwargs):

        from cms.forms import SmartImageFormField

        defaults = {'form_class': SmartImageFormField,
                    'max_size': self.max_size}
        defaults.update(kwargs)
        return super(SmartImageField, self).formfield(**defaults)


########################################################
##                 SETTING MANAGEMENT                 ##
########################################################


class DynamicSetting(models.Model):
    """
    Used to expose and manage some settings.
    """
    name = models.CharField(_('name'), max_length=64, unique=True)
    value = BlobField(_('value'), max_length=2048)

    def __unicode__(self):

        return '%s = %s' % (self.name, self.value)

class DynamicSettingManager(object):

    def __setattr__(self, name, value):

        ds, created = DynamicSetting.objects.get_or_create(name=name)
        ds.value = value
        ds.save()

    def __getattr__(self, name, default='NULL_VALUE'):

        try:
            return DynamicSetting.objects.get(name=name).value
        except ObjectDoesNotExist:
            if default == 'NULL_VALUE':
                raise AttributeError()
            else:
                return default

ds = DynamicSettingManager()


#########################################################################
##  BASE CLASSES FOR TEMPLATING, CATEGORIZATION AND LOGGING MANAGEMENT ##
#########################################################################


class Category(models.Model):

    name = MinimalField(_('name'), max_length=32)
    scope = models.CharField(_('scope'), max_length=32)

    class Meta:

        unique_together = (('name', 'scope'),)

    def __unicode__(self):

        return '%s' % self.name


class Logger(models.Model):
    """
    Implementation of simple logging in db.
    Used for example to registry obj version history.
    """
    # using simple field point to user (througth 'username' attribute) instead of one-to-one
    # relationship to preserve readable information when user was deleted.
    username = models.CharField(_('username'), max_length=32)
    event = models.TextField(_('event'), max_length=1024)
    timestamp = models.DateTimeField(_('timestamp'), auto_now_add=True)
    # point to obj using model name and id for a better lookup
    obj_model_name = models.CharField(_('obj model name'), max_length=32, blank=True, null=True)
    obj_id = models.IntegerField(_('obj id'), blank=True, null=True)

    def __unicode__(self):

        if self.obj_model_name and self.obj_id:
            return "%s %s (%s %s): %s" % (self.timestamp,
                                          self.username,
                                          elf.obj_model_name,
                                          self.obj_id,
                                          self.event)
        else:
            return "%s %s: %s" % (self.timestamp,
                                  self.username,
                                  self.event)

    @staticmethod
    def add(user, event, obj_model_name=None, obj_id=None, obj=None):

        if obj:
            obj_model_name = obj.model_name
            obj_id = obj.id
        return Logger(username=user.username,
                      event=event,
                      obj_model_name=obj_model_name,
                      obj_id=obj_id).save()

    @staticmethod
    def get(user=None, dt_start=None, dt_stop=None, obj_model_name=None, obj_id=None, obj=None):

        logs = Logger.objects.all()

        if obj:
            obj_model_name = obj.model_name
            obj_id = obj.id
        if obj_model_name and obj_id:
            logs = logs.filter(obj_model_name=obj_model_name, obj_id=obj_id)
        if dt_start and dt_stop:
            logs = logs.filter(timestamp__gt=dt_start, timestamp__lt=dt_stop)
        if user:
            logs.filter(username=user.username)

        logs = logs.order_by('-timestamp')

        return logs

    @staticmethod
    def clear(**kwargs):

        Logger.get(**kwargs).delete()

    @staticmethod
    def cycle(max_age=settings.LOGGING_AGE):

        Logger.get(dt_start=datetime.datetime(1,1,1),
                   dt_stop=datetime.datetime.now()-max_age).delete()


########################################################
##  BASE CLASSES FOR HIERARCHY AND LOCKING MANAGEMENT ##
########################################################


class Node(models.Model):
    """
    Hierarchy management class: implement a simple 'adjacency list' providing base
    methods for managing tree structure. Point to obj using model name and id and using
    getter property to give a faster reverse lookup and avoid use of GenericForeignKey.
    Inspired by django-treebeard app.
    """
    obj_model_name = models.CharField(_('obj model name'), max_length=32)
    obj_id = models.IntegerField(_('obj id'))
    parent = models.ForeignKey('self', verbose_name=_('parent'), related_name='children',
                               blank=True, null=True)
    position = models.IntegerField(_('position'))

    DUMMY_POSITION = -1

    FIRST = 'FIRST'
    LAST = 'LAST'
    NEXT = 'NEXT'
    PREVIOUS = 'PREVIOUS'

    class Meta:

        unique_together = (
            ('obj_model_name', 'obj_id'),
            ('parent', 'position'), # not working with multiple root
        )

    def __unicode__(self):

        return self.obj.name
        #return "node %s (hooking %s %s in %s position)" % (self.id,
        #                                                   self.obj_model_name,
        #                                                   self.obj_id,
        #                                                   self.position)

    # FACILITY FOR RETRIEVE HOOKED OBJ

    def _get_obj(self):

        return get_obj_or_none(obj_model_name=self.obj_model_name, obj_id=self.obj_id)

    def _set_obj(self, value):

        raise NotImplementedError("This action is permitted only at obj side.")

    def _del_obj(self):

        raise NotImplementedError("This action is permitted only at obj side.")

    obj = property(_get_obj, _set_obj, _del_obj)

    # TRAVERSAL METHODS

    def get_first_child(self):
        try:
            return self.children.all().order_by('position')[0]
        except IndexError:
            return None

    def get_last_child(self):

        try:
            return self.children.all().order_by('-position')[0]
        except IndexError:
            return None

    def has_children(self):

        return self.children.exists()

    def get_previous_sibling(self):

        try:
            return self.get_siblings().filter(position__lt=self.position).order_by('-position')[0]
        except IndexError:
            return None

    def get_next_sibling(self):

        try:
            return self.get_siblings().filter(position__gt=self.position).order_by('position')[0]
        except IndexError:
            return None

    def get_siblings(self):

        return self.__class__.objects.filter(parent=self.parent)

    def get_descendants(self):

        descendants = []
        for c in self.children.all():
            descendants.extend(c.get_descendants())
            descendants.append(c)
        return descendants

    def get_ancestors(self):

        ancestors = []
        node = self.parent
        while node:
            ancestors.insert(0, node)
            node = node.parent
        return ancestors

    def get_depth(self):

        return len(self.get_ancestors())

    def include(self, node):

        return (node == self) or (node in self.get_descendants())

    # CREATE-MOVE-DELETE-SWAP "PRIMITIVE" METHODS

    def free_pos(self, position):
        """
        Free a position shifting children from position,
        supported Node.FIRST and Node.LAST facility.
        """
        children = self.children

        # return first position
        if not children.exists():
            return 0

        # determinate position and check
        if position == self.LAST:
            return self.get_last_child().position + 1
        elif position == self.FIRST:
            position = 0
        elif not position >= 0:
            raise ValueError

        # shift
        for node in children.filter(position__gte=position):
            node.position += 1
            node.save()

        return position

    def fill_pos(self, position):
        """
        Fill a position shifting children from position.
        """
        children = self.children

        # nothing to fill or special case occourring in last obj deletion
        if not children.exists() or position > self.get_last_child().position:
            return

        # check
        if not position >= 0:
            raise ValueError

        # shift
        for node in children.filter(position__gt=position):
            node.position -= 1
            node.save()

    def swap_pos(self, node):
        """
        Swap position between self and provided node.
        """
        dummy = self.position
        self.position = node.position
        node.position = self.DUMMY_POSITION
        node.save()
        self.save()
        node.position = dummy
        node.save()

    def create_child(self, obj, position=None):
        """
        Free and return new node istance at position (default last) that hook obj.
        """
        # determinate position
        if position == None:
            position = self.LAST

        # free and return new node istance that hook obj
        position = self.free_pos(position)
        return self.__class__.objects.create(obj_model_name=obj.model_name,
                                             obj_id=obj.id,
                                             parent=self,
                                             position=position)

    def move_to(self, target, position=None):
        """
        Move node at position (default last).
        """
        if self.include(target):
            return False

        # determinate position
        if position == None:
            position = self.LAST

        # annotate old (postpone to avoid integrity error because node position restriction)
        old_parent = self.parent
        old_pos = self.position

        # set and save new
        self.parent = target
        self.position = target.free_pos(position)
        self.save()

        # re-organize old
        old_parent.fill_pos(old_pos)

    def delete(self):
        """
        Delete node.
        """
        # annotate old (postpone to avoid integrity error because node position restriction)
        old_parent = self.parent
        old_pos = self.position

        # delete
        super(Node, self).delete()

        # re-organize old
        old_parent.fill_pos(old_pos)

    def delete_recursive(self):

        for child in self.children.all():
            child.delete_recursive()
        self.delete()

    # FIX AND BULK OPERATIONS

    def _compact_positions(self):
        """
        Costrain all children's positions into adjacency values list.
        """
        for position, node in enumerate(self.children.all().order_by('position')):
            node.position = position
            node.save()

    def _recursive_dump(self):

        return (self, tuple(child._recursive_dump() for child in self.children.all()))

    @classmethod
    def dump_bulk(cls):

        return cls.get_root()._recursive_dump()

    @classmethod
    def get_roots(cls):

        return cls.objects.filter(parent=None)

    @classmethod
    def get_root(cls):

        try:
            return cls.get_roots()[0]
        except IndexError:
            raise ObjectDoesNotExist("Malformed tree.")

    @classmethod
    def fix_tree(cls):

        # TO-DO
        # compact positions for all nodes
        # other tasks
        raise NotImplementedError

    @classmethod
    def load_bulk(cls):

        raise NotImplementedError


class BaseNode(models.Model):
    """
    Wrapper model used as mix-in class for adding hierarchy functionality.
    """
    node = models.OneToOneField(Node,
                                verbose_name=_('node'),
                                related_name='+',
                                on_delete=models.SET_NULL,
                                blank=True,
                                null=True)
    class Meta:

        abstract = True

    # TRAVERSAL WRAPPER METHODS

    def get_parent(self):

        try:
            return self.node.parent.obj
        except AttributeError:
            return None

    def get_children(self):

        return [node.obj for node in self.node.children.all()]

    def get_root(self):

        return self.node.get_root().obj

    def get_first_child(self):

        try:
            return self.node.get_first_child().obj
        except AttributeError:
            return None

    def get_last_child(self):

        try:
            return self.node.get_last_child().obj
        except AttributeError:
            return None

    def get_previous_sibling(self):

        try:
            return self.node.get_previous_sibling().obj
        except AttributeError:
            return None

    def get_next_sibling(self):

        try:
            return self.node.get_next_sibling().obj
        except AttributeError:
            return None

    def get_descendants(self):

        return [node.obj for node in self.node.get_descendants()]

    def get_siblings(self):

        return [node.obj for node in self.node.get_siblings()]

    def get_ancestors(self):

        return [node.obj for node in self.node.get_ancestors()]

    def get_depth(self):

        return self.node.get_depth()

    def include(self, obj):

        return self.node.include(obj.node)

    def has_children(self):

        return self.node.has_children()


class Padlock(models.Model):
    """
    Implementation of simple exclusive/pessimistic locking.
    """
    owner = models.ForeignKey(User, verbose_name=_('owner'), on_delete=models.CASCADE,
                              related_name='owner')
    expire_dt = models.DateTimeField(_('expire datetime'))
    # point to obj using model name and id for a better lookup
    obj_model_name = models.CharField(_('obj model name'), max_length=32)
    obj_id = models.IntegerField(_('obj id'))

    class Meta:

        unique_together = (('obj_model_name', 'obj_id'),)

    @staticmethod
    def get_padlocks(owner=None):

        padlocks = Padlock.objects.all()
        if owner:
            if owner.is_anonymous():
                return None
            padlocks = padlocks.filter(owner=owner)
        return padlocks

    @staticmethod
    def get_locked_objs(owner=None):

        return [get_obj_or_none(p.obj_model_name, p.obj_id) for p in Padlock.get_padlocks(owner)]

    @staticmethod
    def clear(owner=None, check_expired=True):

        padlocks = Padlock.get_padlocks(owner=owner)
        if check_expired:
            padlocks = padlocks.filter(expire_dt__lt=datetime.datetime.now())
        padlocks.delete()

class BasePadlock(models.Model):
    """
    Wrapper model used to add locking functionality in mix-in class.
    """
    padlock = models.OneToOneField(Padlock, verbose_name=_('padlock'), on_delete=models.SET_NULL, blank=True, null=True)

    class Meta:

        abstract = True

    def manage_expired(self):

        if self.padlock.expire_dt < datetime.datetime.now():
            self.padlock.delete()
            self.padlock = None
            return True
        else:
            return False

    def is_locked(self, owner=None):

        if self.padlock and not self.manage_expired():
            if owner:
                return self.padlock.owner == owner
            else:
                return True
        else:
            return False

    def lock(self, user, fail_silently=False):

        if self.padlock and not self.manage_expired():
            if user != self.padlock.owner:
                raise LockError(_("Object locked by other user."), display=True)
            else:
                if not fail_silently:
                    raise LockError(_("Object already locked from some user."), display=True)
        else:
            self.padlock = Padlock.objects.create(owner=user,
                                                  expire_dt=datetime.datetime.now() + settings.LOCK_AGE,
                                                  obj_model_name=self.model_name,
                                                  obj_id=self.id)
            self.save()

    def unlock(self, user, fail_silently=False):

        if self.padlock and not self.manage_expired():
            if user != self.padlock.owner:
                raise LockError(_("Object locked by other user."), display=True)
            else:
                self.padlock.delete()
                self.padlock = None
        else:
            if not fail_silently:
                raise LockError(_("Object not locked."), display=True)


#####################################################
##                 BASE CLASSES                    ##
#####################################################


class BaseObj(models.Model):
    """
    Base model.
    """
    class Meta:

        abstract = True

    def __unicode__(self):

        return '%s %s' % (self.model_name, self.id)

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

        super(BaseObj, self).__init__(*args, **kwargs)
        self.model_name = self.__class__.__name__.lower()

    def get_size(self):

        size = 0
        for f in self._meta.fields:
            if isinstance(f, models.FileField):
                try:
                    size += getattr(self, f.name).size
                except ValueError, AttributeError:
                    pass
            else:
                size += getsizeof(getattr(self, f.name))

        return size

    def clone(self):
        """
        Return obj's clone: it's already committed in db because cloning files and relationship.
        """
        clone = self.__class__()

        for f in self._meta.fields:

            # exclude some fields from cloning
            if isinstance(f, models.AutoField) \
               or (f in self._meta.parents.values()) \
               or f.name in ('node', 'padlock'):
                continue

            # clone file field, force saving files
            elif isinstance(f, models.FileField):
                fd = getattr(self, f.name)
                fd._committed = False
                setattr(clone, f.name, fd)

            # clone no file field
            else:
                setattr(clone, f.name, getattr(self, f.name))

        clone.save()

        # now clone related, deferred for waiting new id
        for m in self._meta.many_to_many:
            for related in getattr(self, m.name).all():
                getattr(clone, m.name).add(related)

        return clone

    def delete_files(self, save=True):

        for f in self._meta.fields:
            if isinstance(f, models.FileField):
                file_field_instance = getattr(self, f.name)
                if file_field_instance:
                    file_field_instance.delete(save=save)

    def delete_file(self, field_name, save=True):
        """
        Default on removing obj is let files. Call this
        method for patch this behavior.
        """
        file_field_instance = getattr(self, field_name)
        if file_field_instance:
            file_field_instance.delete(save=save)


class BaseLockableObj(BaseObj, BasePadlock):
    """
    Base model: subclass this ensure locking and other base functionality.
    """
    class Meta:

        abstract = True


class BaseHierarchicObj(BaseLockableObj, BaseNode):
    """
    Base model: subclass this ensure hierarchy, locking and other base functionality.
    """
    class Meta:

        abstract = True

    def get_size(self, recursive=True):

        # get size
        size = super(BaseHierarchicObj, self).get_size()

        # apply recursive
        if recursive:
            for obj in self.get_descendants():
                size += obj.get_size()
        return size

    def add(self, obj, user, position=None, check_permissions=True, locking=True, logging=True):

        # check
        if check_permissions and not has_perm(user, "add %s to" % obj.model_name, obj=self):
            raise PermissionDenied(display=True)

        # lock
        if locking:
            self.lock(user, fail_silently=False)

        # insert obj in tree
        obj.node = self.node.create_child(obj, position=position)
        obj.save()

        # inherit from parent compatible permissions
        inherit_perms(obj, parent=self)

        # unlock
        if locking:
            self.unlock(user, fail_silently=False)

        # log
        if logging:
            Logger.add(user=user,
                       event='add',
                       obj_model_name=obj.model_name,
                       obj_id=obj.id)

    def paste_cut_recursive(self, obj, user, position=None, check_permissions=True, locking=True, logging=True):

        # check
        if obj.include(self):
            raise SelfInclusion(display=True)
        if check_permissions:
            if not has_perm(user, 'cut', obj=obj) or not has_perm(user, 'add %s to' % obj.model_name, obj=self):
                raise PermissionDenied(display=True)
        # lock
        if locking:
            self.lock(user, fail_silently=False)

        # move
        obj.node.move_to(self.node, position=position)

        # unlock
        if locking:
            self.unlock(user, fail_silently=False)

        # log
        if logging:
            Logger.add(user=user,
                       event='move',
                       obj_model_name=obj.model_name,
                       obj_id=obj.id)

    def paste_copy_recursive(self, obj, user, position=None, check_permissions=True, locking=True, logging=True):

        # check
        if obj.include(self):
            raise SelfInclusion(display=True)
        if check_permissions:
            if not has_perm(user, 'copy', obj=obj) or not has_perm(user, 'add %s to' % obj.model_name, obj=self):
                raise PermissionDenied(display=True)
        # lock
        if locking:
            self.lock(user, fail_silently=False)

        # clone
        clone = obj.clone()
        clone.node = self.node.create_child(clone, position=position)
        clone.padlock = None
        clone.owner = user
        clone.status = 'revision'
        clone.save()

        # inherit from parent compatible permissions
        inherit_perms(clone, parent=self)

        # logging here to maintain correct sequence in recursive copy
        if logging:
            Logger.add(user=user,
                       event='add',
                       obj_model_name=clone.model_name,
                       obj_id=clone.id)

        # repeat for obj's children, if error pass to next
        descendants_copied = True
        for child in obj.get_children():
            try:
                clone.paste_copy_recursive(child,
                                           user,
                                           position=child.node.position,
                                           check_permissions=True,
                                           locking=False,
                                           logging=logging)
            except (LockError, PermissionDenied):
                descendants_copied = False

        # unlock
        if locking:
            self.unlock(user, fail_silently=False)

        # raise if almost one error occouring in copying descendant objects
        if not descendants_copied:
            raise PartiallyExecuted(display=True)

    def delete_recursive(self, user, check_permissions=True, locking=True, logging=True):

        descendants_deleted = True

        # delete children, if error pass to next
        for child in self.get_children():
            try:
                child.delete_recursive(user,
                                       check_permissions=True,
                                       locking=True,
                                       logging=logging)
            except (LockError, PermissionDenied):
                descendants_deleted = False

        # delete itself after check remaining descendants, permissions and locking
        if descendants_deleted:
            if check_permissions:
                if not has_perm(user, 'delete', obj=self):
                    raise PermissionDenied(display=True)

            # lock
            if locking:
                self.lock(user, fail_silently=False)

            # remove all permissions on obj
            remove_all_specific_perm(self)

            # delete node and files (because django 1.3.x not delete files)
            self.node.delete()
            self.delete_files(save=False)

            # unlock
            if locking:
                self.unlock(user, fail_silently=False)

            # log
            if logging:
                Logger.add(user=user,
                           event='delete',
                           obj_model_name=self.model_name,
                           obj_id=self.id)

            # finally delete itself
            self.delete()

        # or raise if almost on error occouring in deleting descendant objects
        else:
            raise PartiallyExecuted(display=True)


STATUS_CHOICE = list_to_choices(settings.STATUSES)

class BaseContent(BaseHierarchicObj):
    """
    Base model for contents.
    """
    name = models.CharField(_('name'), max_length=64)
    title = models.CharField(_('title'), max_length=128, blank=True, null=True,
                             help_text=_("Max 128 characters, used also as title tag in head section."))
    keywords = models.TextField(_('keywords'), max_length=256, blank=True, null=True,
                                help_text=_("Max 256 characters, used as meta tag in head section."))
    description = models.TextField(_('description'), max_length=1024, blank=True, null=True,
                                   help_text=_("Max 1024 characters, used as meta tag in head section."))
    categories = models.ManyToManyField(Category, verbose_name=_('categories'), blank=True, null=True)
    dt_addition = models.DateTimeField(_('datetime addition'), auto_now_add=True,
                                       help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE)
    dt_modification = models.DateTimeField(_('datetime modification'), auto_now=True,
                                           help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE)
    dt_validity = models.DateTimeField(_('datetime validity'), blank=True, null=True,
                                       help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE)
    dt_expired = models.DateTimeField(_('datetime expired'), blank=True, null=True,
                                      help_text=_("Example format: %s.") % settings.DATETIME_EXAMPLE)
    owner = models.ForeignKey(User, verbose_name=_('owner'), on_delete=models.SET_NULL, blank=True, null=True)
    language = models.CharField(_('language'), choices=settings.LANGUAGES, max_length=8, blank=True, null=True)
    status = models.CharField(_('status'), choices=STATUS_CHOICE, default='revision', max_length=32)
    in_navigation = models.BooleanField(_('in navigation'), default=False)
    in_sitemap = models.BooleanField(_('in sitemap'), default=False)
    template = models.CharField(_('template for view'), max_length=128, blank=True, null=True)
    layout = models.CharField(_('layout for rendering'), max_length=64, blank=True, null=True)

    class Meta:

        abstract = True

    def change_status(self, status, user, recursive=False, check_permissions=True):

        all_statuses_changed = True

        if check_permissions and not has_perm(user, 'change status', obj=self) or self.is_locked():
            all_statuses_changed = False
        else:
            self.status = status
            self.save()

        if recursive:
            for d in self.get_descendants():
                if check_permissions and not has_perm(user, 'change status', obj=d) or d.is_locked():
                    all_statuses_changed = False
                else:
                    d.status = status
                    d.save()

        if not all_statuses_changed:
            raise PartiallyExecuted(display=True)

    def actualize(self, **kwargs):
        # subclass this method
        pass

    def get_history(self):

        qs = Logger.get(obj=self)
        try:
            dt_addition = qs.filter(event='add').order_by('-timestamp')[0].timestamp
            qs = qs.filter(timestamp__gte=dt_addition)[:settings.LIMIT_HISTORY]
        except IndexError:
            pass
        history = qs.values_list('username', 'timestamp', 'event')
        return history


####################################################
##              CONTENT CLASSES SET               ##
####################################################


class Article(BaseContent):

    subtitle = models.CharField(_('subtitle'), help_text=_("Max 256 characters."), max_length=256,
                                blank=True, null=True)
    introduction = models.TextField(_('introduction'), help_text=_("Max 4096 characters."),
                                    max_length=4096, blank=True, null=True)
    image = SmartImageField(_('image'), max_size=settings.UPLOAD_MAX_SIZE, upload_to="images",
                            blank=True, null=True)
    image_thumb = models.ImageField(_('image thumb'), upload_to="images", blank=True, null=True)
    image_caption = models.CharField(_('caption'), help_text=_("Max 256 characters."), max_length=256,
                                     blank=True, null=True)
    text = models.TextField(_('text'), help_text=_("Max 65536 characters."), max_length=65536)

    icon = "article.png"


class Event(BaseContent):

    text = models.TextField(_('text'), help_text=_("Max 4096 characters."), max_length=4096)
    location = models.CharField(_('location'), max_length=256, help_text=_("Where event happen."),
                                blank=True, null=True)
    map = models.URLField(_('map'), max_length=256, help_text=_("A googlemap (or other service) link."),
                          verify_exists=False, blank=True, null=True)
    dt_start = models.DateTimeField(_('datetime start'))
    dt_stop = models.DateTimeField(_('datetime stop'))
    referent_name =  models.CharField(_('referent name'), help_text=_("Max 32 characters."),
                                      max_length=32, blank=True, null=True)
    referent_email =  models.EmailField(_('referent email'), help_text=_("Max 32 characters."),
                                        max_length=32, blank=True, null=True)
    referent_cell =  models.CharField(_('referent cell'), help_text=_("Max 16 characters."),
                                      max_length=16, blank=True, null=True)

    icon = "event.png"


class Image(BaseContent):

    image = SmartImageField(_('image'), max_size=settings.UPLOAD_MAX_SIZE, upload_to="images")
    image_thumb = models.ImageField(_('image thumb'), blank=True, null=True, upload_to="images")
    notes = models.TextField(_('notes'), help_text=_("Max 16384 characters."), max_length=16384,
                             blank=True, null=True)

    icon = "image.png"


class File(BaseContent):

    file = SmartFileField(_('file'), max_size=settings.UPLOAD_MAX_SIZE, upload_to="files")
    notes = models.TextField(_('notes'), help_text=_("Max 16384 characters."), max_length=16384,
                             blank=True, null=True)
    download_immediately = models.BooleanField(_('download immediatly'), default=False)

    icon = "file.png"


class Link(BaseContent):

    link = models.CharField(_('link'), max_length=64,
                            help_text=_("Format example: http://www.domain.org or /view/article/3."))
    notes = models.TextField(_('notes'), help_text=_("Max 16384 characters."), max_length=16384,
                             blank=True, null=True)
    open_immediately = models.BooleanField(_('open immediately'), default=True)
    no_follow = models.BooleanField(_('no follow'), default=False)

    icon = "link.png"


class Page(BaseContent):

    text = models.TextField(_('text'), help_text=_("Max 65536 characters."), max_length=65536)

    icon = "page.png"


class Html(BaseContent):

    html = models.TextField (_('html'), help_text=_("Max 65536 characters."), max_length=65536)

    icon = "html.png"


class Folder(BaseContent):

    introduction = models.TextField(_('introduction'), help_text=_("Max 16384 characters."),
                                    max_length=16384, blank=True, null=True)
    notes = models.TextField(_('notes'), help_text=_("Max 16384 characters."), max_length=16384,
                             blank=True, null=True)
    image = SmartImageField(_('image'), max_size=settings.UPLOAD_MAX_SIZE, upload_to="images",
                            blank=True, null=True)
    image_thumb = models.ImageField(_('image thumb'), upload_to="images", blank=True, null=True)
    max_size = models.BigIntegerField(_('max size'), blank=True, null=True)

    icon = "folder.png"

    def get_objs_list(self, user=None, caching=False, check_view_perms=True):

        # check caching
        if caching:
            cache_key = 'folder_objs_with_%s_%s' % (self.model_name, self.id)
            objs = cache.get(cache_key)
        else:
            objs = None

        # if not cache get objs
        if objs == None:
            objs = []

            # check permissions, guess and attach preview template path
            for o in self.get_children():
                if check_view_perms and not has_perm(user, 'view', obj=o):
                    continue
                o.template_path = "%s/preview_%s.html" % (o.__module__.split('.')[0], o.model_name)
                objs.append(o)

        # cache
        if caching:
            cache.set(cache_key, objs)

        return objs

    def get_contents_list(self, user=None, language=None, caching=False, check_view_perms=True):

        # check caching
        if caching:
            cache_key = 'folder_contents_with_%s_%s_%s' % (self.model_name, self.id, language)
            contents = cache.get(cache_key)
        else:
            contents = None

        # if not cache get contents
        if contents == None:
            contents = []

            # check permissions and language and validity time, limit content types, guess and attach preview template path
            now = datetime.datetime.now()
            for c in self.get_children():
                if settings.LANGUAGE_RESTRICTED and c.language and language and c.language != language:
                    continue
                if check_view_perms and not has_perm(user, 'view', obj=c):
                    continue
                if not isinstance(c, BaseContent):
                    continue
                if c.dt_validity and now < c.dt_validity or c.dt_expired and now > c.dt_expired:
                    continue
                c.template_path = "%s/preview_%s.html" % (c.__module__.split('.')[0], c.model_name)
                contents.append(c)

        # cache
        if caching:
            cache.set(cache_key, contents)

        return contents

    def actualize(self, **kwargs):

        self.contents = self.get_contents_list(user=kwargs['user'],
                                               language=kwargs['language'],
                                               caching=kwargs['caching'],
                                               check_view_perms=kwargs['check_view_perms'])
        super(Folder, self).actualize(**kwargs)


###########################################
##         SLOT, GRID, LAYOUT            ##
###########################################


class Slot(object):
    """
    Hook an obj or a plugin, permitting alternative templating and styling.
    Calculating all possible now and defer the actualization.
    """
    def __init__(self,
                 type_,
                 obj_model_name=None,
                 obj_id=None,
                 plugin_name=None,
                 template_path=None,
                 css_name=None):

        self.type = type_
        self.css_name = css_name
        self.loaded = False

        # check type and set slug name
        if self.type == 'obj':
            self.obj_model_name = obj_model_name
            self.obj_id = obj_id
            self.slug_name = "%s%s" % (obj_model_name, obj_id)
        elif self.type == 'plugin':
            self.plugin_name = self.slug_name = plugin_name
            try:
                self._load()
            except ImportError:
                pass
        else:
            raise ValueError("Slot type not supported.")

        # get template path from template id or from plugin's name, other task to get template
        # path are deferred because obj.template_path attribute need actualization
        if not template_path:
            self.template_path = get_template_path('view', obj_model_name or plugin_name)
        else:
            self.template_path = template_path

    def _load(self):

        # get plugin from plugin name
        path, __ = settings.PLUGINS[self.plugin_name]
        mod = __import__(path, None, None, 'plugins')
        self.plugin = getattr(mod, self.plugin_name)
        self.loaded = True

    def actualize(self, **kwargs):

        # is obj
        if self.type == 'obj':
            try:
                self.obj = get_obj_or_404(self.obj_model_name, self.obj_id)
                if kwargs['check_view_perms'] and not has_perm(kwargs['user'], 'view', obj=self.obj):
                    return
                self.obj.actualize(**kwargs)
            except:
                self.obj = None

        # is plugin
        elif self.type == 'plugin':
            # maybe having a circular import error in slot initialization,
            # because module not yet availeble: tray againg here at runtime
            if not self.loaded:
                self._load()
            # then actualize plugin, if exist, else raise
            self.plugin_dict = self.plugin(**kwargs)

        # is nothing
        else:
            raise ValueError("Slot type not supported.")


class Grid(object):
    """
    Mixin class provinding slot add-remove management and optional alternative structure
    representation. Attribute grid must be defined in derived or sibling class, and than
    is possible to have dict and list representation.
    """
    def __init__(self, *args, **kwargs):

        self.dict = None
        self.list = None

    def actualize(self, **kwargs):

        for row in self.grid:
            for slot in row:
                slot.actualize(**kwargs)

    def add_slot(self, slot, y, x):

        self.grid[int(y)].insert(int(x), slot)
        if self.dict is not None:
            self._init_dict()
        if self.list is not None:
            self._init_list()

    def remove_slot(self):

        slot = self.grid[int(y)].pop(int(x))
        if self.list is not None:
            self.list.remove(slot)
        if self.dict is not None:
            del(self.dict[slot.slug_name])

    def add_row(self, y):

        self.grid.insert(int(y), [])

    def remove_row(self, y):

        self.grid.pop(int(y))

    def _init_dict(self):

        self.dict = {}
        for row in self.grid:
            for slot in row:
                self.dict[slot.slug_name] = slot

    def _init_list(self):

        self.list = []
        for row in self.grid:
            for slot in row:
                self.list.append(slot)

    def as_dict(self):

        if self.dict is None:
            self._init_dict()
        return self.dict

    def as_list(self):

        if self.list is None:
            self._init_list()
        return self.list


class Layout(Grid):

    def __init__(self, name, template_path, slots):
        """
        Positione slots in a grid structure from
        dict-tuples structure and init dict and list.
        """
        self.name = name
        self.template_path = template_path
        self.grid = []

        for y in slots:
            row = []
            for x in y:
                if x[0] == 'obj':
                    type_, obj_model_name, obj_id, template_path = x
                    slot = Slot(type_=type_,
                                obj_model_name=obj_model_name,
                                obj_id=obj_id,
                                template_path=template_path)
                elif x[0] == 'plugin':
                    type_, plugin_name, template_path = x
                    slot = Slot(type_=type_,
                                plugin_name=plugin_name,
                                template_path=template_path)
                else:
                    raise ValueError("Slot type not supported.")

                row.append(slot)
            self.grid.append(row)

        super(Layout, self).__init__()

        self._init_dict()
        self._init_list()


# preinstantiate layouts from settings layouts definitions
LAYOUTS = {}
for name, tuples in settings.LAYOUTS.items():
    template_path = tuples[0]
    slots = tuples[1:]
    LAYOUTS[name] = Layout(name, template_path, slots)


################################
##         COLLAGE            ##
################################


DEFAULT_COLLAGE_PICKLED = pickle.dumps([[]], 0)

class Collage(BaseContent, Grid):

    grid = BlobField(_('grid'), default=DEFAULT_COLLAGE_PICKLED)
    render_as_layout = models.BooleanField(_('render as layout'), default=False)

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

        Grid.__init__(self, *args, **kwargs)
        BaseContent.__init__(self, *args, **kwargs)

    def actualize(self, **kwargs):

        return Grid.actualize(self, **kwargs)


####################################################
##                   COLLECTOR                    ##
####################################################


DATETIME_OPERATOR_CHOICES = list_to_choices(('minor of', 'major of'))
DELTA_YEAR = list_to_choices(range(-10, 10))
DELTA_MONTH = list_to_choices(range(-12, 12))
DELTA_DAY = list_to_choices(range(-31, 31))
DELTA_HOUR = list_to_choices(range(-24, 24))
DELTA_MIN = list_to_choices((-45,-30,-15,0,15,30,45))

class Collector(BaseContent):

    # base
    subtitle = models.CharField(_('subtitle'), help_text=_("Max 256 characters."), max_length=256,
                                blank=True, null=True)
    introduction = models.TextField(_('introduction'), help_text=_("Max 4096 characters."),
                                    max_length=4096, blank=True, null=True)
    order_field = models.CharField(_('order field'), max_length=32)
    order_direction = models.CharField(_('order direction'), default='crescent', max_length=32,
                                       choices=(('crescent','crescent'),('decrescent','decrescent')))
    limit = models.IntegerField(_('limit'), blank=True, null=True)

    # datetime criterion
    datetime_criterion = models.BooleanField(_('datetime criterion'), default=False)
    param_dt_field = models.CharField(_('datetime field'), max_length=32)
    param_dt_operator = models.CharField(_('datetime operator'), choices=DATETIME_OPERATOR_CHOICES,
                                         default='minor of', max_length=32)
    param_delta_year = models.IntegerField(_('delta year'), choices=DELTA_YEAR, default='0',
                                           max_length=16)
    param_delta_month = models.IntegerField(_('delta month'), choices=DELTA_MONTH, default='0',
                                            max_length=16)
    param_delta_day= models.IntegerField(_('delta day'), choices=DELTA_DAY, default='0',
                                         max_length=16)

    # category criterion
    category_criterion = models.BooleanField(_('category criterion'), default=False)
    param_categories = models.ManyToManyField(Category, verbose_name=_('categories'),
                                              related_name='param_categories', blank=True, null=True)

    # contenttype criterion
    contenttype_criterion = models.BooleanField(_('contenttype criterion'), default=False)
    param_contenttypes = models.ManyToManyField(ContentType, verbose_name=_('contenttypes'),
                                                blank=True, null=True)

    # localization criterion
    localization_criterion = models.BooleanField(_('localization criterion'), default=False)
    param_folders = models.ManyToManyField(Folder, verbose_name=_('folders'), blank=True, null=True)
    param_recursion = models.BooleanField(_('recursion'), default=False)

    # status criterion
    status_criterion = models.BooleanField(_('status criterion'), default=False)
    param_statuses = models.CharField(_('statuses'), choices=STATUS_CHOICE, default='public',
                                      max_length=32)

    def get_contents_list(self, user=None, language=None, caching=False, check_view_perms=True):

        # check caching
        if caching:
            cache_key = 'collection_with_%s_%s' % (self.id, language)
            cached = cache.get(cache_key)
            if cached:
                return  cached

        # PHASE 1
        if self.datetime_criterion:
            ref = datetime.datetime.now()
            date_time = ref + datetime.timedelta(days=self.param_delta_year*365 +
                                                      self.param_delta_month*30 +
                                                      self.param_delta_day)
        contents_phase1 = []

        # if localization criterion specified evaluate folders children with others criteria
        if self.localization_criterion:
            children_or_descendants = []

            # localization criterion
            for f in self.param_folders.all():
                if self.param_recursion:
                    children_or_descendants.extend(f.get_descendants())
                else:
                    children_or_descendants.extend(f.get_children())

            for cd in children_or_descendants:

                # model names criterion
                if self.contenttype_criterion and cd.model_name not in self.param_contenttypes.all().values_list('model', flat=True):
                    continue

                # status criterion
                if self.status_criterion and cd.status not in self.param_statuses:
                    continue

                # datetime criterion
                if self.datetime_criterion:
                    val = getattr(cd, self.param_dt_field, None)
                    if self.param_dt_operator == 'minor of' and val and not (val < date_time):
                        continue
                    elif self.param_dt_operator == 'major of' and val and not (val > date_time):
                        continue

                # category criterion
                if self.category_criterion and not (set(cd.categories.all()) & set(self.param_categories.all())):
                    continue
                contents_phase1.append(cd)

        # if not localization criterion specified apply queryset filtering
        else:

            # model names criterion
            if self.contenttype_criterion:
                cts = self.param_contenttypes.all()
            else:
                cts = ContentType.objects.filter(model__in=settings.COLLECTIBLE)

            for c in cts:
                queryset = c.model_class().objects.all()

                # status criterion
                if self.status_criterion:
                    queryset = queryset.filter(status=self.param_statuses)

                # datetime criterion
                if self.datetime_criterion:
                    if self.param_dt_operator == 'minor of':
                        op = 'lte'
                    elif self.param_dt_operator == 'major of':
                        op = 'gte'
                    queryset = queryset.filter(**{"%s__%s" % (self.param_dt_field, op):date_time})

                # category criterion
                if self.category_criterion:
                    queryset = queryset.filter(categories__name__in=self.param_categories.all().values_list('name', flat=True)) # errore: DOPPIO

                contents_phase1.extend(list(queryset))

        # PHASE 2

        contents_phase2 = []
        count = 0

        # check permissions and language, limit contents, guess and attach preview template path
        for c in contents_phase1:
            if check_view_perms and not has_perm(user, 'view', obj=c):
                continue
            elif settings.LANGUAGE_RESTRICTED and c.language and language and c.language != language:
                continue
            c.template_path = "%s/preview_%s.html" % (c.__module__.split('.')[0], c.model_name)
            contents_phase2.append(c)
            count += 1
            if count == self.limit: break

        # sort as order_field
        reverse = (self.order_direction == 'decrescent')
        try:
            contents_phase2.sort(key=lambda c: getattr(c, self.order_field), reverse=reverse)
        except:
            pass

        # cache
        if caching:
            cache.set(cache_key, contents_phase2)

        return contents_phase2

    def actualize(self, **kwargs):

        self.contents = self.get_contents_list(user=kwargs['user'],
                                               language=kwargs['language'],
                                               caching=kwargs['caching'],
                                               check_view_perms=kwargs['check_view_perms'])

        super(Collector, self).actualize(**kwargs)