Source

galaxy-central / lib / galaxy / webapps / galaxy / controllers / history.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
from galaxy.web.base.controller import *
from galaxy.web.framework.helpers import time_ago, iff, grids
from galaxy.datatypes.data import nice_size
from galaxy import model, util
from galaxy.util.odict import odict
from galaxy.model.mapping import desc
from galaxy.model.orm import *
from galaxy.model.item_attrs import *
from galaxy.util.json import *
from galaxy.util.sanitize_html import sanitize_html
from galaxy.tools.parameters.basic import UnvalidatedValue
from galaxy.tools.actions import upload_common
from galaxy.tags.tag_handler import GalaxyTagHandler
from sqlalchemy.sql.expression import ClauseElement, func
from sqlalchemy.sql import select
import webhelpers, logging, operator, os, tempfile, subprocess, shutil, tarfile
from datetime import datetime
from cgi import escape

log = logging.getLogger( __name__ )

class NameColumn( grids.TextColumn ):
    def get_value( self, trans, grid, history ):
        return history.get_display_name()

class HistoryListGrid( grids.Grid ):
    # Custom column types
    class DatasetsByStateColumn( grids.GridColumn ):
        def get_value( self, trans, grid, history ):
            # Build query to get (state, count) pairs.
            cols_to_select = [ trans.app.model.Dataset.table.c.state, func.count( '*' ) ] 
            from_obj = trans.app.model.HistoryDatasetAssociation.table.join( trans.app.model.Dataset.table )
            where_clause = and_( trans.app.model.HistoryDatasetAssociation.table.c.history_id == history.id,
                                 trans.app.model.HistoryDatasetAssociation.table.c.deleted == False,
                                 trans.app.model.HistoryDatasetAssociation.table.c.visible == True,
                                  )
            group_by = trans.app.model.Dataset.table.c.state
            query = select( columns=cols_to_select,
                            from_obj=from_obj,
                            whereclause=where_clause,
                            group_by=group_by )
                            
            # Process results.
            state_count_dict = {}
            for row in trans.sa_session.execute( query ):
                state, count = row
                state_count_dict[ state ] = count
            rval = []
            for state in ( 'ok', 'running', 'queued', 'error' ):
                count = state_count_dict.get( state, 0 )
                if count:
                    rval.append( '<div class="count-box state-color-%s">%s</div>' % ( state, count ) )
                else:
                    rval.append( '' )
            return rval
    class HistoryListNameColumn( NameColumn ):
        def get_link( self, trans, grid, history ):
            link = None
            if not history.deleted:
                link = dict( operation="Switch", id=history.id, use_panels=grid.use_panels )
            return link
    class DeletedColumn( grids.DeletedColumn ):
        def get_value( self, trans, grid, history ):
            if history == trans.history:
                return "<strong>current history</strong>"
            if history.purged:
                return "deleted permanently"
            elif history.deleted:
                return "deleted"
            return ""
        def sort( self, trans, query, ascending, column_name=None ):
            if ascending:
                query = query.order_by( self.model_class.table.c.purged.asc(), self.model_class.table.c.update_time.desc() )
            else:
                query = query.order_by( self.model_class.table.c.purged.desc(), self.model_class.table.c.update_time.desc() )
            return query

    # Grid definition
    title = "Saved Histories"
    model_class = model.History
    template='/history/grid.mako'
    default_sort_key = "-update_time"
    columns = [
        HistoryListNameColumn( "Name", key="name", attach_popup=True, filterable="advanced" ),
        DatasetsByStateColumn( "Datasets", key="datasets_by_state", ncells=4, sortable=False ),
        grids.IndividualTagsColumn( "Tags", key="tags", model_tag_association_class=model.HistoryTagAssociation, \
                                    filterable="advanced", grid_name="HistoryListGrid" ),
        grids.SharingStatusColumn( "Sharing", key="sharing", filterable="advanced", sortable=False ),
        grids.GridColumn( "Size on Disk", key="get_disk_size_bytes", format=nice_size, sortable=False ),
        grids.GridColumn( "Created", key="create_time", format=time_ago ),
        grids.GridColumn( "Last Updated", key="update_time", format=time_ago ),
        DeletedColumn( "Status", key="deleted", filterable="advanced" )
    ]
    columns.append(
        grids.MulticolFilterColumn(
        "search history names and tags",
        cols_to_filter=[ columns[0], columns[2] ],
        key="free-text-search", visible=False, filterable="standard" )
                )
    operations = [
        grids.GridOperation( "Switch", allow_multiple=False, condition=( lambda item: not item.deleted ), async_compatible=False ),
        grids.GridOperation( "View", allow_multiple=False ),
        grids.GridOperation( "Share or Publish", allow_multiple=False, condition=( lambda item: not item.deleted ), async_compatible=False ),
        grids.GridOperation( "Rename", condition=( lambda item: not item.deleted ), async_compatible=False  ),
        grids.GridOperation( "Delete", condition=( lambda item: not item.deleted ), async_compatible=True ),
        grids.GridOperation( "Delete Permanently", condition=( lambda item: not item.purged ), confirm="History contents will be removed from disk, this cannot be undone.  Continue?", async_compatible=True ),
        grids.GridOperation( "Undelete", condition=( lambda item: item.deleted and not item.purged ), async_compatible=True ),
    ]
    standard_filters = [
        grids.GridColumnFilter( "Active", args=dict( deleted=False ) ),
        grids.GridColumnFilter( "Deleted", args=dict( deleted=True ) ),
        grids.GridColumnFilter( "All", args=dict( deleted='All' ) ),
    ]
    default_filter = dict( name="All", deleted="False", tags="All", sharing="All" )
    num_rows_per_page = 50
    preserve_state = False
    use_async = True
    use_paging = True
    def get_current_item( self, trans, **kwargs ):
        return trans.get_history()
    def apply_query_filter( self, trans, query, **kwargs ):
        return query.filter_by( user=trans.user, importing=False )

class SharedHistoryListGrid( grids.Grid ):
    # Custom column types
    class DatasetsByStateColumn( grids.GridColumn ):
        def get_value( self, trans, grid, history ):
            rval = []
            for state in ( 'ok', 'running', 'queued', 'error' ):
                total = sum( 1 for d in history.active_datasets if d.state == state )
                if total:
                    rval.append( '<div class="count-box state-color-%s">%s</div>' % ( state, total ) )
                else:
                    rval.append( '' )
            return rval
    class SharedByColumn( grids.GridColumn ):
        def get_value( self, trans, grid, history ):
            return history.user.email
    # Grid definition
    title = "Histories shared with you by others"
    model_class = model.History
    default_sort_key = "-update_time"
    default_filter = {}
    columns = [
        grids.GridColumn( "Name", key="name", attach_popup=True ), # link=( lambda item: dict( operation="View", id=item.id ) ), attach_popup=True ),
        DatasetsByStateColumn( "Datasets", ncells=4, sortable=False ),
        grids.GridColumn( "Created", key="create_time", format=time_ago ),
        grids.GridColumn( "Last Updated", key="update_time", format=time_ago ),
        SharedByColumn( "Shared by", key="user_id" )
    ]
    operations = [
        grids.GridOperation( "View", allow_multiple=False, target="_top" ),
        grids.GridOperation( "Clone" ),
        grids.GridOperation( "Unshare" )
    ]
    standard_filters = []
    def build_initial_query( self, trans, **kwargs ):
        return trans.sa_session.query( self.model_class ).join( 'users_shared_with' )
    def apply_query_filter( self, trans, query, **kwargs ):
        return query.filter( model.HistoryUserShareAssociation.user == trans.user )

class HistoryAllPublishedGrid( grids.Grid ):
    class NameURLColumn( grids.PublicURLColumn, NameColumn ):
        pass

    title = "Published Histories"
    model_class = model.History
    default_sort_key = "update_time"
    default_filter = dict( public_url="All", username="All", tags="All" )
    use_async = True
    columns = [
        NameURLColumn( "Name", key="name", filterable="advanced" ),
        grids.OwnerAnnotationColumn( "Annotation", key="annotation", model_annotation_association_class=model.HistoryAnnotationAssociation, filterable="advanced" ),
        grids.OwnerColumn( "Owner", key="username", model_class=model.User, filterable="advanced" ),
        grids.CommunityRatingColumn( "Community Rating", key="rating" ),
        grids.CommunityTagsColumn( "Community Tags", key="tags", model_tag_association_class=model.HistoryTagAssociation, filterable="advanced", grid_name="PublicHistoryListGrid" ),
        grids.ReverseSortColumn( "Last Updated", key="update_time", format=time_ago )
    ]
    columns.append(
        grids.MulticolFilterColumn(
        "Search name, annotation, owner, and tags",
        cols_to_filter=[ columns[0], columns[1], columns[2], columns[4] ],
        key="free-text-search", visible=False, filterable="standard" )
                )
    operations = []
    def build_initial_query( self, trans, **kwargs ):
        # Join so that searching history.user makes sense.
        return trans.sa_session.query( self.model_class ).join( model.User.table )
    def apply_query_filter( self, trans, query, **kwargs ):
        # A public history is published, has a slug, and is not deleted.
        return query.filter( self.model_class.published == True ).filter( self.model_class.slug != None ).filter( self.model_class.deleted == False )

class HistoryController( BaseUIController, SharableMixin, UsesAnnotations, UsesItemRatings, UsesHistoryMixin ):
    @web.expose
    def index( self, trans ):
        return ""
    @web.expose
    def list_as_xml( self, trans ):
        """XML history list for functional tests"""
        trans.response.set_content_type( 'text/xml' )
        return trans.fill_template( "/history/list_as_xml.mako" )

    stored_list_grid = HistoryListGrid()
    shared_list_grid = SharedHistoryListGrid()
    published_list_grid = HistoryAllPublishedGrid()

    @web.expose
    def list_published( self, trans, **kwargs ):
        grid = self.published_list_grid( trans, **kwargs )
        if 'async' in kwargs:
            return grid
        else:
            # Render grid wrapped in panels
            return trans.fill_template( "history/list_published.mako", grid=grid )

    @web.expose
    @web.require_login( "work with multiple histories" )
    def list( self, trans, **kwargs ):
        """List all available histories"""
        current_history = trans.get_history()
        status = message = None
        if 'operation' in kwargs:
            operation = kwargs['operation'].lower()
            if operation == "share or publish":
                return self.sharing( trans, **kwargs )
            if operation == "rename" and kwargs.get('id', None): # Don't call rename if no ids
                if 'name' in kwargs:
                    del kwargs['name'] # Remove ajax name param that rename method uses
                return self.rename( trans, **kwargs )
            if operation == "view":
                history = self.get_history( trans, kwargs.get( 'id', None ) )
                if history:
                    return trans.response.send_redirect( url_for( controller='history',
                                                                  action='view',
                                                                  id=kwargs['id'],
                                                                  show_deleted=history.deleted,
                                                                  use_panels=False ) )
                    #return self.view( trans, id=kwargs['id'], show_deleted=history.deleted, use_panels=False )
            history_ids = util.listify( kwargs.get( 'id', [] ) )
            # Display no message by default
            status, message = None, None
            refresh_history = False
            # Load the histories and ensure they all belong to the current user
            histories = []
            for history_id in history_ids:
                history = self.get_history( trans, history_id )
                if history:
                    # Ensure history is owned by current user
                    if history.user_id != None and trans.user:
                        assert trans.user.id == history.user_id, "History does not belong to current user"
                    histories.append( history )
                else:
                    log.warn( "Invalid history id '%r' passed to list", history_id )
            if histories:
                if operation == "switch":
                    status, message = self._list_switch( trans, histories )
                    # Take action to update UI to reflect history switch. If
                    # grid is using panels, it is standalone and hence a redirect
                    # to root is needed; if grid is not using panels, it is nested
                    # in the main Galaxy UI and refreshing the history frame
                    # is sufficient.
                    use_panels = kwargs.get('use_panels', False) == 'True'
                    if use_panels:
                        return trans.response.send_redirect( url_for( "/" ) )
                    else:
                        trans.template_context['refresh_frames'] = ['history']
                elif operation in ( "delete", "delete permanently" ):
                    if operation == "delete permanently":
                        status, message = self._list_delete( trans, histories, purge=True )
                    else:
                        status, message = self._list_delete( trans, histories )
                    if current_history in histories:
                        # Deleted the current history, so a new, empty history was
                        # created automatically, and we need to refresh the history frame
                        trans.template_context['refresh_frames'] = ['history']
                elif operation == "undelete":
                    status, message = self._list_undelete( trans, histories )
                elif operation == "unshare":
                    for history in histories:
                        for husa in trans.sa_session.query( trans.app.model.HistoryUserShareAssociation ) \
                                                    .filter_by( history=history ):
                            trans.sa_session.delete( husa )
                elif operation == "enable import via link":
                    for history in histories:
                        if not history.importable:
                            self._make_item_importable( trans.sa_session, history )
                elif operation == "disable import via link":
                    if history_ids:
                        histories = [ self.get_history( trans, history_id ) for history_id in history_ids ]
                        for history in histories:
                            if history.importable:
                                history.importable = False
                trans.sa_session.flush()
        # Render the list view
        return self.stored_list_grid( trans, status=status, message=message, **kwargs )
    def _list_delete( self, trans, histories, purge=False ):
        """Delete histories"""
        n_deleted = 0
        deleted_current = False
        message_parts = []
        status = SUCCESS
        for history in histories:
            if history.users_shared_with:
                message_parts.append( "History (%s) has been shared with others, unshare it before deleting it.  " % history.name )
                status = ERROR
            elif not history.deleted:
                # We'll not eliminate any DefaultHistoryPermissions in case we undelete the history later
                history.deleted = True
                # If deleting the current history, make a new current.
                if history == trans.get_history():
                    deleted_current = True
                    trans.new_history()
                trans.log_event( "History (%s) marked as deleted" % history.name )
                n_deleted += 1
            if purge and trans.app.config.allow_user_dataset_purge:
                for hda in history.datasets:
                    if trans.user:
                        trans.user.total_disk_usage -= hda.quota_amount( trans.user )
                    hda.purged = True
                    trans.sa_session.add( hda )
                    trans.log_event( "HDA id %s has been purged" % hda.id )
                    trans.sa_session.flush()
                    if hda.dataset.user_can_purge:
                        try:
                            hda.dataset.full_delete()
                            trans.log_event( "Dataset id %s has been purged upon the the purge of HDA id %s" % ( hda.dataset.id, hda.id ) )
                            trans.sa_session.add( hda.dataset )
                        except:
                            log.exception( 'Unable to purge dataset (%s) on purge of hda (%s):' % ( hda.dataset.id, hda.id ) )
                history.purged = True
                self.sa_session.add( history )
                self.sa_session.flush()
        trans.sa_session.flush()
        if n_deleted:
            part = "Deleted %d %s" % ( n_deleted, iff( n_deleted != 1, "histories", "history" ) )
            if purge and trans.app.config.allow_user_dataset_purge:
                part += " and removed %s datasets from disk" % iff( n_deleted != 1, "their", "its" )
            elif purge:
                part += " but the datasets were not removed from disk because that feature is not enabled in this Galaxy instance"
            message_parts.append( "%s.  " % part )
        if deleted_current:
            message_parts.append( "Your active history was deleted, a new empty history is now active.  " )
            status = INFO
        return ( status, " ".join( message_parts ) )
    def _list_undelete( self, trans, histories ):
        """Undelete histories"""
        n_undeleted = 0
        n_already_purged = 0
        for history in histories:
            if history.purged:
                n_already_purged += 1
            if history.deleted:
                history.deleted = False
                if not history.default_permissions:
                    # For backward compatibility - for a while we were deleting all DefaultHistoryPermissions on
                    # the history when we deleted the history.  We are no longer doing this.
                    # Need to add default DefaultHistoryPermissions in case they were deleted when the history was deleted
                    default_action = trans.app.security_agent.permitted_actions.DATASET_MANAGE_PERMISSIONS
                    private_user_role = trans.app.security_agent.get_private_user_role( history.user )
                    default_permissions = {}
                    default_permissions[ default_action ] = [ private_user_role ]
                    trans.app.security_agent.history_set_default_permissions( history, default_permissions )
                n_undeleted += 1
                trans.log_event( "History (%s) %d marked as undeleted" % ( history.name, history.id ) )
        status = SUCCESS
        message_parts = []
        if n_undeleted:
            message_parts.append( "Undeleted %d %s.  " % ( n_undeleted, iff( n_undeleted != 1, "histories", "history" ) ) )
        if n_already_purged:
            message_parts.append( "%d histories have already been purged and cannot be undeleted." % n_already_purged )
            status = WARNING
        return status, "".join( message_parts )
    def _list_switch( self, trans, histories ):
        """Switch to a new different history"""
        new_history = histories[0]
        galaxy_session = trans.get_galaxy_session()
        try:
            association = trans.sa_session.query( trans.app.model.GalaxySessionToHistoryAssociation ) \
                                          .filter_by( session_id=galaxy_session.id, history_id=trans.security.decode_id( new_history.id ) ) \
                                          .first()
        except:
            association = None
        new_history.add_galaxy_session( galaxy_session, association=association )
        trans.sa_session.add( new_history )
        trans.sa_session.flush()
        trans.set_history( new_history )
        # No message
        return None, None

    @web.expose
    @web.require_login( "work with shared histories" )
    def list_shared( self, trans, **kwargs ):
        """List histories shared with current user by others"""
        msg = util.restore_text( kwargs.get( 'msg', '' ) )
        status = message = None
        if 'operation' in kwargs:
            ids = util.listify( kwargs.get( 'id', [] ) )
            operation = kwargs['operation'].lower()
            if operation == "view":
                # Display history.
                history = self.get_history( trans, ids[0], False)
                return self.display_by_username_and_slug( trans, history.user.username, history.slug )
            elif operation == "clone":
                if not ids:
                    message = "Select a history to clone"
                    return self.shared_list_grid( trans, status='error', message=message, **kwargs )
                # When cloning shared histories, only copy active datasets
                new_kwargs = { 'clone_choice' : 'active' }
                return self.clone( trans, ids, **new_kwargs )
            elif operation == 'unshare':
                if not ids:
                    message = "Select a history to unshare"
                    return self.shared_list_grid( trans, status='error', message=message, **kwargs )
                histories = [ self.get_history( trans, history_id ) for history_id in ids ]
                for history in histories:
                    # Current user is the user with which the histories were shared
                    association = trans.sa_session.query( trans.app.model.HistoryUserShareAssociation ).filter_by( user=trans.user, history=history ).one()
                    trans.sa_session.delete( association )
                    trans.sa_session.flush()
                message = "Unshared %d shared histories" % len( ids )
                status = 'done'
        # Render the list view
        return self.shared_list_grid( trans, status=status, message=message, **kwargs )

    @web.expose
    def display_structured( self, trans, id=None ):
        """
        Display a history as a nested structure showing the jobs and workflow
        invocations that created each dataset (if any).
        """
        # Get history
        if id is None:
            id = trans.history.id
        else:
            id = trans.security.decode_id( id )
        # Expunge history from the session to allow us to force a reload
        # with a bunch of eager loaded joins
        trans.sa_session.expunge( trans.history )
        history = trans.sa_session.query( model.History ).options(
                eagerload_all( 'active_datasets.creating_job_associations.job.workflow_invocation_step.workflow_invocation.workflow' ),
                eagerload_all( 'active_datasets.children' )
            ).get( id )
        assert history
        assert history.user and ( history.user.id == trans.user.id ) or ( history.id == trans.history.id )
        # Resolve jobs and workflow invocations for the datasets in the history
        # items is filled with items (hdas, jobs, or workflows) that go at the
        # top level
        items = []
        # First go through and group hdas by job, if there is no job they get
        # added directly to items
        jobs = odict()
        for hda in history.active_datasets:
            if hda.visible == False:
                continue
            # Follow "copied from ..." association until we get to the original
            # instance of the dataset
            original_hda = hda
            ## while original_hda.copied_from_history_dataset_association:
            ##     original_hda = original_hda.copied_from_history_dataset_association
            # Check if the job has a creating job, most should, datasets from
            # before jobs were tracked, or from the upload tool before it
            # created a job, may not
            if not original_hda.creating_job_associations:
                items.append( ( hda, None ) )
            # Attach hda to correct job
            # -- there should only be one creating_job_association, so this
            #    loop body should only be hit once
            for assoc in original_hda.creating_job_associations:
                job = assoc.job
                if job in jobs:
                    jobs[ job ].append( ( hda, None ) )
                else:
                    jobs[ job ] = [ ( hda, None ) ]
        # Second, go through the jobs and connect to workflows
        wf_invocations = odict()
        for job, hdas in jobs.iteritems():
            # Job is attached to a workflow step, follow it to the
            # workflow_invocation and group
            if job.workflow_invocation_step:
                wf_invocation = job.workflow_invocation_step.workflow_invocation
                if wf_invocation in wf_invocations:
                    wf_invocations[ wf_invocation ].append( ( job, hdas ) )
                else:
                    wf_invocations[ wf_invocation ] = [ ( job, hdas ) ]
            # Not attached to a workflow, add to items
            else:
                items.append( ( job, hdas ) )
        # Finally, add workflow invocations to items, which should now
        # contain all hdas with some level of grouping
        items.extend( wf_invocations.items() )
        # Sort items by age
        items.sort( key=( lambda x: x[0].create_time ), reverse=True )
        #
        return trans.fill_template( "history/display_structured.mako", items=items )

    @web.expose
    def purge_deleted_datasets( self, trans ):
        count = 0
        if trans.app.config.allow_user_dataset_purge:
            for hda in trans.history.datasets:
                if not hda.deleted or hda.purged:
                    continue
                if trans.user:
                    trans.user.total_disk_usage -= hda.quota_amount( trans.user )
                hda.purged = True
                trans.sa_session.add( hda )
                trans.log_event( "HDA id %s has been purged" % hda.id )
                trans.sa_session.flush()
                if hda.dataset.user_can_purge:
                    try:
                        hda.dataset.full_delete()
                        trans.log_event( "Dataset id %s has been purged upon the the purge of HDA id %s" % ( hda.dataset.id, hda.id ) ) 
                        trans.sa_session.add( hda.dataset )
                    except:
                        log.exception( 'Unable to purge dataset (%s) on purge of hda (%s):' % ( hda.dataset.id, hda.id ) )
                count += 1
        return trans.show_ok_message( "%d datasets have been deleted permanently" % count, refresh_frames=['history'] )

    @web.expose
    def delete_current( self, trans, purge=False ):
        """Delete just the active history -- this does not require a logged in user."""
        history = trans.get_history()
        if history.users_shared_with:
            return trans.show_error_message( "History (%s) has been shared with others, unshare it before deleting it.  " % history.name )
        if not history.deleted:
            history.deleted = True
            trans.sa_session.add( history )
            trans.sa_session.flush()
            trans.log_event( "History id %d marked as deleted" % history.id )
        if purge and trans.app.config.allow_user_dataset_purge:
            for hda in history.datasets:
                if trans.user:
                    trans.user.total_disk_usage -= hda.quota_amount( trans.user )
                hda.purged = True
                trans.sa_session.add( hda )
                trans.log_event( "HDA id %s has been purged" % hda.id )
                trans.sa_session.flush()
                if hda.dataset.user_can_purge:
                    try:
                        hda.dataset.full_delete()
                        trans.log_event( "Dataset id %s has been purged upon the the purge of HDA id %s" % ( hda.dataset.id, hda.id ) )
                        trans.sa_session.add( hda.dataset )
                    except:
                        log.exception( 'Unable to purge dataset (%s) on purge of hda (%s):' % ( hda.dataset.id, hda.id ) )
            history.purged = True
            self.sa_session.add( history )
            self.sa_session.flush()
        # Regardless of whether it was previously deleted, we make a new history active
        trans.new_history()
        return trans.show_ok_message( "History deleted, a new history is active", refresh_frames=['history'] )

    @web.expose
    def unhide_datasets( self, trans, current=False, ids=None ):
        """Unhide the datasets in the active history -- this does not require a logged in user."""
        if not ids and util.string_as_bool( current ):
            histories = [ trans.get_history() ]
            refresh_frames = ['history']
        else:
            raise NotImplementedError( "You can currently only unhide all the datasets of the current history." )
        for history in histories:
            history.unhide_datasets()
            trans.sa_session.add( history )
        trans.sa_session.flush()
        return trans.show_ok_message( "Your datasets have been unhidden.", refresh_frames=refresh_frames )

    @web.expose
    def resume_paused_jobs( self, trans, current=False, ids=None ):
        """Resume paused jobs the active history -- this does not require a logged in user."""
        if not ids and util.string_as_bool( current ):
            histories = [ trans.get_history() ]
            refresh_frames = ['history']
        else:
            raise NotImplementedError( "You can currently only resume all the datasets of the current history." )
        for history in histories:
            history.resume_paused_jobs()
            trans.sa_session.add( history )
        trans.sa_session.flush()
        return trans.show_ok_message( "Your jobs have been resumed.", refresh_frames=refresh_frames )

    @web.expose
    @web.require_login( "rate items" )
    @web.json
    def rate_async( self, trans, id, rating ):
        """ Rate a history asynchronously and return updated community data. """
        history = self.get_history( trans, id, check_ownership=False, check_accessible=True )
        if not history:
            return trans.show_error_message( "The specified history does not exist." )
        # Rate history.
        history_rating = self.rate_item( trans.sa_session, trans.get_user(), history, rating )
        return self.get_ave_item_rating_data( trans.sa_session, history )

    @web.expose
    def rename_async( self, trans, id=None, new_name=None ):
        history = self.get_history( trans, id )
        # Check that the history exists, and is either owned by the current
        # user (if logged in) or the current history
        assert history is not None
        if history.user is None:
            assert history == trans.get_history()
        else:
            assert history.user == trans.user
        # Rename
        history.name = sanitize_html( new_name )
        trans.sa_session.add( history )
        trans.sa_session.flush()
        return history.name

    @web.expose
    @web.require_login( "use Galaxy histories" )
    def annotate_async( self, trans, id, new_annotation=None, **kwargs ):
        history = self.get_history( trans, id )
        if new_annotation:
            # Sanitize annotation before adding it.
            new_annotation = sanitize_html( new_annotation, 'utf-8', 'text/html' )
            self.add_item_annotation( trans.sa_session, trans.get_user(), history, new_annotation )
            trans.sa_session.flush()
            return new_annotation

    @web.expose
    # TODO: Remove require_login when users are warned that, if they are not
    # logged in, this will remove their current history.
    @web.require_login( "use Galaxy histories" )
    def import_archive( self, trans, **kwargs ):
        """ Import a history from a file archive. """
        # Set archive source and type.
        archive_file = kwargs.get( 'archive_file', None )
        archive_url = kwargs.get( 'archive_url', None )
        archive_source = None
        if archive_file:
            archive_source = archive_file
            archive_type = 'file'
        elif archive_url:
            archive_source = archive_url
            archive_type = 'url'
        # If no source to create archive from, show form to upload archive or specify URL.
        if not archive_source:
            return trans.show_form(
                web.FormBuilder( web.url_for(), "Import a History from an Archive", submit_text="Submit" ) \
                    .add_input( "text", "Archived History URL", "archive_url", value="", error=None )
                    # TODO: add support for importing via a file.
                    #.add_input( "file", "Archived History File", "archive_file", value=None, error=None )
                                )
        # Run job to do import.
        history_imp_tool = trans.app.toolbox.get_tool( '__IMPORT_HISTORY__' )
        incoming = { '__ARCHIVE_SOURCE__' : archive_source, '__ARCHIVE_TYPE__' : archive_type }
        history_imp_tool.execute( trans, incoming=incoming )
        return trans.show_message( "Importing history from '%s'. \
                                    This history will be visible when the import is complete" % archive_source )

    @web.expose
    def export_archive( self, trans, id=None, gzip=True, include_hidden=False, include_deleted=False ):
        """ Export a history to an archive. """
        #
        # Convert options to booleans.
        #
        if isinstance( gzip, basestring ):
            gzip = ( gzip in [ 'True', 'true', 'T', 't' ] )
        if isinstance( include_hidden, basestring ):
            include_hidden = ( include_hidden in [ 'True', 'true', 'T', 't' ] )
        if isinstance( include_deleted, basestring ):
            include_deleted = ( include_deleted in [ 'True', 'true', 'T', 't' ] )

        #
        # Get history to export.
        #
        if id:
            history = self.get_history( trans, id, check_ownership=False, check_accessible=True )
        else:
            # Use current history.
            history = trans.history
            id = trans.security.encode_id( history.id )

        if not history:
            return trans.show_error_message( "This history does not exist or you cannot export this history." )

        #
        # If history has already been exported and it has not changed since export, stream it.
        #
        jeha = trans.sa_session.query( model.JobExportHistoryArchive ).filter_by( history=history ) \
                .order_by( model.JobExportHistoryArchive.id.desc() ).first()
        if jeha and ( jeha.job.state not in [ model.Job.states.ERROR, model.Job.states.DELETED ] ) \
           and jeha.job.update_time > history.update_time:
            if jeha.job.state == model.Job.states.OK:
                # Stream archive.
                valid_chars = '.,^_-()[]0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
                hname = history.name
                hname = ''.join(c in valid_chars and c or '_' for c in hname)[0:150]
                hname = "Galaxy-History-%s.tar" % ( hname )
                if jeha.compressed:
                    hname += ".gz"
                    trans.response.set_content_type( 'application/x-gzip' )
                else:
                    trans.response.set_content_type( 'application/x-tar' )
                trans.response.headers["Content-Disposition"] = 'attachment; filename="%s"' % ( hname )
                return open( trans.app.object_store.get_filename( jeha.dataset ) )
            elif jeha.job.state in [ model.Job.states.RUNNING, model.Job.states.QUEUED, model.Job.states.WAITING ]:
                return trans.show_message( "Still exporting history %(n)s; please check back soon. Link: <a href='%(s)s'>%(s)s</a>" \
                        % ( { 'n' : history.name, 's' : url_for( action="export_archive", id=id, qualified=True ) } ) )

        # Run job to do export.
        history_exp_tool = trans.app.toolbox.get_tool( '__EXPORT_HISTORY__' )
        params = {
            'history_to_export' : history,
            'compress' : gzip,
            'include_hidden' : include_hidden,
            'include_deleted' : include_deleted }
        history_exp_tool.execute( trans, incoming = params, set_output_hid = True )
        return trans.show_message( "Exporting History '%(n)s'. Use this link to download \
                                    the archive or import it to another Galaxy server: \
                                    <a href='%(u)s'>%(u)s</a>" \
                                    % ( { 'n' : history.name, 'u' : url_for( action="export_archive", id=id, qualified=True ) } ) )

    @web.expose
    @web.json
    @web.require_login( "get history name and link" )
    def get_name_and_link_async( self, trans, id=None ):
        """ Returns history's name and link. """
        history = self.get_history( trans, id, False )
        if self.create_item_slug( trans.sa_session, history ):
            trans.sa_session.flush()
        return_dict = {
            "name" : history.name,
            "link" : url_for( action="display_by_username_and_slug", username=history.user.username, slug=history.slug ) }
        return return_dict

    @web.expose
    @web.require_login( "set history's accessible flag" )
    def set_accessible_async( self, trans, id=None, accessible=False ):
        """ Set history's importable attribute and slug. """
        history = self.get_history( trans, id, True )
        # Only set if importable value would change; this prevents a change in the update_time unless attribute really changed.
        importable = accessible in ['True', 'true', 't', 'T'];
        if history and history.importable != importable:
            if importable:
                self._make_item_accessible( trans.sa_session, history )
            else:
                history.importable = importable
            trans.sa_session.flush()
        return

    @web.expose
    def get_item_content_async( self, trans, id ):
        """ Returns item content in HTML format. """

        history = self.get_history( trans, id, False, True )
        if history is None:
            raise web.httpexceptions.HTTPNotFound()

        # Get datasets.
        datasets = self.get_history_datasets( trans, history )
        # Get annotations.
        history.annotation = self.get_item_annotation_str( trans.sa_session, history.user, history )
        for dataset in datasets:
            dataset.annotation = self.get_item_annotation_str( trans.sa_session, history.user, dataset )
        return trans.stream_template_mako( "/history/item_content.mako", item = history, item_data = datasets )

    @web.expose
    def name_autocomplete_data( self, trans, q=None, limit=None, timestamp=None ):
        """Return autocomplete data for history names"""
        user = trans.get_user()
        if not user:
            return

        ac_data = ""
        for history in trans.sa_session.query( model.History ).filter_by( user=user ).filter( func.lower( model.History.name ) .like(q.lower() + "%") ):
            ac_data = ac_data + history.name + "\n"
        return ac_data

    @web.expose
    def imp( self, trans, id=None, confirm=False, **kwd ):
        """Import another user's history via a shared URL"""
        msg = ""
        user = trans.get_user()
        user_history = trans.get_history()
        # Set referer message
        if 'referer' in kwd:
            referer = kwd['referer']
        else:
            referer = trans.request.referer
        if referer is not "":
            referer_message = "<a href='%s'>return to the previous page</a>" % referer
        else:
            referer_message = "<a href='%s'>go to Galaxy's start page</a>" % url_for( '/' )

        # Do import.
        if not id:
            return trans.show_error_message( "You must specify a history you want to import.<br>You can %s." % referer_message, use_panels=True )
        import_history = self.get_history( trans, id, check_ownership=False, check_accessible=False )
        if not import_history:
            return trans.show_error_message( "The specified history does not exist.<br>You can %s." % referer_message, use_panels=True )
        # History is importable if user is admin or it's accessible. TODO: probably want to have app setting to enable admin access to histories.
        if not trans.user_is_admin() and not self.security_check( trans, import_history, check_ownership=False, check_accessible=True ):
            return trans.show_error_message( "You cannot access this history.<br>You can %s." % referer_message, use_panels=True )
        if user:
            #dan: I can import my own history.
            #if import_history.user_id == user.id:
            #    return trans.show_error_message( "You cannot import your own history.<br>You can %s." % referer_message, use_panels=True )
            new_history = import_history.copy( target_user=user )
            new_history.name = "imported: " + new_history.name
            new_history.user_id = user.id
            galaxy_session = trans.get_galaxy_session()
            try:
                association = trans.sa_session.query( trans.app.model.GalaxySessionToHistoryAssociation ) \
                                              .filter_by( session_id=galaxy_session.id, history_id=new_history.id ) \
                                              .first()
            except:
                association = None
            new_history.add_galaxy_session( galaxy_session, association=association )
            trans.sa_session.add( new_history )
            trans.sa_session.flush()
            # Set imported history to be user's current history.
            trans.set_history( new_history )
            return trans.show_ok_message(
                message="""History "%s" has been imported. <br>You can <a href="%s">start using this history</a> or %s."""
                % ( new_history.name, web.url_for( '/' ), referer_message ), use_panels=True )
        elif not user_history or not user_history.datasets or confirm:
            new_history = import_history.copy()
            new_history.name = "imported: " + new_history.name
            new_history.user_id = None
            galaxy_session = trans.get_galaxy_session()
            try:
                association = trans.sa_session.query( trans.app.model.GalaxySessionToHistoryAssociation ) \
                                              .filter_by( session_id=galaxy_session.id, history_id=new_history.id ) \
                                              .first()
            except:
                association = None
            new_history.add_galaxy_session( galaxy_session, association=association )
            trans.sa_session.add( new_history )
            trans.sa_session.flush()
            trans.set_history( new_history )
            return trans.show_ok_message(
                message="""History "%s" has been imported. <br>You can <a href="%s">start using this history</a> or %s."""
                % ( new_history.name, web.url_for( '/' ), referer_message ), use_panels=True )
        return trans.show_warn_message( """
            Warning! If you import this history, you will lose your current
            history. <br>You can <a href="%s">continue and import this history</a> or %s.
            """ % ( web.url_for( id=id, confirm=True, referer=trans.request.referer ), referer_message ), use_panels=True )

    @web.expose
    def view( self, trans, id=None, show_deleted=False, use_panels=True ):
        """View a history. If a history is importable, then it is viewable by any user."""
        # Get history to view.
        if not id:
            return trans.show_error_message( "You must specify a history you want to view." )
        history_to_view = self.get_history( trans, id, False)
        # Integrity checks.
        if not history_to_view:
            return trans.show_error_message( "The specified history does not exist." )
        # Admin users can view any history
        if not trans.user_is_admin() and not history_to_view.importable:
            error( "Either you are not allowed to view this history or the owner of this history has not made it accessible." )
        # View history.
        show_deleted = util.string_as_bool( show_deleted )
        datasets = self.get_history_datasets( trans, history_to_view, show_deleted=show_deleted )
        try:
            use_panels = util.string_as_bool( use_panels )
        except:
            pass # already a bool
        return trans.stream_template_mako( "history/view.mako",
                                           history = history_to_view,
                                           datasets = datasets,
                                           show_deleted = show_deleted,
                                           use_panels = use_panels )

    @web.expose
    def display_by_username_and_slug( self, trans, username, slug ):
        """ Display history based on a username and slug. """

        # Get history.
        session = trans.sa_session
        user = session.query( model.User ).filter_by( username=username ).first()
        history = trans.sa_session.query( model.History ).filter_by( user=user, slug=slug, deleted=False ).first()
        if history is None:
           raise web.httpexceptions.HTTPNotFound()
        # Security check raises error if user cannot access history.
        self.security_check( trans, history, False, True)

        # Get datasets.
        datasets = self.get_history_datasets( trans, history )
        # Get annotations.
        history.annotation = self.get_item_annotation_str( trans.sa_session, history.user, history )
        for dataset in datasets:
            dataset.annotation = self.get_item_annotation_str( trans.sa_session, history.user, dataset )

        # Get rating data.
        user_item_rating = 0
        if trans.get_user():
            user_item_rating = self.get_user_item_rating( trans.sa_session, trans.get_user(), history )
            if user_item_rating:
                user_item_rating = user_item_rating.rating
            else:
                user_item_rating = 0
        ave_item_rating, num_ratings = self.get_ave_item_rating_data( trans.sa_session, history )
        return trans.stream_template_mako( "history/display.mako", item = history, item_data = datasets,
                                            user_item_rating = user_item_rating, ave_item_rating=ave_item_rating, num_ratings=num_ratings )

    @web.expose
    @web.require_login( "share Galaxy histories" )
    def sharing( self, trans, id=None, histories=[], **kwargs ):
        """ Handle history sharing. """

        # Get session and histories.
        session = trans.sa_session
        # Id values take precedence over histories passed in; last resort is current history.
        if id:
            ids = util.listify( id )
            if ids:
                histories = [ self.get_history( trans, history_id ) for history_id in ids ]
        elif not histories:
            histories = [ trans.history ]

        # Do operation on histories.
        for history in histories:
            if 'make_accessible_via_link' in kwargs:
                self._make_item_accessible( trans.sa_session, history )
            elif 'make_accessible_and_publish' in kwargs:
                self._make_item_accessible( trans.sa_session, history )
                history.published = True
            elif 'publish' in kwargs:
                if history.importable:
                    history.published = True
                else:
                    # TODO: report error here.
                    pass
            elif 'disable_link_access' in kwargs:
                history.importable = False
            elif 'unpublish' in kwargs:
                history.published = False
            elif 'disable_link_access_and_unpublish' in kwargs:
                history.importable = history.published = False
            elif 'unshare_user' in kwargs:
                user = trans.sa_session.query( trans.app.model.User ).get( trans.security.decode_id( kwargs[ 'unshare_user' ] ) )
                # Look for and delete sharing relation for history-user.
                deleted_sharing_relation = False
                husas = trans.sa_session.query( trans.app.model.HistoryUserShareAssociation ).filter_by( user=user, history=history ).all()
                if husas:
                    deleted_sharing_relation = True
                    for husa in husas:
                        trans.sa_session.delete( husa )
                if not deleted_sharing_relation:
                    message = "History '%s' does not seem to be shared with user '%s'" % ( history.name, user.email )
                    return trans.fill_template( '/sharing_base.mako', item=history,
                                                message=message, status='error' )


        # Legacy issue: histories made accessible before recent updates may not have a slug. Create slug for any histories that need them.
        for history in histories:
            if history.importable and not history.slug:
                self._make_item_accessible( trans.sa_session, history )

        session.flush()

        return trans.fill_template( "/sharing_base.mako", item=history )

    @web.expose
    @web.require_login( "share histories with other users" )
    def share( self, trans, id=None, email="", **kwd ):
        # If a history contains both datasets that can be shared and others that cannot be shared with the desired user,
        # then the entire history is shared, and the protected datasets will be visible, but inaccessible ( greyed out )
        # in the cloned history
        params = util.Params( kwd )
        user = trans.get_user()
        # TODO: we have too many error messages floating around in here - we need
        # to incorporate the messaging system used by the libraries that will display
        # a message on any page.
        err_msg = util.restore_text( params.get( 'err_msg', '' ) )
        if not email:
            if not id:
                # Default to the current history
                id = trans.security.encode_id( trans.history.id )
            id = util.listify( id )
            send_to_err = err_msg
            histories = []
            for history_id in id:
                histories.append( self.get_history( trans, history_id ) )
            return trans.fill_template( "/history/share.mako",
                                        histories=histories,
                                        email=email,
                                        send_to_err=send_to_err )
        histories, send_to_users, send_to_err = self._get_histories_and_users( trans, user, id, email )
        if not send_to_users:
            if not send_to_err:
                send_to_err += "%s is not a valid Galaxy user.  %s" % ( email, err_msg )
            return trans.fill_template( "/history/share.mako",
                                        histories=histories,
                                        email=email,
                                        send_to_err=send_to_err )
        if params.get( 'share_button', False ):
            # The user has not yet made a choice about how to share, so dictionaries will be built for display
            can_change, cannot_change, no_change_needed, unique_no_change_needed, send_to_err = \
                self._populate_restricted( trans, user, histories, send_to_users, None, send_to_err, unique=True )
            send_to_err += err_msg
            if cannot_change and not no_change_needed and not can_change:
                send_to_err = "The histories you are sharing do not contain any datasets that can be accessed by the users with which you are sharing."
                return trans.fill_template( "/history/share.mako", histories=histories, email=email, send_to_err=send_to_err )
            if can_change or cannot_change:
                return trans.fill_template( "/history/share.mako",
                                            histories=histories,
                                            email=email,
                                            send_to_err=send_to_err,
                                            can_change=can_change,
                                            cannot_change=cannot_change,
                                            no_change_needed=unique_no_change_needed )
            if no_change_needed:
                return self._share_histories( trans, user, send_to_err, histories=no_change_needed )
            elif not send_to_err:
                # User seems to be sharing an empty history
                send_to_err = "You cannot share an empty history.  "
        return trans.fill_template( "/history/share.mako", histories=histories, email=email, send_to_err=send_to_err )

    @web.expose
    @web.require_login( "share restricted histories with other users" )
    def share_restricted( self, trans, id=None, email="", **kwd ):
        if 'action' in kwd:
            action = kwd[ 'action' ]
        else:
            err_msg = "Select an action.  "
            return trans.response.send_redirect( url_for( controller='history',
                                                          action='share',
                                                          id=id,
                                                          email=email,
                                                          err_msg=err_msg,
                                                          share_button=True ) )
        user = trans.get_user()
        user_roles = user.all_roles()
        histories, send_to_users, send_to_err = self._get_histories_and_users( trans, user, id, email )
        send_to_err = ''
        # The user has made a choice, so dictionaries will be built for sharing
        can_change, cannot_change, no_change_needed, unique_no_change_needed, send_to_err = \
            self._populate_restricted( trans, user, histories, send_to_users, action, send_to_err )
        # Now that we've populated the can_change, cannot_change, and no_change_needed dictionaries,
        # we'll populate the histories_for_sharing dictionary from each of them.
        histories_for_sharing = {}
        if no_change_needed:
            # Don't need to change anything in cannot_change, so populate as is
            histories_for_sharing, send_to_err = \
                self._populate( trans, histories_for_sharing, no_change_needed, send_to_err )
        if cannot_change:
            # Can't change anything in cannot_change, so populate as is
            histories_for_sharing, send_to_err = \
                self._populate( trans, histories_for_sharing, cannot_change, send_to_err )
        # The action here is either 'public' or 'private', so we'll continue to populate the
        # histories_for_sharing dictionary from the can_change dictionary.
        for send_to_user, history_dict in can_change.items():
            for history in history_dict:
                # Make sure the current history has not already been shared with the current send_to_user
                if trans.sa_session.query( trans.app.model.HistoryUserShareAssociation ) \
                                   .filter( and_( trans.app.model.HistoryUserShareAssociation.table.c.user_id == send_to_user.id,
                                                  trans.app.model.HistoryUserShareAssociation.table.c.history_id == history.id ) ) \
                                   .count() > 0:
                    send_to_err += "History (%s) already shared with user (%s)" % ( history.name, send_to_user.email )
                else:
                    # Only deal with datasets that have not been purged
                    for hda in history.activatable_datasets:
                        # If the current dataset is not public, we may need to perform an action on it to
                        # make it accessible by the other user.
                        if not trans.app.security_agent.can_access_dataset( send_to_user.all_roles(), hda.dataset ):
                            # The user with which we are sharing the history does not have access permission on the current dataset
                            if trans.app.security_agent.can_manage_dataset( user_roles, hda.dataset ) and not hda.dataset.library_associations:
                                # The current user has authority to change permissions on the current dataset because
                                # they have permission to manage permissions on the dataset and the dataset is not associated
                                # with a library.
                                if action == "private":
                                    trans.app.security_agent.privately_share_dataset( hda.dataset, users=[ user, send_to_user ] )
                                elif action == "public":
                                    trans.app.security_agent.make_dataset_public( hda.dataset )
                    # Populate histories_for_sharing with the history after performing any requested actions on
                    # it's datasets to make them accessible by the other user.
                    if send_to_user not in histories_for_sharing:
                        histories_for_sharing[ send_to_user ] = [ history ]
                    elif history not in histories_for_sharing[ send_to_user ]:
                        histories_for_sharing[ send_to_user ].append( history )
        return self._share_histories( trans, user, send_to_err, histories=histories_for_sharing )
    def _get_histories_and_users( self, trans, user, id, email ):
        if not id:
            # Default to the current history
            id = trans.security.encode_id( trans.history.id )
        id = util.listify( id )
        send_to_err = ""
        histories = []
        for history_id in id:
            histories.append( self.get_history( trans, history_id ) )
        send_to_users = []
        for email_address in util.listify( email ):
            email_address = email_address.strip()
            if email_address:
                if email_address == user.email:
                    send_to_err += "You cannot send histories to yourself.  "
                else:
                    send_to_user = trans.sa_session.query( trans.app.model.User ) \
                                                   .filter( and_( trans.app.model.User.table.c.email==email_address,
                                                                  trans.app.model.User.table.c.deleted==False ) ) \
                                                   .first()
                    if send_to_user:
                        send_to_users.append( send_to_user )
                    else:
                        send_to_err += "%s is not a valid Galaxy user.  " % email_address
        return histories, send_to_users, send_to_err
    def _populate( self, trans, histories_for_sharing, other, send_to_err ):
        # This method will populate the histories_for_sharing dictionary with the users and
        # histories in other, eliminating histories that have already been shared with the
        # associated user.  No security checking on datasets is performed.
        # If not empty, the histories_for_sharing dictionary looks like:
        # { userA: [ historyX, historyY ], userB: [ historyY ] }
        # other looks like:
        # { userA: {historyX : [hda, hda], historyY : [hda]}, userB: {historyY : [hda]} }
        for send_to_user, history_dict in other.items():
            for history in history_dict:
                # Make sure the current history has not already been shared with the current send_to_user
                if trans.sa_session.query( trans.app.model.HistoryUserShareAssociation ) \
                                   .filter( and_( trans.app.model.HistoryUserShareAssociation.table.c.user_id == send_to_user.id,
                                                  trans.app.model.HistoryUserShareAssociation.table.c.history_id == history.id ) ) \
                                   .count() > 0:
                    send_to_err += "History (%s) already shared with user (%s)" % ( history.name, send_to_user.email )
                else:
                    # Build the dict that will be used for sharing
                    if send_to_user not in histories_for_sharing:
                        histories_for_sharing[ send_to_user ] = [ history ]
                    elif history not in histories_for_sharing[ send_to_user ]:
                        histories_for_sharing[ send_to_user ].append( history )
        return histories_for_sharing, send_to_err
    def _populate_restricted( self, trans, user, histories, send_to_users, action, send_to_err, unique=False ):
        # The user may be attempting to share histories whose datasets cannot all be accessed by other users.
        # If this is the case, the user sharing the histories can:
        # 1) action=='public': choose to make the datasets public if he is permitted to do so
        # 2) action=='private': automatically create a new "sharing role" allowing protected
        #    datasets to be accessed only by the desired users
        # This method will populate the can_change, cannot_change and no_change_needed dictionaries, which
        # are used for either displaying to the user, letting them make 1 of the choices above, or sharing
        # after the user has made a choice.  They will be used for display if 'unique' is True, and will look
        # like: {historyX : [hda, hda], historyY : [hda] }
        # For sharing, they will look like:
        # { userA: {historyX : [hda, hda], historyY : [hda]}, userB: {historyY : [hda]} }
        can_change = {}
        cannot_change = {}
        no_change_needed = {}
        unique_no_change_needed = {}
        user_roles = user.all_roles()
        for history in histories:
            for send_to_user in send_to_users:
                # Make sure the current history has not already been shared with the current send_to_user
                if trans.sa_session.query( trans.app.model.HistoryUserShareAssociation ) \
                                   .filter( and_( trans.app.model.HistoryUserShareAssociation.table.c.user_id == send_to_user.id,
                                                  trans.app.model.HistoryUserShareAssociation.table.c.history_id == history.id ) ) \
                                   .count() > 0:
                    send_to_err += "History (%s) already shared with user (%s)" % ( history.name, send_to_user.email )
                else:
                    # Only deal with datasets that have not been purged
                    for hda in history.activatable_datasets:
                        if trans.app.security_agent.can_access_dataset( send_to_user.all_roles(), hda.dataset ):
                            # The no_change_needed dictionary is a special case.  If both of can_change
                            # and cannot_change are empty, no_change_needed will used for sharing.  Otherwise
                            # unique_no_change_needed will be used for displaying, so we need to populate both.
                            # Build the dictionaries for display, containing unique histories only
                            if history not in unique_no_change_needed:
                                unique_no_change_needed[ history ] = [ hda ]
                            else:
                                unique_no_change_needed[ history ].append( hda )
                            # Build the dictionaries for sharing
                            if send_to_user not in no_change_needed:
                                no_change_needed[ send_to_user ] = {}
                            if history not in no_change_needed[ send_to_user ]:
                                no_change_needed[ send_to_user ][ history ] = [ hda ]
                            else:
                                no_change_needed[ send_to_user ][ history ].append( hda )
                        else:
                            # The user with which we are sharing the history does not have access permission on the current dataset
                            if trans.app.security_agent.can_manage_dataset( user_roles, hda.dataset ):
                                # The current user has authority to change permissions on the current dataset because
                                # they have permission to manage permissions on the dataset.
                                # NOTE: ( gvk )There may be problems if the dataset also has an ldda, but I don't think so
                                # because the user with which we are sharing will not have the "manage permission" permission
                                # on the dataset in their history.  Keep an eye on this though...
                                if unique:
                                    # Build the dictionaries for display, containing unique histories only
                                    if history not in can_change:
                                        can_change[ history ] = [ hda ]
                                    else:
                                        can_change[ history ].append( hda )
                                else:
                                    # Build the dictionaries for sharing
                                    if send_to_user not in can_change:
                                        can_change[ send_to_user ] = {}
                                    if history not in can_change[ send_to_user ]:
                                        can_change[ send_to_user ][ history ] = [ hda ]
                                    else:
                                        can_change[ send_to_user ][ history ].append( hda )
                            else:
                                if action in [ "private", "public" ]:
                                    # The user has made a choice, so 'unique' doesn't apply.  Don't change stuff
                                    # that the user doesn't have permission to change
                                    continue
                                if unique:
                                    # Build the dictionaries for display, containing unique histories only
                                    if history not in cannot_change:
                                        cannot_change[ history ] = [ hda ]
                                    else:
                                        cannot_change[ history ].append( hda )
                                else:
                                    # Build the dictionaries for sharing
                                    if send_to_user not in cannot_change:
                                        cannot_change[ send_to_user ] = {}
                                    if history not in cannot_change[ send_to_user ]:
                                        cannot_change[ send_to_user ][ history ] = [ hda ]
                                    else:
                                        cannot_change[ send_to_user ][ history ].append( hda )
        return can_change, cannot_change, no_change_needed, unique_no_change_needed, send_to_err
    def _share_histories( self, trans, user, send_to_err, histories={} ):
        # histories looks like: { userA: [ historyX, historyY ], userB: [ historyY ] }
        msg = ""
        sent_to_emails = []
        for send_to_user in histories.keys():
            sent_to_emails.append( send_to_user.email )
        emails = ",".join( e for e in sent_to_emails )
        if not histories:
            send_to_err += "No users have been specified or no histories can be sent without changing permissions or associating a sharing role.  "
        else:
            for send_to_user, send_to_user_histories in histories.items():
                shared_histories = []
                for history in send_to_user_histories:
                    share = trans.app.model.HistoryUserShareAssociation()
                    share.history = history
                    share.user = send_to_user
                    trans.sa_session.add( share )
                    self.create_item_slug( trans.sa_session, history )
                    trans.sa_session.flush()
                    if history not in shared_histories:
                        shared_histories.append( history )
        if send_to_err:
            msg += send_to_err
        return self.sharing( trans, histories=shared_histories, msg=msg )

    @web.expose
    @web.require_login( "rename histories" )
    def rename( self, trans, id=None, name=None, **kwd ):
        user = trans.get_user()
        if not id:
            # Default to the current history
            history = trans.get_history()
            if not history.user:
                return trans.show_error_message( "You must save your history before renaming it." )
            id = trans.security.encode_id( history.id )
        id = util.listify( id )
        name = util.listify( name )
        histories = []
        cur_names = []
        for history_id in id:
            history = self.get_history( trans, history_id )
            if history and history.user_id == user.id:
                histories.append( history )
                cur_names.append( history.get_display_name() )
        if not name or len( histories ) != len( name ):
            return trans.fill_template( "/history/rename.mako", histories=histories )
        change_msg = ""
        for i in range(len(histories)):
            if histories[i].user_id == user.id:
                if name[i] == histories[i].get_display_name():
                    change_msg = change_msg + "<p>History: "+cur_names[i]+" is already named: "+name[i]+"</p>"
                elif name[i] not in [None,'',' ']:
                    name[i] = escape(name[i])
                    histories[i].name = sanitize_html( name[i] )
                    trans.sa_session.add( histories[i] )
                    trans.sa_session.flush()
                    change_msg = change_msg + "<p>History: "+cur_names[i]+" renamed to: "+name[i]+"</p>"
                    trans.log_event( "History renamed: id: %s, renamed to: '%s'" % (str(histories[i].id), name[i] ) )
                else:
                    change_msg = change_msg + "<p>You must specify a valid name for History: "+cur_names[i]+"</p>"
            else:
                change_msg = change_msg + "<p>History: "+cur_names[i]+" does not appear to belong to you.</p>"
        return trans.show_message( "<p>%s" % change_msg, refresh_frames=['history'] )

    @web.expose
    @web.require_login( "clone shared Galaxy history" )
    def clone( self, trans, id=None, **kwd ):
        """Clone a list of histories"""
        params = util.Params( kwd )
        # If clone_choice was not specified, display form passing along id
        # argument
        clone_choice = params.get( 'clone_choice', None )
        if not clone_choice:
            return trans.fill_template( "/history/clone.mako", id_argument=id )
        # Extract histories for id argument, defaulting to current
        if id is None:
            histories = [ trans.history ]
        else:
            ids = util.listify( id )
            histories = []
            for history_id in ids:
                history = self.get_history( trans, history_id, check_ownership=False )
                histories.append( history )
        user = trans.get_user()
        for history in histories:
            if history.user == user:
                owner = True
            else:
                if trans.sa_session.query( trans.app.model.HistoryUserShareAssociation ) \
                                   .filter_by( user=user, history=history ) \
                                   .count() == 0:
                    return trans.show_error_message( "The history you are attempting to clone is not owned by you or shared with you.  " )
                owner = False
            name = "Clone of '%s'" % history.name
            if not owner:
                name += " shared by '%s'" % history.user.email
            if clone_choice == 'activatable':
                new_history = history.copy( name=name, target_user=user, activatable=True )
            elif clone_choice == 'active':
                name += " (active items only)"
                new_history = history.copy( name=name, target_user=user )
        if len( histories ) == 1:
            msg = 'Clone with name "<a href="%s" target="_top">%s</a>" is now included in your previously stored histories.' % ( url_for( controller="history", action="switch_to_history", hist_id=trans.security.encode_id( new_history.id ) ) , new_history.name )
        else:
            msg = '%d cloned histories are now included in your previously stored histories.' % len( histories )
        return trans.show_ok_message( msg )

    @web.expose
    @web.require_login( "switch to a history" )
    def switch_to_history( self, trans, hist_id=None ):
        decoded_id = trans.security.decode_id(hist_id)
        hist = trans.sa_session.query( trans.app.model.History ).get( decoded_id )
        trans.set_history( hist )
        return trans.response.send_redirect( url_for( "/" ) )
        
    def get_item( self, trans, id ):
        return self.get_history( trans, id )
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.