Source

zine-maintenance / zine / models.py

   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
# -*- coding: utf-8 -*-
"""
    zine.models
    ~~~~~~~~~~~

    The core models and query helper functions.

    :copyright: (c) 2009 by the Zine Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from math import ceil, log
from datetime import date, datetime, timedelta
from urlparse import urljoin

from werkzeug.exceptions import NotFound

from zine.database import users, categories, posts, post_links, \
     post_categories, post_tags, tags, comments, groups, group_users, \
     privileges, user_privileges, group_privileges, db
from zine.utils import zeml
from zine.utils.text import gen_slug, build_tag_uri, increment_string
from zine.utils.pagination import Pagination
from zine.utils.crypto import gen_pwhash, check_pwhash
from zine.utils.http import make_external_url
from zine.privileges import Privilege, _Privilege, privilege_attribute, \
     add_admin_privilege, MODERATE_COMMENTS, ENTER_ADMIN_PANEL, BLOG_ADMIN, \
     VIEW_DRAFTS
from zine.application import get_application, get_request, url_for


#: all kind of states for a post
STATUS_DRAFT = 1
STATUS_PUBLISHED = 2

#: Comment Status
COMMENT_MODERATED = 0
COMMENT_UNMODERATED = 1
COMMENT_BLOCKED_USER = 2
COMMENT_BLOCKED_SPAM = 3
COMMENT_BLOCKED_SYSTEM = 4

#: moderation modes
MODERATE_NONE = 0
MODERATE_ALL = 1
MODERATE_UNKNOWN = 2


class _ZEMLContainer(object):
    """A mixin for objects that have ZEML markup stored."""

    parser_reason = None

    @property
    def parser_missing(self):
        """If the parser for this post is not available this property will
        be `True`.  If such as post is edited the text area is grayed out
        and tells the user to reinstall the plugin that provides that
        parser.  Because it doesn't know the name of the plugin, the
        preferred was is telling it the parser which is available using
        the `parser` property.
        """
        app = get_application()
        return self.parser not in app.parsers

    def _get_parser(self):
        if self.parser_data is not None:
            return self.parser_data.get('parser')

    def _set_parser(self, value):
        if self.parser_data is None:
            self.parser_data = {}
        self.parser_data['parser'] = value

    parser = property(_get_parser, _set_parser, doc="The name of the parser.")
    del _get_parser, _set_parser

    @property
    def body(self):
        """The body as ZEML element."""
        if self.parser_data is not None:
            return self.parser_data.get('body')

    def _parse_text(self, text):
        from zine.parsers import parse
        self.parser_data['body'] = parse(text, self.parser, 'post')

    def _get_text(self):
        return self._text

    def _set_text(self, value):
        if self.parser_data is None:
            self.parser_data = {}
        self._text = value
        self._parse_text(value)

    text = property(_get_text, _set_text, doc="The raw text.")
    del _get_text, _set_text

    def find_urls(self):
        """Iterate over all urls in the text.  This will only work if the
        parser for this post is available, otherwise an exception is raised.
        The URLs returned are absolute URLs.
        """
        from zine.parsers import parse
        if self.parser_missing:
            raise TypeError('parser is missing, urls cannot be looked up.')
        found = set()
        this_url = url_for(self, _external=True)
        tree = parse(self.text, self.parser, 'linksearch')
        for node in tree.query('a[href]'):
            href = urljoin(this_url, node.attributes['href'])
            if href not in found:
                found.add(href)
                yield href


class _ZEMLDualContainer(_ZEMLContainer):
    """Like the ZEML mixin but with intro and body sections."""

    def _parse_text(self, text):
        from zine.parsers import parse
        self.parser_data['intro'], self.parser_data['body'] = \
            zeml.split_intro(parse(text, self.parser, self.parser_reason))

    @property
    def intro(self):
        """The intro as zeml element."""
        if self.parser_data is not None:
            return self.parser_data.get('intro')


class UserQuery(db.Query):
    """Add some extra query methods to the user object."""

    def get_nobody(self):
        return AnonymousUser()

    def authors(self):
        return self.filter_by(is_author=True)


class User(object):
    """Represents an user.

    If you change something on this model, even default values, keep in mind
    that the websetup does not use this model to create the admin account
    because at that time the Zine system is not yet ready. Also update
    the code in `zine.websetup.WebSetup.start_setup`.
    """

    query = db.query_property(UserQuery)
    is_somebody = True

    def __init__(self, username, password, email, real_name=u'',
                 description=u'', www=u'', is_author=False):
        self.username = username
        if password is not None:
            self.set_password(password)
        else:
            self.disable()
        self.email = email
        self.www = www
        self.real_name = real_name
        self.description = description
        self.extra = {}
        self.display_name = u'$username'
        self.is_author = is_author

    @property
    def is_manager(self):
        return self.has_privilege(ENTER_ADMIN_PANEL)

    @property
    def is_admin(self):
        return self.has_privilege(BLOG_ADMIN)

    def _set_display_name(self, value):
        self._display_name = value

    def _get_display_name(self):
        from string import Template
        return Template(self._display_name).safe_substitute(
            username=self.username,
            real_name=self.real_name
        )

    display_name = property(_get_display_name, _set_display_name)
    own_privileges = privilege_attribute('_own_privileges')

    @property
    def privileges(self):
        """A read-only set with all privileges."""
        result = set(self.own_privileges)
        for group in self.groups:
            result.update(group.privileges)
        return frozenset(result)

    def has_privilege(self, privilege):
        """Check if the user has a given privilege.  If the user has the
        BLOG_ADMIN privilege he automatically has all the other privileges
        as well.
        """
        return add_admin_privilege(privilege)(self.privileges)

    def set_password(self, password):
        self.pw_hash = gen_pwhash(password)

    def check_password(self, password):
        if self.pw_hash == '!':
            return False
        return check_pwhash(self.pw_hash, password)

    def disable(self):
        self.pw_hash = '!'

    @property
    def disabled(self):
        return self.pw_hash == '!'

    def get_url_values(self):
        if self.is_author:
            return 'blog/show_author', {
                'username': self.username
            }
        return self.www or '#'

    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.username
        )


class Group(object):
    """Wraps the group table."""

    def __init__(self, name):
        self.name = name

    privileges = privilege_attribute('_privileges')

    def has_privilege(self, privilege):
        return add_admin_privilege(privilege)(self.privileges)

    def get_url_values(self):
        # TODO: a public view is missing!
        return 'admin/edit_group', {'group_id': self.id}

    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.name
        )


class AnonymousUser(User):
    """Fake model for anonymous users."""
    id = -1
    is_somebody = is_author = False
    display_name = 'Nobody'
    real_name = description = username = ''
    own_privileges = privileges = \
        property(lambda x: frozenset())

    def __init__(self):
        pass

    def __nonzero__(self):
        return False

    def check_password(self, password):
        return False


class PostQuery(db.Query):
    """Add some extra methods to the post model."""

    def lightweight(self, deferred=None, lazy=('comments',)):
        """Send a lightweight query which deferes some more expensive
        things such as comment queries or even text and parser data.
        """
        args = map(db.lazyload, lazy or ())
        if deferred:
            args.extend(map(db.defer, deferred))
        # undefer the _comment_count query which is used by comment_count
        # for lightweight post objects.  See Post.comment_count for more
        # details.
        if lazy and 'comments' in lazy:
            args.append(db.undefer('_comment_count'))
        return self.options(*args)

    def type(self, content_type):
        """Filter all posts by a given type."""
        return self.filter_by(content_type=content_type)

    def for_index(self):
        """Return all the types for the index."""
        types = get_application().cfg['index_content_types']
        if len(types) == 1:
            return self.filter_by(content_type=types[0].strip())
        return self.filter(Post.content_type.in_([x.strip() for x in types]))

    def published(self, ignore_privileges=None):
        """Return a queryset for only published posts."""
        return self.filter(
            (Post.status == STATUS_PUBLISHED) &
            (Post.pub_date <= datetime.utcnow())
        )

    def drafts(self, ignore_user=False, user=None):
        """Return a query that returns all drafts for the current user.
        or the user provided or no user at all if `ignore_user` is set.
        """
        if user is None and not ignore_user:
            req = get_request()
            if req and req.user:
                user = req.user
        query = self.filter(Post.status == STATUS_DRAFT)
        if user is not None:
            query = query.filter(Post.author_id == user.id)
        return query

    def get_list(self, endpoint=None, page=1, per_page=None,
                 url_args=None, raise_if_empty=True):
        """Return a dict with pagination, the current posts, number of pages,
        total posts and all that stuff for further processing.
        """
        if per_page is None:
            app = get_application()
            per_page = app.cfg['posts_per_page']

        # send the query
        offset = per_page * (page - 1)
        postlist = self.order_by(Post.pub_date.desc()) \
                       .offset(offset).limit(per_page).all()

        # if raising exceptions is wanted, raise it
        if raise_if_empty and (page != 1 and not postlist):
            raise NotFound()

        pagination = Pagination(endpoint, page, per_page,
                                self.count(), url_args)

        return {
            'pagination':       pagination,
            'posts':            postlist
        }

    def get_archive_summary(self, detail='months', limit=None,
                            ignore_privileges=False):
        """Query function to get the archive of the blog. Usually used
        directly from the templates to add some links to the sidebar.
        """
        # XXX: currently we also return months without articles in it.
        # other blog systems do not, but because we use sqlalchemy we have
        # to go with the functionality provided.  Currently there is no way
        # to do date truncating in a database agnostic way.  When this is done
        # ignore_privileges should no longer be a noop
        last = self.filter(Post.pub_date != None) \
                   .order_by(Post.pub_date.asc()).first()
        now = datetime.utcnow()

        there_are_more = False
        result = []

        if last is not None:
            now = date(now.year, now.month, now.day)
            oldest = date(last.pub_date.year, last.pub_date.month,
                          last.pub_date.day)
            result = [now]

            there_are_more = False
            if detail == 'years':
                now, oldest = [x.replace(month=1, day=1) for x in now, oldest]
                while True:
                    now = now.replace(year=now.year - 1)
                    if now < oldest:
                        break
                    result.append(now)
                else:
                    there_are_more = True
            elif detail == 'months':
                now, oldest = [x.replace(day=1) for x in now, oldest]
                while limit is None or len(result) < limit:
                    if not now.month - 1:
                        now = now.replace(year=now.year - 1, month=12)
                    else:
                        now = now.replace(month=now.month - 1)
                    if now < oldest:
                        break
                    result.append(now)
                else:
                    there_are_more = True
            elif detail == 'days':
                while limit is None or len(result) < limit:
                    now = now - timedelta(days=1)
                    if now < oldest:
                        break
                    result.append(now)
                else:
                    there_are_more = True
            else:
                raise ValueError('detail must be years, months, or days')

        return {
            detail:     result,
            'more':     there_are_more,
            'empty':    not result
        }

    def latest(self, ignore_privileges=False):
        """Filter for the latest n posts."""
        return self.published(ignore_privileges=ignore_privileges)

    def date_filter(self, year, month=None, day=None):
        """Filter all the items that match the given date."""
        if month is None:
            return self.filter(
                (Post.pub_date >= datetime(year, 1, 1)) &
                (Post.pub_date < datetime(year + 1, 1, 1))
            )
        elif day is None:
            return self.filter(
                (Post.pub_date >= datetime(year, month, 1)) &
                (Post.pub_date < (month == 12 and
                               datetime(year + 1, 1, 1) or
                               datetime(year, month + 1, 1)))
            )
        return self.filter(
            (Post.pub_date >= datetime(year, month, day)) &
            (Post.pub_date < datetime(year, month, day) +
                             timedelta(days=1))
        )

    def search(self, query):
        """Search for posts by a query."""
        # XXX: use a sophisticated search
        q = self
        for word in query.split():
            q = q.filter(
                posts.c.body.like('%%%s%%' % word) |
                posts.c.intro.like('%%%s%%' % word) |
                posts.c.title.like('%%%s%%' % word)
            )
        return q.all()


class Post(_ZEMLDualContainer):
    """Represents one blog post."""

    query = db.query_property(PostQuery)
    parser_reason = 'post'

    def __init__(self, title, author, text, slug=None, pub_date=None,
                 last_update=None, comments_enabled=True,
                 pings_enabled=True, status=STATUS_PUBLISHED,
                 parser=None, uid=None, content_type='entry'):
        app = get_application()
        self.content_type = content_type
        self.title = title
        self.author = author
        if parser is None:
            parser = app.cfg['default_parser']

        self.parser = parser
        self.text = text or u''
        self.extra = {}

        self.comments_enabled = comments_enabled
        self.pings_enabled = pings_enabled
        self.status = status

        # set times now, they depend on status being set
        self.touch_times(pub_date)
        if last_update is not None:
            self.last_update = last_update

        # now bind the slug for which we need the times set.
        self.bind_slug(slug)

        # generate a UID if none is given
        if uid is None:
            uid = build_tag_uri(app, self.pub_date, content_type, self.slug)
        self.uid = uid

    @property
    def _privileges(self):
        return get_application().content_type_privileges[self.content_type]

    @property
    def EDIT_OWN_PRIVILEGE(self):
        """The edit-own privilege for this content type."""
        return self._privileges[1]

    @property
    def EDIT_OTHER_PRIVILEGE(self):
        """The edit-other privilege for this content type."""
        return self._privileges[2]

    @property
    def root_comments(self):
        """Return only the comments for this post that don't have a parent."""
        return [x for x in self.comments if x.parent is None]

    @property
    def visible_comments(self):
        """Return only the comments for this post that are visible to
        the user.
        """
        return [x for x in self.comments if x.visible]

    @property
    def visible_root_comments(self):
        """Return only the comments for this post that are visible to
        the user and that don't have a parent.
        """
        return [x for x in self.comments if x.visible and x.parent is None]

    @property
    def comment_count(self):
        """The number of visible comments."""
        req = get_request()

        # if the model was loaded with .lightweight() there are no comments
        # but a _comment_count we can use.
        if not db.attribute_loaded(self, 'comments'):
            return self._comment_count

        # otherwise the comments are already available and we can savely
        # filter it.
        if req.user.is_manager:
            return len(self.comments)
        return len([x for x in self.comments if not x.blocked])

    @property
    def comment_feed_url(self):
        """The link to the comment feed."""
        return make_external_url(self.slug.rstrip('/') + '/feed.atom')

    @property
    def is_draft(self):
        """True if this post is unpublished."""
        return self.status == STATUS_DRAFT

    def set_auto_slug(self):
        """Generate a slug for this post."""
        cfg = get_application().cfg
        slug = gen_slug(self.title)
        if not slug:
            slug = self.pub_date.strftime('%H:%M')
        prefix = cfg['blog_url_prefix'].lstrip('/')
        if prefix:
            prefix += '/'
        if cfg['fixed_url_date_digits']:
            date_pattern = '%04d/%02d/%02d'
        else:
            date_pattern = '%d/%d/%d'
        full_slug = u'%s%s/%s' % (
            prefix,
            date_pattern % (
                self.pub_date.year,
                self.pub_date.month,
                self.pub_date.day,
            ),
            slug
        )

        if full_slug != self.slug:
            while Post.query.autoflush(False).filter_by(slug=full_slug) \
                      .limit(1).count():
                full_slug = increment_string(full_slug)
            self.slug = full_slug

    def touch_times(self, pub_date=None):
        """Touches the times for this post.  If the pub_date is given the
        `pub_date` is changed to the given date.  If it's not given the
        current time is assumed if the post status is set to published,
        otherwise it's set to `None`.

        Additionally the `last_update` is always set to now.
        """
        now = datetime.utcnow()
        if pub_date is None and self.status == STATUS_PUBLISHED:
            pub_date = now
        self.pub_date = pub_date
        self.last_update = now

    def bind_slug(self, slug=None):
        """Binds a new slug to the post.  If the slug is `None`/empty a new
        automatically generated slug is created.  Otherwise that slug is
        used and assigned.
        """
        if not slug:
            self.set_auto_slug()
        else:
            self.slug = slug

    def bind_tags(self, tags):
        """Rebinds the tags to a list of tags (strings, not tag objects)."""
        current_map = dict((x.name, x) for x in self.tags)
        currently_attached = set(x.name for x in self.tags)
        new_tags = set(tags)

        # delete outdated tags
        for name in currently_attached.difference(new_tags):
            self.tags.remove(current_map[name])

        # add new tags
        for name in new_tags.difference(currently_attached):
            self.tags.append(Tag.get_or_create(name))

    def bind_categories(self, categories):
        """Rebinds the categories to the list passed.  The list of objects
        must be a list of category objects.
        """
        currently_attached = set(self.categories)
        new_categories = set(categories)

        # delete outdated categories
        for category in currently_attached.difference(new_categories):
            self.categories.remove(category)

        # attach new categories
        for category in new_categories.difference(currently_attached):
            self.categories.append(category)

    def can_edit(self, user=None):
        """Checks if the given user (or current user) can edit this post."""
        if user is None:
            user = get_request().user

        return (
            user.has_privilege(self.EDIT_OTHER_PRIVILEGE) or
            (self.author == user and
             user.has_privilege(self.EDIT_OWN_PRIVILEGE))
        )

    def can_read(self, user=None):
        """Check if the current user or the user provided can read-access
        this post. If there is no user there must be a request object
        for this thread defined.
        """
        # published posts are always accessible
        if self.status == STATUS_PUBLISHED and \
           self.pub_date <= datetime.utcnow():
            return True

        if user is None:
            user = get_request().user

        # users that are allowed to look at drafts may pass
        if user.has_privilege(VIEW_DRAFTS):
            return True

        # if we have the privilege to edit other entries or if we are
        # a blog administrator we can always look at posts.
        if user.has_privilege(self.EDIT_OTHER_PRIVILEGE):
            return True

        # otherwise if the user has the EDIT_OWN_PRIVILEGE and the
        # author of the post, he may look at it as well
        if user.id == self.author_id and \
           user.has_privilege(self.EDIT_OWN_PRIVILEGE):
            return True

        return False

    @property
    def is_published(self):
        """`True` if the post is visible for everyone."""
        return self.can_read(AnonymousUser())

    @property
    def is_scheduled(self):
        """True if the item is scheduled for appearing."""
        return self.status == STATUS_PUBLISHED and \
               self.pub_date > datetime.utcnow()

    def get_url_values(self):
        return self.slug

    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.title
        )


class PostLink(object):
    """Represents a link in a post.  This can be used for podcasts or other
    resources that require ``<link>`` categories.
    """

    def __init__(self, post, href, rel='alternate', type=None, hreflang=None,
                 title=None, length=None):
        self.post = post
        self.href = href
        self.rel = rel
        self.type = type
        self.hreflang = hreflang
        self.title = title
        self.length = length

    def as_dict(self):
        """Return the values as dict.  Useful for feed building."""
        result = {'href': href}
        for key in 'rel', 'type', 'hreflang', 'title', 'length':
            value = getattr(self, key, None)
            if value is not None:
                result[key] = value
        return result

    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.href
        )


class CategoryQuery(db.Query):
    """Also categories have their own manager."""

    def get_or_create(self, slug, name=None):
        """Get the category for this slug or create it if it does not exist."""
        category = self.filter_by(slug=slug).first()
        if category is None:
            if name is None:
                name = slug
            category = Category(name, slug=slug)
        return category


class Category(object):
    """Represents a category."""

    query = db.query_property(CategoryQuery)

    def __init__(self, name, description='', slug=None):
        self.name = name
        if slug is None:
            self.set_auto_slug()
        else:
            self.slug = slug
        self.description = description

    def set_auto_slug(self):
        """Generate a slug for this category."""
        full_slug = gen_slug(self.name)
        if not full_slug:
            # if slug generation failed we select the highest category
            # id as base for slug generation.
            category = Category.query.autoflush(False) \
                               .order_by(Category.id.desc()).first()
            full_slug = unicode(category and category.id or u'1')
        if full_slug != self.slug:
            while Category.query.autoflush(False) \
                          .filter_by(slug=full_slug).limit(1).count():
                full_slug = increment_string(full_slug)
            self.slug = full_slug

    def get_url_values(self):
        return 'blog/show_category', {
            'slug':     self.slug
        }

    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.name
        )


class CommentQuery(db.Query):
    """The manager for comments"""

    def approved(self):
        """Return only the approved comments."""
        return self.filter(Comment.status == COMMENT_MODERATED)

    def blocked(self):
        """Filter all blocked comments.  Blocked comments are all comments but
        unmoderated and moderated comments.
        """
        return self.filter(Comment.status.in_([COMMENT_BLOCKED_USER,
                                               COMMENT_BLOCKED_SPAM,
                                               COMMENT_BLOCKED_SYSTEM]))
    def unmoderated(self):
        """Filter all the unmoderated comments and comments blocked by a user
        or system.
        """
        return self.filter(Comment.status.in_([COMMENT_UNMODERATED,
                                               COMMENT_BLOCKED_USER,
                                               COMMENT_BLOCKED_SYSTEM]))

    def spam(self):
        """Filter all the spam comments."""
        return self.filter(Comment.status == COMMENT_BLOCKED_SPAM)

    def latest(self, limit=None, ignore_privileges=False, ignore_blocked=True):
        """Filter the list of non blocked comments for anonymous users or
        all comments for admin users.
        """
        query = self

        # only the approved if blocked are ignored
        if ignore_blocked:
            query = query.approved()

        # otherwise if we don't ignore the privileges we only want
        # the approved if the user does not have the MODERATE_COMMENTS
        # privileges.
        elif not ignore_privileges:
            req = get_request()
            if req:
                user = req.user
                if not user.has_privilege(MODERATE_COMMENTS):
                    query = query.approved()

        return query

    def comments_for_post(self, post):
        """Return all comments for the blog post."""
        return self.filter(Comment.post_id == post.id)


class Comment(_ZEMLContainer):
    """Represent one comment."""

    query = db.query_property(CommentQuery)
    parser_reason = 'comment'

    def __init__(self, post, author, text, email=None, www=None, parent=None,
                 pub_date=None, submitter_ip='0.0.0.0', parser=None,
                 is_pingback=False, status=COMMENT_MODERATED):
        self.post = post
        if isinstance(author, basestring):
            self.user = None
            self._author = author
            self._email = email
            self._www = www
        else:
            assert email is www is None, \
                'email and www can only be provided if the author is ' \
                'an anonmous user'
            self.user = author

        if parser is None:
            parser = get_application().cfg['comment_parser']
        self.parser = parser
        self.text = text or ''
        self.parent = parent
        if pub_date is None:
            pub_date = datetime.utcnow()
        self.pub_date = pub_date
        self.blocked_msg = None
        self.submitter_ip = submitter_ip
        self.is_pingback = is_pingback
        self.status = status

    def _union_property(attribute, user_attribute=None):
        """An attribute that can exist on a user and the comment."""
        user_attribute = user_attribute or attribute
        attribute = '_' + attribute
        def get(self):
            if self.user:
                return getattr(self.user, user_attribute)
            return getattr(self, attribute)
        def set(self, value):
            if self.user:
                raise TypeError('can\'t set this attribute if the comment '
                                'does not belong to an anonymous user')
            setattr(self, attribute, value)
        return property(get, set)

    email = _union_property('email')
    www = _union_property('www')
    author = _union_property('author', 'display_name')
    del _union_property

    @property
    def anonymous(self):
        """True if this comment is an anonymous comment."""
        return self.user is None

    @property
    def requires_moderation(self):
        """This is `True` if the comment requires moderation with the
        current moderation settings.  This does not check if the comment
        is already moderated.
        """
        if not self.anonymous:
            return False
        moderate = get_application().cfg['moderate_comments']
        if moderate == MODERATE_ALL:
            return True
        elif moderate == MODERATE_NONE:
            return False
        return db.execute(comments.select(
            (comments.c.author == self._author) &
            (comments.c.email == self._email) &
            (comments.c.status == COMMENT_MODERATED)
        )).fetchone() is None

    def make_visible_for_request(self, request=None):
        """Make the comment visible for the current request."""
        if request is None:
            request = get_request()
        comments = set(request.session.get('visible_comments', ()))
        comments.add(self.id)
        request.session['visible_comments'] = tuple(comments)

    def visible_for_user(self, user=None):
        """Check if the current user or the user given can see this comment"""
        if not self.blocked:
            return True
        if user is None:
            user = get_request().user
        return user.has_privilege(MODERATE_COMMENTS)

    @property
    def visible(self):
        """Check the current session it can see the comment or check against the
        current user.  To display a comment for a request you can use the
        `make_visible_for_request` function.  This is useful to show a comment
        to a user that submited a comment which is not yet moderated.
        """
        request = get_request()
        if self.id in request.session.get('visible_comments', ()):
            return True
        return self.visible_for_user(request.user)

    @property
    def visible_children(self):
        """Only the children that are visible for the current user."""
        return [x for x in self.children if x.visible]

    @property
    def blocked(self):
        """This is true if the status is anything but moderated."""
        return self.status != COMMENT_MODERATED

    @property
    def is_spam(self):
        """This is true if the comment is currently flagges as spam."""
        return self.status == COMMENT_BLOCKED_SPAM

    @property
    def is_unmoderated(self):
        """True if the comment is not yet approved."""
        return self.status == COMMENT_UNMODERATED

    def get_url_values(self):
        return url_for(self.post) + '#comment-%d' % self.id

    def __repr__(self):
        return '<%s %r>' % (
            self.__class__.__name__,
            self.author
        )


class TagQuery(db.Query):

    def get_cloud(self, max=None, ignore_privileges=False):
        """Get a categorycloud."""
        # XXX: ignore_privileges is currently ignored and no privilege
        # checking is performed.  As a matter of fact only published posts
        # appear in the cloud.

        # get a query
        pt = post_tags.c
        p = posts.c
        t = tags.c

        q = ((pt.tag_id == t.tag_id) &
             (pt.post_id == p.post_id) &
             (p.status == STATUS_PUBLISHED) &
             (p.pub_date >= datetime.utcnow()))

        s = db.select([t.slug, t.name, db.func.count(p.post_id).label('s_count')],
                      (pt.tag_id == t.tag_id) &
                      (pt.post_id == p.post_id),
                      group_by=[t.slug, t.name]).alias('post_count_query').c

        options = {'order_by': [db.asc(s.s_count)]}
        if max is not None:
            options['limit'] = max

        # the label statement circumvents a bug for sqlite3 on windows
        # see #65
        q = db.select([s.slug, s.name, s.s_count.label('s_count')], **options)

        items = [{
            'slug':     row.slug,
            'name':     row.name,
            'count':    row.s_count,
            'size':     100 + log(row.s_count or 1) * 20
        } for row in db.execute(q)]

        items.sort(key=lambda x: x['name'].lower())
        return items


class Tag(object):
    """A single tag."""
    query = db.query_property(TagQuery)

    def __init__(self, name, slug=None):
        self.name = name
        if slug is None:
            self.set_auto_slug()
        else:
            self.slug = slug

    @staticmethod
    def get_or_create(name):
        tag = Tag.query.filter_by(name=name).first()
        if tag is not None:
            return tag
        return Tag(name)

    def set_auto_slug(self):
        full_slug = gen_slug(self.name)
        if not full_slug:
            # if slug generation failed we select the highest category
            # id as base for slug generation.
            tag = Tag.query.autoflush(False).order_by(Tag.id.desc()).first()
            full_slug = unicode(tag and tag.id or u'1')
        if full_slug != self.slug:
            while Tag.query.autoflush(False) \
                          .filter_by(slug=full_slug).limit(1).count():
                full_slug = increment_string(full_slug)
            self.slug = full_slug

    def get_url_values(self):
        return 'blog/show_tag', {'slug': self.slug}

    def __repr__(self):
        return u'<%s %r>' % (
            self.__class__.__name__,
            self.name
        )


# connect the tables.
db.mapper(User, users, properties={
    'id':               users.c.user_id,
    'display_name':     db.synonym('_display_name', map_column=True),
    'posts':            db.dynamic_loader(Post,
                                          backref=db.backref('author', lazy=False),
                                          cascade='all, delete, delete-orphan'),
    'comments':         db.dynamic_loader(Comment,
                                          backref=db.backref('user', lazy=False),
                                          cascade='all, delete'),
    '_own_privileges':  db.relation(_Privilege, lazy=True,
                                    secondary=user_privileges,
                                    collection_class=set,
                                    cascade='all, delete')
})
db.mapper(Group, groups, properties={
    'id':               groups.c.group_id,
    'users':            db.dynamic_loader(User, backref=db.backref('groups', lazy=True),
                                          secondary=group_users),
    '_privileges':      db.relation(_Privilege, lazy=True,
                                    secondary=group_privileges,
                                    collection_class=set,
                                    cascade='all, delete')
})
db.mapper(_Privilege, privileges, properties={
    'id':               privileges.c.privilege_id,
})
db.mapper(Category, categories, properties={
    'id':               categories.c.category_id,
    'posts':            db.dynamic_loader(Post, secondary=post_categories)
}, order_by=categories.c.name)
db.mapper(Comment, comments, properties={
    'id':           comments.c.comment_id,
    'text':         db.synonym('_text', map_column=True),
    'author':       db.synonym('_author', map_column=True),
    'email':        db.synonym('_email', map_column=True),
    'www':          db.synonym('_www', map_column=True),
    'children':     db.relation(Comment,
        primaryjoin=comments.c.parent_id == comments.c.comment_id,
        order_by=[db.asc(comments.c.pub_date)],
        backref=db.backref('parent', remote_side=[comments.c.comment_id],
                           primaryjoin=comments.c.parent_id == comments.c.comment_id),
        lazy=True
    )
}, order_by=comments.c.pub_date.desc())
db.mapper(PostLink, post_links, properties={
    'id':           post_links.c.link_id,
})
db.mapper(Tag, tags, properties={
    'id':           tags.c.tag_id,
    'posts':        db.dynamic_loader(Post, secondary=post_tags)
}, order_by=tags.c.name)
db.mapper(Post, posts, properties={
    'id':               posts.c.post_id,
    'text':             db.synonym('_text', map_column=True),
    'comments':         db.relation(Comment, backref='post',
                                    primaryjoin=posts.c.post_id ==
                                        comments.c.post_id,
                                    order_by=[db.asc(comments.c.pub_date)],
                                    lazy=False,
                                    cascade='all, delete, delete-orphan'),
    'links':            db.relation(PostLink, backref='post',
                                    cascade='all, delete, delete-orphan'),
    'categories':       db.relation(Category, secondary=post_categories, lazy=False,
                                    order_by=[db.asc(categories.c.name)]),
    'tags':             db.relation(Tag, secondary=post_tags, lazy=False,
                                    order_by=[tags.c.name]),
    '_comment_count':   db.column_property(
        db.select([db.func.count(comments.c.comment_id)],
                  (comments.c.post_id == posts.c.post_id) &
                  (comments.c.status == COMMENT_MODERATED)
        ).label('comment_count'), deferred=True)
}, order_by=posts.c.pub_date.desc())