zine-main / zine / views / admin.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
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
# -*- coding: utf-8 -*-
"""
    zine.views.admin
    ~~~~~~~~~~~~~~~~

    This module implements the admin views. The admin interface is only
    available for admins, editors and authors but not for subscribers. For
    subscribers a simplified account management system exists at /account.

    :copyright: (c) 2010 by the Zine Team, see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from urlparse import urlparse

from werkzeug import escape
from werkzeug.exceptions import NotFound, BadRequest, Forbidden

from zine.privileges import assert_privilege, \
     CREATE_ENTRIES, EDIT_OWN_ENTRIES, EDIT_OTHER_ENTRIES, \
     CREATE_PAGES, EDIT_OWN_PAGES, EDIT_OTHER_PAGES, MODERATE_COMMENTS, \
     MODERATE_OWN_ENTRIES, MODERATE_OWN_PAGES, MANAGE_CATEGORIES, BLOG_ADMIN
from zine.i18n import _, ngettext
from zine.application import get_request, url_for, emit_event, \
     render_response
from zine.models import User, Group, Post, Category, Comment
from zine.database import db, secure_database_uri
from zine.utils.admin import flash, load_zine_reddit, require_admin_privilege
from zine.utils.pagination import AdminPagination
from zine.utils.http import redirect_to, redirect
from zine.importers import list_import_queue, load_import_dump, \
     delete_import_dump
from zine.pluginsystem import install_package, InstallationError, \
     get_object_name
from zine.pingback import pingback, PingbackError
from zine.forms import ChangePasswordForm, PluginForm, \
     LogOptionsForm, EntryForm, PageForm, BasicOptionsForm, URLOptionsForm, \
     PostDeleteForm, EditCommentForm, DeleteCommentForm, \
     ApproveCommentForm, BlockCommentForm, EditCategoryForm, \
     DeleteCategoryForm, EditUserForm, DeleteUserForm, \
     CommentMassModerateForm, CacheOptionsForm, EditGroupForm, \
     DeleteGroupForm, ThemeOptionsForm, DeleteImportForm, ExportForm, \
     MaintenanceModeForm, MarkCommentForm, RemovePluginForm, \
     make_config_form, make_import_form

#: how many posts / comments should be displayed per page?
PER_PAGE = 20


def render_admin_response(template_name, _active_menu_item=None, **values):
    """Works pretty much like the normal `render_response` function but
    it emits some events to collect navigation items and injects that
    into the template context. This also gets the flashes messages from
    the user session and injects them into the template context after the
    plugins have provided theirs in the `before-admin-response-rendered`
    event.

    The second parameter can be the active menu item if wanted. For example
    ``'options.overview'`` would show the overview button in the options
    submenu. If the menu is a standalone menu like the dashboard (no
    child items) you can also just use ``'dashboard'`` to highlight that.
    """
    request = get_request()

    # set up the core navigation bar
    navigation_bar = [
        ('dashboard', url_for('admin/index'), _(u'Dashboard'), [])
    ]

    write_nav = []
    if request.user.has_privilege(CREATE_ENTRIES):
        write_nav.append(('entry', url_for('admin/new_entry'), _(u'Entry')))
    if request.user.has_privilege(CREATE_PAGES):
        write_nav.append(('page', url_for('admin/new_page'), _(u'Page')))
    if request.user.has_privilege(CREATE_ENTRIES | CREATE_PAGES):
        navigation_bar.append(
            ('write', url_for('admin/new_entry'), _(u'Write'), write_nav)
        )

    manage_items = []
    if request.user.has_privilege(EDIT_OWN_ENTRIES):
        manage_items.append(
            ('entries', url_for('admin/manage_entries'), _(u'Entries'))
        )
    if request.user.has_privilege(EDIT_OWN_PAGES):
        manage_items.append(
            ('pages', url_for('admin/manage_pages'), _(u'Pages')),
        )
    if request.user.has_privilege(MANAGE_CATEGORIES):
        manage_items.append(
            ('categories', url_for('admin/manage_categories'), _(u'Categories'))
        )
    if request.user.has_privilege(EDIT_OWN_ENTRIES | EDIT_OWN_PAGES |
                                  MANAGE_CATEGORIES):
        navigation_bar.append(
            ('manage', url_for('admin/manage_entries'), _(u'Manage'),
             manage_items)
        )
    if request.user.has_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                                  MODERATE_OWN_PAGES):
        unmoderated = Comment.query.unmoderated()
        approved = Comment.query.approved()
        blocked = Comment.query.blocked()
        spam = Comment.query.spam()

        if request.user.has_privilege(MODERATE_OWN_ENTRIES |
                                      MODERATE_OWN_PAGES):
            unmoderated = unmoderated.for_user(request.user)
            approved = approved.for_user(request.user)
            blocked = blocked.for_user(request.user)
            spam = spam.for_user(request.user)

        navigation_bar.append(
            ('comments', url_for('admin/manage_comments'), _(u'Comments'), [
                ('overview', url_for('admin/manage_comments'), _(u'Overview')),
                ('unmoderated', url_for('admin/show_unmoderated_comments'),
                 _(u'Awaiting Moderation (%d)') % unmoderated.count()),
                ('approved', url_for('admin/show_approved_comments'),
                 _(u'Approved (%d)') % approved.count()),
                ('blocked', url_for('admin/show_blocked_comments'),
                 _(u'Blocked (%d)') % blocked.count()),
                ('spam', url_for('admin/show_spam_comments'),
                 _(u'Spam (%d)') % spam.count())
            ])
        )

    # set up the administration menu bar
    if request.user.has_privilege(BLOG_ADMIN):
        navigation_bar.extend([
            ('options', url_for('admin/options'), _(u'Options'), [
                ('basic', url_for('admin/basic_options'), _(u'Basic')),
                ('urls', url_for('admin/urls'), _(u'URLs')),
                ('theme', url_for('admin/theme'), _(u'Theme')),
                ('cache', url_for('admin/cache'), _(u'Cache')),
                ('configuration', url_for('admin/configuration'),
                 _(u'Configuration Editor'))
            ])
        ])
        manage_items.extend([
            ('users', url_for('admin/manage_users'), _(u'Users')),
            ('groups', url_for('admin/manage_groups'), _(u'Groups'))
        ])

    # add the help item to the navigation bar
    system_items = [('help', url_for('admin/help'), _(u'Help'))]

    if request.user.has_privilege(BLOG_ADMIN):
        system_items[0:0] = [
            ('information', url_for('admin/information'),
             _(u'Information')),
            ('maintenance', url_for('admin/maintenance'),
             _(u'Maintenance')),
            ('plugins', url_for('admin/plugins'), _(u'Plugins')),
            ('import', url_for('admin/import'), _(u'Import')),
            ('export', url_for('admin/export'), _(u'Export')),
            ('log', url_for('admin/log'), _(u'Log'))
        ]

    navigation_bar.append(('system', system_items[0][1], _(u'System'),
                           system_items))

    #! allow plugins to extend the navigation bar
    emit_event('modify-admin-navigation-bar', request, navigation_bar)

    # find out which is the correct menu and submenu bar
    active_menu = active_submenu = None
    if _active_menu_item is not None:
        p = _active_menu_item.split('.')
        if len(p) == 1:
            active_menu = p[0]
        else:
            active_menu, active_submenu = p
    for id, url, title, subnavigation_bar in navigation_bar:
        if id == active_menu:
            break
    else:
        subnavigation_bar = []

    # if we are in maintenance_mode the user should know that, no matter
    # on which page he is.
    if request.app.cfg['maintenance_mode'] and \
                                        request.user.has_privilege(BLOG_ADMIN):
        flash(_(u'Zine is in maintenance mode. Don\'t forget to '
                u'turn it off again once you finish your changes. You '
                u'can do that under System -> Maintenance'))

    # check for broken plugins if we have the plugin guard enabled
    if request.app.cfg['plugin_guard']:
        plugins_to_deactivate = []
        for plugin in request.app.plugins.itervalues():
            if plugin.active and plugin.setup_error is not None:
                flash(_(u'Could not activate plugin “%(name)s”: %(error)s') % {
                    'name':     plugin.html_display_name,
                    'error':    plugin.setup_error
                })
                plugins_to_deactivate.append(plugin.name)

        if plugins_to_deactivate:
            #TODO: it's quite tricky – it needs at least two reloads to
            #      deactivate the plugin (which is in fact a application reload)
            cfg = request.app.cfg.edit()
            cfg['plugins'] = u', '.join(sorted(set(request.app.cfg['plugins']) - \
                                               set(plugins_to_deactivate)))
            cfg.commit()
            # we change the plugins inline so that the user get somewhat more
            # information
            request.app.cfg.touch()


    #! used to flash messages, add links to stylesheets, modify the admin
    #! context etc.
    emit_event('before-admin-response-rendered', request, values)

    # the admin variables is pushed into the context after the event was
    # sent so that plugins can flash their messages. If we would emit the
    # event afterwards all flashes messages would appear in the request
    # after the current request.
    values['admin'] = {
        'navbar': [{
            'id':       id,
            'url':      url,
            'title':    title,
            'active':   active_menu == id
        } for id, url, title, children in navigation_bar],
        'ctxnavbar': [{
            'id':       id,
            'url':      url,
            'title':    title,
            'active':   active_submenu == id
        } for id, url, title in subnavigation_bar],
        'messages': [{
            'type':     type,
            'msg':      msg
        } for type, msg in request.session.pop('admin/flashed_messages', [])],
        'active_pane': _active_menu_item
    }
    return render_response(template_name, **values)


def ping_post_links(form):
    """A helper that pings the links in a post."""
    pinged_successfully = []
    if form.request.app.cfg['maintenance_mode'] or \
       not form.post.is_published:
        flash(_(u'No URLs pinged so far because the post is not '
                u'publicly available'))
    elif form.post.parser_missing:
        flash(_(u'Could not ping URLs because the parser for the '
                u'post is not available any longer.'), 'error')
    else:
        this_url = url_for(form.post, _external=True)
        for url in form.find_new_links():
            host = urlparse(url)[1].decode('utf-8', 'ignore')
            try:
                pingback(this_url, url)
            except PingbackError, e:
                if not e.ignore_silently:
                    flash(_(u'Could not ping %(url)s: %(error)s') % {
                        'url':   escape(host),
                        'error': e.message
                    }, 'error')
            else:
                pinged_successfully.append(html_url)
    if pinged_successfully:
        flash(ngettext(u'The following link was pinged successfully: %s',
                       u'The following links where pinged successfully: %s',
                       len(pinged_successfully)) %
              u', '.join(pinged_successfully))


@require_admin_privilege()
def index(request):
    """Show the admin interface index page which is a wordpress inspired
    dashboard (doesn't exist right now).

    Once it's finished it should show the links to the most useful pages
    such as "new post", etc. and the recent blog activity (unmoderated
    comments etc.)
    """
    # the template loads the reddit with a separate http request via
    # javascript to not slow down the page loading
    if request.args.get('load') == 'reddit':
        return render_response('admin/reddit.html', items=load_zine_reddit())

    return render_admin_response('admin/index.html', 'dashboard',
        drafts=Post.query.drafts().all(), unmoderated_comments=
            Comment.query.post_lightweight().unmoderated().for_user(request.user).all(),
        your_posts=Post.query.filter(Post.author_id==request.user.id).count(),
        last_posts=Post.query.published(ignore_privileges=True)
            .order_by(Post.pub_date.desc()).limit(5).all(),
        show_reddit = request.app.cfg['dashboard_reddit']
    )


def bookmarklet(request):
    """Requests to this view are usually triggered by the bookmarklet
    from the edit-post page.  Currently this is a redirect to the new-post
    page with some small modifications but in the future this could be
    expanded to add a wizard or something.
    """
    if request.args['mode'] != 'newpost':
        raise BadRequest()
    body = '%s\n\n<a href="%s">%s</a>' % (
        request.args.get('text', _(u'Text here...')),
        request.args['url'],
        request.args.get('title', _(u'Untitled Page'))
    )
    return redirect_to('admin/new_entry',
        title=request.args.get('title'),
        body=body
    )


@require_admin_privilege(CREATE_ENTRIES | EDIT_OWN_ENTRIES | EDIT_OTHER_ENTRIES)
def manage_entries(request, page):
    """Show a list of entries."""
    entry_query = Post.query.type('entry')
    entries = entry_query.order_by([Post.status, Post.pub_date.desc()]) \
                         .limit(PER_PAGE).offset(PER_PAGE * (page - 1)).all()
    pagination = AdminPagination('admin/manage_entries', page, PER_PAGE,
                                 entry_query.count())
    if not entries and page != 1:
        raise NotFound()
    return render_admin_response('admin/manage_entries.html', 'manage.entries',
                                 entries=entries, pagination=pagination)


def _make_post_dispatcher(action):
    """Creates a new dispatcher for the given content type action.  This
    already checks if the user can enter the admin panel but not if the
    user has the required privileges.
    """
    @require_admin_privilege()
    def func(request, post_id):
        """Dispatch to the request handler for a post."""
        post = Post.query.get(post_id)
        if post is None:
            raise NotFound()
        try:
            handler = request.app.admin_content_type_handlers \
                [post.content_type][action]
        except KeyError:
            raise NotFound()
        return handler(request, post)
    func.__name__ = 'dispatch_post_' + action
    return func


dispatch_post_edit = _make_post_dispatcher('edit')
dispatch_post_delete = _make_post_dispatcher('delete')


def edit_entry(request, post=None):
    """Edit an existing entry or create a new one."""
    active_tab = post and 'manage.entries' or 'write.entry'
    initial = {}
    body = request.args.get('body')
    title = request.args.get('title')
    if body:
        initial['text'] = body
    if title:
        initial['title'] = title
    form = EntryForm(post, initial)

    if post is None:
        assert_privilege(CREATE_ENTRIES)
    else:
        if not post.can_edit(request.user):
            raise Forbidden()

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/manage_entries')
        elif 'delete' in request.form:
            return redirect_to('admin/delete_post', post_id=post.id)
        elif form.validate(request.form):
            if post is None:
                post = form.make_post()
                msg = _(u'The entry “%s” was created successfully.')
            else:
                form.save_changes()
                msg = _(u'The entry “%s” was updated successfully.')

            flash(msg % escape(post.title))

            db.commit()
            emit_event('after-post-saved', post)
            if form['ping_links']:
                ping_post_links(form)
            if 'save_and_continue' in request.form:
                return redirect_to('admin/edit_post', post_id=post.id)
            return form.redirect('admin/new_entry')
    return render_admin_response('admin/edit_entry.html', active_tab,
                                 form=form.as_widget())


@require_admin_privilege()
def delete_entry(request, post):
    """This dialog deletes an entry.  Usually users are redirected here from the
    edit post view or the post index page.  If the entry was not deleted the
    user is taken back to the page he's coming from or back to the edit
    page if the information is invalid.
    """
    form = PostDeleteForm(post)
    if not post.can_edit():
        raise Forbidden()

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/edit_post', post_id=post.id)
        elif request.form.get('confirm') and form.validate(request.form):
            form.add_invalid_redirect_target('admin/edit_post', post_id=post.id)
            form.delete_post()
            flash(_(u'The entry “%s” was deleted successfully.') %
                  escape(post.title), 'remove')
            db.commit()
            return form.redirect('admin/manage_entries')

    return render_admin_response('admin/delete_entry.html', 'manage.entries',
                                 form=form.as_widget())


@require_admin_privilege(CREATE_PAGES | EDIT_OWN_PAGES | EDIT_OTHER_PAGES)
def manage_pages(request, page):
    """Show a list of pages."""
    page_query = Post.query.type('page')
    pages = page_query.limit(PER_PAGE).offset(PER_PAGE * (page - 1)).all()
    pagination = AdminPagination('admin/manage_pages', page, PER_PAGE,
                                 page_query.count())
    if not pages and page != 1:
        raise NotFound()
    return render_admin_response('admin/manage_pages.html', 'manage.pages',
                                 pages=pages, pagination=pagination)


@require_admin_privilege(EDIT_OWN_PAGES | EDIT_OTHER_PAGES)
def edit_page(request, post=None):
    """Edit an existing entry or create a new one."""
    active_tab = post and 'manage.pages' or 'write.page'
    form = PageForm(post)


    if post is None:
        assert_privilege(CREATE_PAGES)
    else:
        if not post.can_edit(request.user):
            raise Forbidden()

    if request.method == 'POST':
        if 'cancel' in request.form:
            return form.redirect('admin/manage_pages')
        elif 'delete' in request.form:
            return redirect_to('admin/delete_post', post_id=post.id)
        elif form.validate(request.form):
            if post is None:
                post = form.make_post()
                msg = _(u'The page “%s” was created successfully.')
            else:
                form.save_changes()
                msg = _(u'The page “%s” was updated successfully.')

            flash(msg % escape(post.title))

            db.commit()
            emit_event('after-post-saved', post)
            if form['ping_links']:
                ping_post_links(form)
            if 'save_and_continue' in request.form:
                return redirect_to('admin/edit_post', post_id=post.id)
            return form.redirect('admin/new_page')
    return render_admin_response('admin/edit_page.html', active_tab,
                                 form=form.as_widget())


@require_admin_privilege(EDIT_OWN_PAGES | EDIT_OTHER_PAGES)
def delete_page(request, post):
    """This dialog deletes a page.  Usually users are redirected here from the
    edit post view or the page indexpage.  If the page was not deleted the
    user is taken back to the page he's coming from or back to the edit
    page if the information is invalid.
    """
    form = PostDeleteForm(post)
    if not post.can_edit(request.user):
        raise Forbidden()

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/edit_post', post_id=post.id)
        elif request.form.get('confirm') and form.validate(request.form):
            form.add_invalid_redirect_target('admin/edit_post', post_id=post.id)
            form.delete_post()
            flash(_(u'The page “%s” was deleted successfully.') %
                  escape(post.title), 'remove')
            db.commit()
            return form.redirect('admin/manage_pages')

    return render_admin_response('admin/delete_page.html', 'manage.pages',
                                 form=form.as_widget())


def _handle_comments(identifier, title, query, page, per_page, post_id=None,
                     endpoint='admin/manage_comments'):
    request = get_request()
    if request.method == 'POST' and 'per_page_update' in request.form:
        # Don't even filter the database query since we're redirecting
        return redirect(url_for(endpoint, page=page, post_id=post_id,
                                per_page=request.values.get('per_page')))

    if request.user.has_privilege(MODERATE_OWN_ENTRIES | MODERATE_OWN_PAGES):
        query = query.for_user(request.user)

    comments = query.post_lightweight().limit(per_page) \
                    .offset(per_page * (page - 1))


    pagination = AdminPagination(endpoint, page, per_page, query.count(),
                                 post_id=post_id)

    if not comments and page > 1:
        # Since we can tweak how many comments are shown, maybe we've just
        # changed how many we want to see per-page and there are not enought
        # pages now for the chosen ammount
        # Redirect to page-1 until comments are found.
        return redirect(url_for(endpoint, page=page-1, per_page=per_page,
                                post_id=post_id))

    form = CommentMassModerateForm(comments, initial=dict(per_page=per_page))

    tab = 'comments'
    if identifier is not None:
        tab += '.' + identifier

    if request.method == 'POST':
        if 'cancel' not in request.form and form.validate(request.form):
            if 'delete' in request.form:
                if 'confirm' in request.form:
                    form.delete_selection()
                    db.commit()
                    return redirect_to(endpoint, page=page, per_page=per_page)
                return render_admin_response('admin/delete_comments.html', tab,
                                             form=form.as_widget())
            # delete all comments in current tab
            elif 'delete_all' in request.form:
                if identifier not in ('spam', 'blocked'):
                    flash(_(u'“Delete All” can only be issued for “Spam” and '
                            u'“Blocked” comment types.'), 'error')
                elif 'confirm' in request.form:
                    comments = query.all()
                    # Don't use .count() means a 2nd query and it's
                    # aprox. 0.111 secs slower; rough average calculation :)
                    count = len(comments)
                    for comment in comments:
                        # Although we're deleting spam or blocked comments,
                        # they're still comments, so emit the right event
                        emit_event('before-comment-deleted', comment)
                        db.delete(comment)
                    db.commit()
                    # XXX: untranslatable
                    flash(_(u'Deleted %d %s comments.') % (count, identifier))
                    return redirect_to(endpoint, page=page, per_page=per_page)
                return render_admin_response('admin/delete_comments_all.html',
                                             tab, form=form.as_widget(),
                                             comment_kind = identifier,
                                             comment_count=query.count())

            # or approve them all
            elif 'approve' in request.form:
                form.approve_selection()
                db.commit()
                flash(_(u'Approved all the selected comments.'))
                return redirect_to(endpoint, page=page, per_page=per_page)

            # or block them all
            elif 'block' in request.form:
                if 'confirm' in request.form:
                    form.block_selection()
                    db.commit()
                    flash(_(u'Blocked all the selected comments.'))
                    return redirect_to(endpoint, page=page, per_page=per_page)
                return render_admin_response('admin/block_comments.html', tab,
                                             form=form.as_widget())

            # or mark them all as spam
            elif 'spam' in request.form:
                if 'confirm' in request.form:
                    form.mark_selection_as_spam()
                    db.commit()
                    flash(_(u'Reported all the selected comments as SPAM.'))
                    return redirect_to(endpoint, page=page, per_page=per_page)
                return render_admin_response('admin/mark_spam_comments.html',
                                             tab, form=form.as_widget())
            # or mark them all as ham
            elif 'ham' in request.form:
                if 'confirm' in request.form:
                    form.mark_selection_as_ham()
                    db.commit()
                    flash(_(u'Reported all the selected comments as NOT SPAM.'))
                    return redirect_to(endpoint, page=page, per_page=per_page)
                return render_admin_response('admin/mark_ham_comments.html',
                                             tab, form=form.as_widget())
    return render_admin_response(
        'admin/manage_comments.html', tab, comments_title=title,
        form=form.as_widget(), pagination=pagination,
        akismet_active = request.app.plugins['akismet_spam_filter'].active)


@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def manage_comments(request, page, per_page):
    """Show all the comments."""
    return _handle_comments('overview', _(u'All Comments'),
                            Comment.query, page, per_page)

@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def show_unmoderated_comments(request, page, per_page):
    """Show all unmoderated and user-blocked comments."""
    return _handle_comments('unmoderated', _(u'Comments Awaiting Moderation'),
                            Comment.query.unmoderated(), page, per_page,
                            endpoint='admin/show_unmoderated_comments')

@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def show_approved_comments(request, page, per_page):
    """Show all moderated comments."""
    return _handle_comments('approved', _(u'Approved Commments'),
                            Comment.query.approved(), page, per_page,
                            endpoint='admin/show_approved_comments')

@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def show_blocked_comments(request, page, per_page):
    """Show all spam comments."""
    return _handle_comments('blocked', _(u'Blocked'),
                            Comment.query.blocked(), page, per_page,
                            endpoint='admin/show_blocked_comments')

@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def show_spam_comments(request, page, per_page):
    """Show all spam comments."""
    return _handle_comments('spam', _(u'Spam'), Comment.query.spam(), page,
                            per_page, endpoint='admin/show_spam_comments')


@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def show_post_comments(request, page, post_id, per_page):
    """Show all comments for a single post."""
    post = Post.query.get(post_id)
    if post is None:
        raise NotFound()
    link = '<a href="%s">%s</a>' % (
        url_for('admin/edit_post', post_id=post.id),
        escape(post.title)
    )
    return _handle_comments(None, _(u'Comments for “%s”') % link,
                            Comment.query.comments_for_post(post), page,
                            per_page, post_id=post_id,
                            endpoint='admin/show_post_comments')


@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def edit_comment(request, comment_id):
    """Edit a comment.  Unlike the post edit screen it's not possible to
    create new comments from here, that has to happen from the post page.
    """
    comment = Comment.query.get(comment_id)
    if comment is None:
        raise NotFound()
    elif not comment.visible_for_user(request.user):
        raise Forbidden(_(u'You\'re not allowed to manage this comment'))
    form = EditCommentForm(comment)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/manage_comments')
        elif request.form.get('delete'):
            return redirect_to('admin/delete_comment', comment_id=comment_id)
        elif form.validate(request.form):
            form.save_changes()
            db.commit()
            flash(_(u'Comment by %s moderated successfully.') %
                  escape(comment.author))
            return form.redirect('admin/manage_comments')

    return render_admin_response('admin/edit_comment.html',
                                 'comments.overview', form=form.as_widget())


@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def delete_comment(request, comment_id):
    """This dialog deletes a comment.  Usually users are redirected here from
    the comment moderation page or the comment edit page.  If the comment was
    not deleted, the user is taken back to the page he's coming from or back to
    the edit page if the information is invalid.  The same happens if the post
    was deleted but if the referrer is the edit page. Then the user is taken
    back to the index so that he doesn't end up an a "page not found" error page.
    """
    comment = Comment.query.get(comment_id)
    if comment is None or comment.is_deleted:
        return redirect_to('admin/manage_comments')
    elif not comment.visible_for_user(request.user):
        raise Forbidden(_(u'You\'re not allowed to manage this comment'))

    form = DeleteCommentForm(comment)

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('cancel'):
            return form.redirect('admin/edit_comment', comment_id=comment.id)
        elif request.form.get('confirm'):
            form.add_invalid_redirect_target('admin/edit_comment',
                                             comment_id=comment.id)
            form.delete_comment()
            db.commit()
            return form.redirect('admin/manage_comments')

    return render_admin_response('admin/delete_comment.html',
                                 'comments.overview', form=form.as_widget())


@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def approve_comment(request, comment_id):
    """Approve a comment"""
    comment = Comment.query.get(comment_id)
    if comment is None:
        raise NotFound()
    elif not comment.visible_for_user(request.user):
        raise Forbidden(_(u'You\'re not allowed to manage this comment'))
    form = ApproveCommentForm(comment)

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('confirm'):
            form.approve_comment()
            db.commit()
            flash(_(u'Comment by %s approved successfully.') %
                  escape(comment.author), 'configure')
        return form.redirect('admin/manage_comments')

    return render_admin_response('admin/approve_comment.html',
                                 'comments.overview', form=form.as_widget())


@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def block_comment(request, comment_id):
    """Block a comment."""
    comment = Comment.query.get(comment_id)
    if comment is None:
        raise NotFound()
    elif not comment.visible_for_user(request.user):
        raise Forbidden(_(u'You\'re not allowed to manage this comment'))
    form = BlockCommentForm(comment)

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('confirm'):
            form.block_comment()
            db.commit()
            flash(_(u'Comment by %s blocked successfully.') %
                  escape(comment.author), 'configure')
        return form.redirect('admin/manage_comments')

    return render_admin_response('admin/block_comment.html',
                                 'comments.overview', form=form.as_widget())

@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def report_comment_spam(request, comment_id):
    """Block a comment."""
    comment = Comment.query.get(comment_id)
    if comment is None:
        raise NotFound()
    elif not comment.visible_for_user(request.user):
        raise Forbidden(_(u'You\'re not allowed to manage this comment'))
    form = MarkCommentForm(comment)

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('confirm'):
            form.mark_as_spam()
            db.commit()
            flash(_(u'Comment by %s reported as Spam successfully.') %
                  escape(comment.author), 'configure')
        return form.redirect('admin/manage_comments')

    return render_admin_response('admin/mark_comment.html',
                                 'comments.overview', form=form.as_widget(),
                                 form_action=_(u'Spam'))

@require_admin_privilege(MODERATE_COMMENTS | MODERATE_OWN_ENTRIES |
                         MODERATE_OWN_PAGES)
def report_comment_ham(request, comment_id):
    """Block a comment."""
    comment = Comment.query.get(comment_id)
    if comment is None:
        raise NotFound()
    elif not comment.visible_for_user(request.user):
        raise Forbidden(_(u'You\'re not allowed to manage this comment'))
    form = MarkCommentForm(comment)

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('confirm'):
            form.mark_as_ham()
            db.commit()
            flash(_(u'Comment by %s reported as NOT Spam successfully.') %
                  escape(comment.author), 'configure')
        return form.redirect('admin/manage_comments')

    return render_admin_response('admin/mark_comment.html',
                                 'comments.overview', form=form.as_widget(),
                                 form_action=_(u'NOT Spam'))

@require_admin_privilege(MANAGE_CATEGORIES)
def manage_categories(request, page):
    """Show a list of used post categories."""
    categories = Category.query.limit(PER_PAGE).offset(PER_PAGE * (page - 1)).all()
    pagination = AdminPagination('admin/manage_categories', page, PER_PAGE,
                                 Category.query.count())
    if not categories and page != 1:
        raise NotFound()
    return render_admin_response('admin/manage_categories.html', 'manage.categories',
                                 categories=categories,
                                 pagination=pagination)


@require_admin_privilege(MANAGE_CATEGORIES)
def edit_category(request, category_id=None):
    """Edit a category."""
    category = None
    if category_id is not None:
        category = Category.query.get(category_id)
        if category is None:
            raise NotFound()

    form = EditCategoryForm(category)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/manage_categories')
        if request.form.get('delete'):
            return redirect_to('admin/delete_category', category_id=category.id)
        elif form.validate(request.form):
            if category is None:
                category = form.make_category()
                msg = _(u'Category “%s” created successfully.')
                msg_type = 'add'
            else:
                form.save_changes()
                msg = _(u'Category “%s” updated successfully.')
                msg_type = 'info'
            db.commit()
            flash(msg % escape(category.name), msg_type)
            return redirect_to('admin/manage_categories')

    return render_admin_response('admin/edit_category.html',
                                 'manage.categories', form=form.as_widget())


@require_admin_privilege(MANAGE_CATEGORIES)
def delete_category(request, category_id):
    """Works like the other delete pages, just that it deletes categories."""
    category = Category.query.get(category_id)
    if category is None:
        return redirect_to('admin/manage_categories')
    form = DeleteCategoryForm(category)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return redirect('admin/edit_category', category_id=category.id)
        elif request.form.get('confirm') and form.validate(request.form):
            form.add_invalid_redirect_target('admin/edit_category',
                                             category_id=category.id)
            form.delete_category()
            flash(_(u'Category %s deleted successfully.') % escape(category.name))
            db.commit()
            return form.redirect('admin/manage_categories')

    return render_admin_response('admin/delete_category.html', 'manage.categories',
                                 form=form.as_widget())


@require_admin_privilege(BLOG_ADMIN)
def manage_users(request, page):
    """Show all users in a list."""
    users = User.query.limit(PER_PAGE).offset(PER_PAGE * (page - 1)).all()
    pagination = AdminPagination('admin/manage_users', page, PER_PAGE,
                                 User.query.count())
    if not users and page != 1:
        raise NotFound()
    return render_admin_response('admin/manage_users.html', 'manage.users',
                                 users=users, pagination=pagination)


@require_admin_privilege(BLOG_ADMIN)
def edit_user(request, user_id=None):
    """Edit a user.  This can also create a user.  If a new user is created
    the dialog is simplified, some unimportant details are left out.
    """
    user = None
    if user_id is not None:
        user = User.query.get(user_id)
        if user is None:
            raise NotFound()
    form = EditUserForm(user)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/manage_users')
        elif request.form.get('delete') and user:
            return redirect_to('admin/delete_user', user_id=user.id)
        elif form.validate(request.form):
            if user is None:
                user = form.make_user()
                msg = _(u'User “%s” created successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _(u'User “%s” edited successfully.')
                icon = 'info'
            db.commit()
            flash(msg % escape(user.username), icon)
            if request.form.get('save'):
                return form.redirect('admin/manage_users')
            return redirect_to('admin/edit_user', user_id=user.id)

    return render_admin_response('admin/edit_user.html', 'manage.users',
                                 form=form.as_widget())


@require_admin_privilege(BLOG_ADMIN)
def delete_user(request, user_id):
    """Like all other delete screens just that it deletes a user."""
    user = User.query.get(user_id)
    if user is None:
        raise NotFound()
    form = DeleteUserForm(user)
    if user == request.user:
        flash(_(u'You cannot delete yourself.'), 'error')
        return form.redirect('admin/manage_users')

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/edit_user', user_id=user.id)
        elif request.form.get('confirm') and form.validate(request.form):
            form.add_invalid_redirect_target('admin/edit_user', user_id=user.id)
            form.delete_user()
            db.commit()
            return form.redirect('admin/manage_users')

    return render_admin_response('admin/delete_user.html', 'manage.users',
                                 form=form.as_widget())


@require_admin_privilege(BLOG_ADMIN)
def manage_groups(request):
    groups = Group.query.all()
    return render_admin_response('admin/manage_groups.html', 'manage.groups',
                                 groups=groups)

@require_admin_privilege(BLOG_ADMIN)
def edit_group(request, group_id=None):
    """Edit a Group.  This is used to create a group as well."""
    group = None
    if group_id is not None:
        group = Group.query.get(group_id)
        if group is None:
            raise NotFound()
    form = EditGroupForm(group)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/manage_groups')
        elif request.form.get('delete') and group:
            return redirect_to('admin/delete_group', group_id=group.id)
        elif form.validate(request.form):
            if group is None:
                group = form.make_group()
                msg = _(u'Group “%s” created successfully.')
                icon = 'add'
            else:
                form.save_changes()
                msg = _(u'Group “%s” edited successfully.')
                icon = 'info'
            db.commit()
            flash(msg % escape(group.name), icon)

            if request.form.get('save'):
                return form.redirect('admin/manage_groups')
            return redirect_to('admin/edit_group', group_id=group.id)

    return render_admin_response('admin/edit_group.html', 'manage.groups',
                                 form=form.as_widget())

@require_admin_privilege(BLOG_ADMIN)
def delete_group(request, group_id):
    """Like all other delete screens just that it deletes a group."""
    group = Group.query.get(group_id)
    if group is None:
        raise NotFound()
    form = DeleteGroupForm(group)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/edit_group', group_id=group.id)
        elif request.form.get('confirm') and form.validate(request.form):
            form.add_invalid_redirect_target('admin/edit_group',
                                             group_id=group.id)
            form.delete_group()
            db.commit()
            return form.redirect('admin/manage_groups')

    return render_admin_response('admin/delete_group.html', 'manage.groups',
                                 form=form.as_widget())


@require_admin_privilege(BLOG_ADMIN)
def options(request):
    """So far just a redirect page, later it would be a good idea to have
    a page that shows all the links to configuration things in form of
    a simple table.
    """
    return redirect_to('admin/basic_options')


@require_admin_privilege(BLOG_ADMIN)
def basic_options(request):
    """The dialog for basic options such as the blog title etc."""
    # flash an altered message if the url is ?altered=true.  For more information
    # see the comment that redirects to the url below.
    if request.args.get('altered') == 'true':
        flash(_(u'Configuration altered successfully.'), 'configure')
        return redirect_to('admin/basic_options')

    form = BasicOptionsForm()

    if request.method == 'POST' and form.validate(request.form):
        form.apply()

        # because the configuration page could change the language and
        # we want to flash the message "configuration changed" in the
        # new language rather than the old.  As a matter of fact we have
        # to wait for Zine to reload first which is why we do the
        # actual flashing after one reload.
        return redirect_to('admin/basic_options', altered='true')

    return render_admin_response('admin/basic_options.html', 'options.basic',
                                 form=form.as_widget())


@require_admin_privilege(BLOG_ADMIN)
def urls(request):
    """A config page for URL depending settings."""
    form = URLOptionsForm()

    if request.method == 'POST' and form.validate(request.form):
        form.apply()
        db.commit()
        flash(_(u'URL configuration changed.'), 'configure')
        # because the next request could reload the application and move
        # the admin interface we construct the URL to this page by hand.
        return redirect(form['admin_url_prefix'][1:] + '/options/urls')

    return render_admin_response('admin/url_options.html', 'options.urls',
                                 form=form.as_widget())


@require_admin_privilege(BLOG_ADMIN)
def theme(request):
    """Allow the user to select one of the themes that are available."""
    form = ThemeOptionsForm()

    if request.method == 'GET':
        if 'configure' in request.args:
            return redirect_to('admin/configure_theme')
        elif form.validate(request.args):
            new_theme = request.args.get('select')
            if new_theme in request.app.themes:
                request.app.cfg.change_single('theme', new_theme)
                flash(_(u'Theme changed successfully.'), 'configure')
                return redirect_to('admin/theme')

    return render_admin_response('admin/theme.html', 'options.theme',
        themes=sorted(
            request.app.themes.values(),
            key=lambda x: x.name == 'default' or x.display_name.lower()
        ),
        current_theme=request.app.theme,
        form=form.as_widget()
    )


@require_admin_privilege(BLOG_ADMIN)
def configure_theme(request):
    if not request.app.theme.configurable:
        flash(_(u'This theme is not configurable'), 'error')
        return redirect_to('admin/theme')
    return request.app.theme.configuration_page(request)


@require_admin_privilege(BLOG_ADMIN)
def plugins(request):
    """Load and unload plugins and reload Zine if required."""
    form = PluginForm()

    if request.method == 'POST' and form.validate(request.form):
        form.apply()
        flash(_(u'Plugin configuration changed'), 'configure')

        new_plugin = request.files.get('new_plugin')
        if new_plugin:
            try:
                plugin = install_package(request.app, new_plugin)
            except InstallationError, e:
                flash(e.message, 'error')
            else:
                flash(_(u'Plugin “%s” added successfully. You can now '
                        u'enable it in the plugin list.') %
                      plugin.html_display_name, 'add')

        return redirect_to('admin/plugins')

    return render_admin_response('admin/plugins.html', 'system.plugins',
        form=form.as_widget(),
        plugins=sorted(request.app.plugins.values(), key=lambda x: x.name)
    )


@require_admin_privilege(BLOG_ADMIN)
def remove_plugin(request, plugin):
    """Remove an inactive, instance installed plugin completely."""
    plugin = request.app.plugins.get(plugin)
    if plugin is None or \
       not plugin.instance_plugin or \
       plugin.active:
        raise NotFound()
    form = RemovePluginForm(plugin)

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('confirm'):
            try:
                plugin.remove()
            except IOError:
                flash(_(u'Could not remove the plugin “%s” because an '
                        u'IO error occurred. Wrong permissions?') %
                      plugin.html_display_name)
            flash(_(u'The plugin “%s” was removed from the instance '
                    u'successfully.') % escape(plugin.display_name), 'remove')
        return form.redirect('admin/plugins')

    return render_admin_response('admin/remove_plugin.html', 'options.plugins',
        plugin=plugin,
        form=form.as_widget()
    )


@require_admin_privilege(BLOG_ADMIN)
def cache(request):
    """Configure the cache."""
    form = CacheOptionsForm()

    if request.method == 'POST':
        if 'clear_cache' in request.form:
            request.app.cache.clear()
            flash(_(u'The cache was cleared successfully.'), 'configure')
            return redirect_to('admin/cache')
        elif form.validate(request.form):
            form.apply()
            flash(_(u'Cache settings were changed successfully.'), 'configure')
            return redirect_to('admin/cache')

    return render_admin_response('admin/cache.html', 'options.cache',
                                 form=form.as_widget())


@require_admin_privilege(BLOG_ADMIN)
def configuration(request):
    """Advanced configuration editor.  This is useful for development or if a
    plugin doesn't ship an editor for the configuration values.  Because all
    the values are not further checked it could easily be that Zine is
    left in an unusable state if a variable is set to something bad.  Because
    of this the editor shows a warning and must be enabled by hand.
    """
    form = make_config_form()

    if request.method == 'POST':
        if request.form.get('enable_editor'):
            request.session['ace_on'] = True
        elif request.form.get('disable_editor'):
            request.session['ace_on'] = False
        elif form.validate(request.form):
            form.apply()
            flash(_(u'Configuration updated successfully.'), 'configure')
            return redirect_to('admin/configuration')
        else:
            flash(_(u'Could not save the configuration because the '
                    u'configuration is invalid.'), 'error')

    return render_admin_response('admin/configuration.html',
                                 'options.configuration',
                                 form=form.as_widget(), editor_enabled=
                                 request.session.get('ace_on', False))


@require_admin_privilege(BLOG_ADMIN)
def maintenance(request):
    """Enable / Disable maintenance mode."""
    cfg = request.app.cfg
    form = MaintenanceModeForm()
    if request.method == 'POST' and form.validate(request.form):
        cfg.change_single('maintenance_mode', not cfg['maintenance_mode'])
        if not cfg['maintenance_mode']:
            flash(_(u'Maintenance mode disabled.  The blog is now '
                    u'publicly available.'), 'configure')
        return redirect_to('admin/maintenance')

    return render_admin_response('admin/maintenance.html',
                                 'system.maintenance',
        maintenance_mode=cfg['maintenance_mode'],
        form=form.as_widget()
    )


@require_admin_privilege(BLOG_ADMIN)
def import_dump(request):
    """Show the current import queue or add new items."""
    return render_admin_response('admin/import.html', 'system.import',
        importers=sorted(request.app.importers.values(),
                         key=lambda x: x.title.lower()),
        queue=list_import_queue(request.app)
    )


@require_admin_privilege(BLOG_ADMIN)
def inspect_import(request, id):
    """Inspect a database dump."""
    blog = load_import_dump(request.app, id)
    if blog is None:
        raise NotFound()
    form = make_import_form(blog)

    # perform the actual import here
    if request.method == 'POST':
        if 'cancel' in request.form:
            return redirect_to('admin/maintenance')
        elif 'delete' in request.form:
            return redirect_to('admin/delete_import', id=id)
        elif form.validate(request.form):
            return render_admin_response('admin/perform_import.html',
                                         'system.import',
                live_log=form.perform_import(),
                _stream=True
            )

    return render_admin_response('admin/inspect_import.html',
                                 'system.import', blog=blog,
                                 form=form.as_widget(), dump_id=id)


@require_admin_privilege(BLOG_ADMIN)
def delete_import(request, id):
    """Delete an imported file."""
    dump = load_import_dump(request.app, id)
    if dump is None:
        raise NotFound()
    form = DeleteImportForm()

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('cancel'):
            return form.redirect('admin/inspect_import', id=id)
        elif request.form.get('confirm'):
            form.add_invalid_redirect_target('admin/inspect_import', id=id)
            delete_import_dump(request.app, id)
            flash(_(u'The imported dump “%s” was deleted successfully.') %
                  escape(dump.title), 'remove')
            return form.redirect('admin/import')

    return render_admin_response('admin/delete_import.html',
                                 'system.import',
        dump=dump,
        form=form.as_widget()
    )


@require_admin_privilege(BLOG_ADMIN)
def export(request):
    """Export the blog to the ZXA format."""
    form = ExportForm()

    if request.method == 'POST' and form.validate(request.form):
        if request.form.get('format') == 'zxa':
            from zine.zxa import export
            response = export(request.app)
            response.headers['Content-Disposition'] = 'attachment; ' \
                'filename="%s.zxa"' % '_'.join(request.app.cfg['blog_title'].split())
            return response
    return render_admin_response('admin/export.html', 'system.export',
        form=form.as_widget()
    )


@require_admin_privilege(BLOG_ADMIN)
def information(request):
    """Shows some details about this Zine installation.  It's useful for
    debugging and checking configurations.  If severe errors in a Zine
    installation occur it's a good idea to dump this page and attach it to
    a bug report mail.
    """
    from platform import platform
    from sys import version as python_version
    from threading import activeCount
    from jinja2.defaults import DEFAULT_NAMESPACE, DEFAULT_FILTERS
    from zine import environment, __version__ as zine_version

    export = request.args.get('do') == 'export'
    database_uri = request.app.cfg['database_uri']
    if export:
        database_uri = secure_database_uri(database_uri)

    content_types = {}
    for name, func in request.app.content_type_handlers.iteritems():
        content_types[name] = {'name': name, 'show': get_object_name(func)}
    for name, funcs in request.app.admin_content_type_handlers.iteritems():
        if name in content_types:
            for action, func in funcs.iteritems():
                content_types[name][action] = get_object_name(func)
    content_types = sorted(content_types.values(), key=lambda x: x['name'])

    response = render_admin_response('admin/information.html', 'system.information',
        apis=[{
            'name':         name,
            'blog_id':      blog_id,
            'preferred':    preferred,
            'endpoint':     endpoint
        } for name, (blog_id, preferred, endpoint) in request.app.apis.iteritems()],
        endpoints=[{
            'name':         rule.endpoint,
            'rule':         unicode(rule)
        } for rule in sorted(request.app.url_map._rules, key=lambda x: x.endpoint)],
        views=sorted([{
            'endpoint':     endpoint,
            'handler':      get_object_name(view)
        } for endpoint, view
            in request.app.views.iteritems()], key=lambda x: x['endpoint']),
        markup_extensions=[{
            'name':         handler.name,
            'objname':      get_object_name(handler)
        } for handler in sorted(request.app.markup_extensions,
                                key=lambda x: x.name)],
        parsers=[{
            'key':          key,
            'name':         parser.name,
            'id':           get_object_name(parser)
        } for key, parser in request.app.parsers.iteritems()],
        absolute_url_handlers=[get_object_name(handler) for handler
                               in request.app._absolute_url_handlers],
        content_types=content_types,
        privileges=request.app.list_privileges(),
        servicepoints=sorted([{
            'name':         name,
            'handler':      get_object_name(service)
        } for name, service in request.app._services.iteritems()],
            key=lambda x: x['name']),
        configuration=request.app.cfg.get_public_list(export),
        hosting_env={
            'persistent':       not request.is_run_once,
            'multithreaded':    request.is_multithread,
            'thread_count':     activeCount(),
            'multiprocess':     request.is_multiprocess,
            'wsgi_version':     '.'.join(map(str, request.environ['wsgi.version']))
        },
        plugins=sorted(request.app.plugins.values(), key=lambda x: not x.active and x.name),
        python_version='<br>'.join(map(escape, python_version.splitlines())),
        zine_env=environment,
        zine_version=zine_version,
        template_globals=[name for name, obj in
                          sorted(request.app.template_env.globals.items())
                          if name not in DEFAULT_NAMESPACE],
        template_filters=[name for name, obj in
                          sorted(request.app.template_env.filters.items())
                          if name not in DEFAULT_FILTERS],
        instance_path=request.app.instance_folder,
        database_uri=database_uri,
        platform=platform(),
        export=export
    )

    if export:
        response.headers['Content-Disposition'] = 'attachment; ' \
            'filename="zine-environment.html"'

    return response


@require_admin_privilege(BLOG_ADMIN)
def log(request, page):
    page = request.app.log.view().get_page(page)
    form = LogOptionsForm()
    if request.method == 'POST' and form.validate(request.form):
        form.apply()
        flash(_(u'Log changes saved.'), 'configure')
        return redirect_to('admin/log', page=page.number)
    return render_admin_response('admin/log.html', 'system.log',
                                 page=page, form=form.as_widget())


@require_admin_privilege()
def change_password(request):
    """Allow the current user to change his password."""
    form = ChangePasswordForm(request.user)

    if request.method == 'POST':
        if request.form.get('cancel'):
            return form.redirect('admin/index')
        if form.validate(request.form):
            form.user.set_password(form['new_password'])
            db.commit()
            flash(_(u'Password changed successfully.'), 'configure')
            return form.redirect('admin/index')

    return render_admin_response('admin/change_password.html',
        form=form.as_widget()
    )

@require_admin_privilege()
def help(req, page=''):
    """Show help page."""
    from zine.docs import load_page, get_resource

    rv = load_page(req.app, page)
    if rv is None:
        resource = get_resource(req.app, page)
        if resource is None:
            return render_admin_response('admin/help_404.html', 'system.help')
        return resource

    parts, is_index = rv
    ends_with_slash = not page or page.endswith('/')
    if is_index and not ends_with_slash:
        return redirect_to('admin/help', page=page + '/')
    elif not is_index and ends_with_slash:
        raise NotFound()

    return render_admin_response('admin/help.html', 'system.help', **parts)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.