This file is indexed.

/usr/lib/python2.7/dist-packages/sagenb/notebook/notebook.py is in python-sagenb 1.0.1+ds1-2.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
# -*- coding: utf-8 -*
"""
The Sage Notebook

AUTHORS:

- William Stein
"""

#############################################################################
#
#       Copyright (C) 2006-2009 William Stein <wstein@gmail.com>
#  Distributed under the terms of the GNU General Public License (GPL)
#  The full text of the GPL is available at:
#                  http://www.gnu.org/licenses/
#
#############################################################################
from __future__ import print_function, absolute_import

# For debugging sometimes it is handy to use only the reference implementation.
USE_REFERENCE_WORKSHEET_PROCESSES = False

# System libraries
import os
import random
import re
import shutil
import socket
import time
import bz2
from cgi import escape

try:
    import cPickle as pickle
except ImportError:
    import pickle

from six import iteritems

# Sage libraries
from sagenb.misc.misc import (pad_zeros, cputime, tmp_dir, load, save,
                              ignore_nonexistent_files, unicode_str)

# Sage Notebook
from . import css          # style
from . import js           # javascript
from . import worksheet    # individual worksheets (which make up a notebook)
from . import config       # internal configuration stuff (currently, just keycodes)
from . import keyboards    # keyboard layouts
from . import server_conf  # server configuration
from . import user_conf    # user configuration
from . import user         # users
from   .template import template, prettify_time_ago
from flask_babel import gettext, lazy_gettext

try:
    # sage is installed
    import sage
    # [(string: name, bool: optional)]
    SYSTEMS = [('sage', False),
               ('gap', False),
               ('gp', False),
               ('html', False),
               ('latex', False),
               ('maxima', False),
               ('python', False),
               ('r', False),
               ('sh', False),
               ('singular', False),
               ('axiom', True),
               ('fricas', True),
               ('kash', True),
               ('macaulay2', True),
               ('magma', True),
               ('maple', True,),
               ('mathematica', True),
               ('matlab', True),
               ('mupad', True),
               ('octave', True),
               ('scilab', True)]
except ImportError:
    # sage is not installed
    SYSTEMS = [('sage', True)]    # but gracefully degenerated version of sage mode, e.g., preparsing is trivial


# We also record the system names without (optional) since they are
# used in some of the html menus, etc.
SYSTEM_NAMES = [v[0] for v in SYSTEMS]

MATHJAX = True

JEDITABLE_TINYMCE  = True

class WorksheetDict(dict):
    def __init__(self, notebook, *args, **kwds):
        self.notebook = notebook
        self.storage = notebook._Notebook__storage
        dict.__init__(self, *args, **kwds)

    def __getitem__(self, item):
        if item in self:
            return dict.__getitem__(self, item)

        try:
            if '/' not in item:
                raise KeyError(item)
        except TypeError:
            raise KeyError(item)

        username, id = item.split('/')
        try:
            id=int(id)
        except ValueError:
            raise KeyError(item)
        try:
            worksheet = self.storage.load_worksheet(username, id)
        except ValueError:
            raise KeyError(item)

        dict.__setitem__(self, item, worksheet)
        return worksheet
        
        
class Notebook(object):
    HISTORY_MAX_OUTPUT = 92*5
    HISTORY_NCOLS = 90
    
    def __init__(self, dir, user_manager = None):

        if isinstance(dir, basestring) and len(dir) > 0 and dir[-1] == "/":
            dir = dir[:-1]

        if not dir.endswith('.sagenb'):
            raise ValueError("dir (=%s) must end with '.sagenb'" % dir)

        self._dir = dir

        # For now we only support the FilesystemDatastore storage
        # backend.
        from sagenb.storage import FilesystemDatastore
        S = FilesystemDatastore(dir)
        self.__storage = S

        # Now set the configuration, loaded from the datastore.
        try:
            self.__conf = S.load_server_conf()
        except IOError:
            # Worksheet has never been saved before, so the server conf doesn't exist.
            self.__worksheets = WorksheetDict(self)

        from sagenb.notebook.user_manager import SimpleUserManager, OpenIDUserManager
        self._user_manager = OpenIDUserManager(conf=self.conf()) if user_manager is None else user_manager

        # Set up email notification logger
        import logging
        from sagenb.notebook.notification import logger, TwistedEmailHandler
        logger.addHandler(TwistedEmailHandler(self.conf(), logging.ERROR))
        # also log to stderr
        logger.addHandler(logging.StreamHandler())

        # Set the list of users
        try:
            S.load_users(self._user_manager)
        except IOError:
            pass

        # Set the list of worksheets
        W = WorksheetDict(self)
        self.__worksheets = W

        # Store / Refresh public worksheets
        for id_number in os.listdir(self.__storage._abspath(self.__storage._user_path("pub"))):
            if id_number.isdigit():
                a = "pub/"+str(id_number)
                if a not in self.__worksheets:
                    try:
                        self.__worksheets[a] = self.__storage.load_worksheet("pub",int(id_number))
                    except Exception:
                        import traceback
                        print("Warning: problem loading %s/%s: %s" % ("pub", int(id_number), traceback.format_exc()))

        # Set the openid-user dict
        try:
            self._user_manager.load(S)
        except IOError:
            pass

    def delete(self):
        """
        Delete all files related to this notebook.

        This is used for doctesting mainly. This command is obviously
        *VERY* dangerous to use on a notebook you actually care about.
        You could easily lose all data.

        EXAMPLES::

            sage: tmp = tmp_dir(ext='.sagenb')
            sage: nb = sagenb.notebook.notebook.Notebook(tmp)
            sage: sorted(os.listdir(tmp))
            ['home']
            sage: nb.delete()

        Now the directory is gone.::

            sage: os.listdir(tmp)
            Traceback (most recent call last):
            ...
            OSError: [Errno 2] No such file or directory: '...
        """
        self.__storage.delete()

    def systems(self, username=None):
        systems = []
        for system in SYSTEMS:
            if system[1]:
                systems.append(system[0] + ' (' + lazy_gettext('optional') + ')')
            else:
                systems.append(system[0])
        return systems

    def system_names(self):
        return SYSTEM_NAMES

    def user_manager(self):
        """
        Returns self's UserManager object.

        EXAMPLES::

            sage: n = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: n.user_manager() 
            <sagenb.notebook.user_manager.OpenIDUserManager object at 0x...>
        """
        return self._user_manager
        
    ##########################################################
    # Users
    ##########################################################
    def create_default_users(self, passwd):
        """
        Create the default users for a notebook.

        INPUT:

        - ``passwd`` - a string

        EXAMPLES::

            sage: from six import iteritems
            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: sorted(list(iteritems(nb.user_manager().users())))
            [('_sage_', _sage_), ('admin', admin), ('guest', guest), ('pub', pub)]
            sage: sorted(list(iteritems(nb.user_manager().passwords()))) #random
            [('_sage_', ''), ('admin', ''), ('guest', ''), ('pub', '')]
            sage: nb.create_default_users('newpassword')
            WARNING: User 'pub' already exists -- and is now being replaced.
            WARNING: User '_sage_' already exists -- and is now being replaced.
            WARNING: User 'guest' already exists -- and is now being replaced.
            WARNING: User 'admin' already exists -- and is now being replaced.
            sage: sorted(list(iteritems(nb.user_manager().passwords()))) #random
            [('_sage_', ''), ('admin', ''), ('guest', ''), ('pub', '')]
            sage: len(list(iteritems(nb.user_manager().passwords())))
            4
        """
        self.user_manager().create_default_users(passwd)

    def user(self, username):
        """
        Return an instance of the User class given the ``username`` of a user
        in a notebook.

        INPUT:

        - ``username`` - a string

        OUTPUT:

        - an instance of User

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.user_manager().create_default_users('password')
            sage: nb.user('admin')
            admin
            sage: nb.user('admin').get_email()
            ''
            sage: nb.user('admin').password() #random
            '256$7998210096323979f76e9fedaf1f85bda1561c479ae732f9c1f1abab1291b0b9$373f16b9d5fab80b9a9012af26a6b2d52d92b6d4b64c1836562cbd4264a6e704'
        """
        return self.user_manager().user(username)

    def valid_login_names(self):
        """
        Return a list of users that can log in.

        OUTPUT:

        - a list of strings

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: nb.valid_login_names()
            ['admin']
            sage: nb.user_manager().add_user('Mark', 'password', '', force=True)
            sage: nb.user_manager().add_user('Sarah', 'password', '', force=True)
            sage: nb.user_manager().add_user('David', 'password', '', force=True)
            sage: sorted(nb.valid_login_names())
            ['David', 'Mark', 'Sarah', 'admin']
        """
        return self.user_manager().valid_login_names()

    def readonly_user(self, username):
        """
        Returns True if the user is supposed to only be a read-only user.
        """
        return self.__storage.readonly_user(username)

    ##########################################################
    # Publishing worksheets
    ##########################################################
    def _initialize_worksheet(self, src, W):
        r"""
        Initialize a new worksheet from a source worksheet.

        INPUT:

        - ``src`` - a Worksheet instance; the source

        - ``W`` - a new Worksheet instance; the target
        """
        # Note: Each Worksheet method *_directory actually creates a
        # directory, if it doesn't already exist.

        # More compact, but significantly less efficient?
        #      shutil.rmtree(W.cells_directory(), ignore_errors=True)
        #      shutil.rmtree(W.data_directory(), ignore_errors=True)
        #      shutil.rmtree(W.snapshots_directory(), ignore_errors=True)
        #      shutil.copytree(src.cells_directory(), W.cells_directory())
        #      shutil.copytree(src.data_directory(), W.data_directory())

        for sub in ['cells', 'data', 'snapshots']:
            target_dir = os.path.join(W.directory(), sub)
            if os.path.exists(target_dir):
                shutil.rmtree(target_dir, ignore_errors=True)

        # Copy images, data files, etc.
        for sub in ['cells', 'data']:
            source_dir = os.path.join(src.directory(), sub)
            if os.path.exists(source_dir):
                target_dir = os.path.join(W.directory(), sub)
                shutil.copytree(source_dir, target_dir)

        W.edit_save(src.edit_text())
        W.save()

    def pub_worksheets(self):
        path = self.__storage._abspath(self.__storage._user_path("pub"))
        v = []
        a = ""
        for id_number in os.listdir(path):
            if id_number.isdigit():
                a = "pub"+"/"+id_number
                if a in self.__worksheets:
                    v.append(self.__worksheets[a])
                else:
                    try:
                        self.__worksheets[a] = self.__storage.load_worksheet("pub", int(id_number))
                        v.append(self.__worksheets[a])
                    except Exception:
                        import traceback
                        print("Warning: problem loading %s/%s: %s" % ("pub", id_number, traceback.format_exc()))
        return v

    def users_worksheets(self, username):
        r"""
        Returns all worksheets owned by `username`
        """

        if username == "pub":
            return self.pub_worksheets()

        worksheets = self.__storage.worksheets(username)
        # if a worksheet has already been loaded in self.__worksheets, return
        # that instead since worksheets that are already running should be
        # noted as such
        return [self.__worksheets[w.filename()] if w.filename() in self.__worksheets else w for w in worksheets]

    def users_worksheets_view(self, username):
        r"""
        Returns all worksheets viewable by `username`
        """
        # Should return worksheets from self.__worksheets if possible
        worksheets = self.users_worksheets(username)
        user=self.user_manager().user(username)
        viewable_worksheets=[self.__storage.load_worksheet(owner, id) for owner,id in user.viewable_worksheets()]
        # we double-check that we can actually view these worksheets
        # just in case someone forgets to update the map
        worksheets.extend([w for w in viewable_worksheets if w.is_viewer(username)])
        # if a worksheet has already been loaded in self.__worksheets, return that instead
        # since worksheets that are already running should be noted as such
        return [self.__worksheets[w.filename()] if w.filename() in self.__worksheets else w for w in worksheets]

    def publish_worksheet(self, worksheet, username):
        r"""
        Publish a user's worksheet.  This creates a new worksheet in
        the 'pub' directory with the same contents as ``worksheet``.

        INPUT:

        - ``worksheet`` - an instance of Worksheet

        - ``username`` - a string

        OUTPUT:

        - a new or existing published instance of Worksheet

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.load_notebook(tmp_dir(ext='.sagenb'))
            sage: nb.user_manager().add_user('Mark','password','',force=True)
            sage: W = nb.new_worksheet_with_title_from_text('First steps', owner='Mark')
            sage: nb.worksheet_names()
            ['Mark/0']
            sage: nb.create_default_users('password')
            sage: nb.publish_worksheet(nb.get_worksheet_with_filename('Mark/0'), 'Mark')
            pub/0: [Cell 1: in=, out=]
            sage: sorted(nb.worksheet_names())
            ['Mark/0', 'pub/0']
        """
        W = None

        # Reuse an existing published version
        for X in self.get_worksheets_with_owner('pub'):
            if (X.worksheet_that_was_published() == worksheet):
                W = X

        # Or create a new one.
        if W is None:
            W = self.create_new_worksheet(worksheet.name(), 'pub')

        # Copy cells, output, data, etc.
        self._initialize_worksheet(worksheet, W)

        # Update metadata.
        W.set_worksheet_that_was_published(worksheet)
        W.move_to_archive(username)
        worksheet.set_published_version(W.filename())
        W.record_edit(username)
        W.set_name(worksheet.name())
        self.__worksheets[W.filename()] = W
        W.save()
        return W

    ##########################################################
    # Moving, copying, creating, renaming, and listing worksheets
    ##########################################################

    def scratch_worksheet(self):
        try:
            return self.__scratch_worksheet
        except AttributeError:
            W = self.create_new_worksheet('scratch', '_sage_')
            self.__scratch_worksheet = W
            return W

    def create_new_worksheet(self, worksheet_name, username):
        if username!='pub' and self.user_manager().user_is_guest(username):
            raise ValueError("guests cannot create new worksheets")

        W = self.worksheet(username)

        W.set_system(self.system(username))
        W.set_name(worksheet_name)
        self.save_worksheet(W)
        self.__worksheets[W.filename()] = W

        return W

    def copy_worksheet(self, ws, owner):
        W = self.create_new_worksheet('default', owner)
        self._initialize_worksheet(ws, W)
        name = "Copy of %s" % ws.name()
        W.set_name(name)
        return W

    def delete_worksheet(self, filename):
        """
        Delete the given worksheet and remove its name from the worksheet
        list.  Raise a KeyError, if it is missing.

        INPUT:

        - ``filename`` - a string
        """
        try:
            W = self.__worksheets[filename]
        except KeyError:
            raise KeyError("Attempt to delete missing worksheet '%s'" % filename)
        
        W.quit()
        shutil.rmtree(W.directory(), ignore_errors=False)
        self.deleted_worksheets()[filename] = W

    def deleted_worksheets(self):
        try:
            return self.__deleted_worksheets
        except AttributeError:
            self.__deleted_worksheets = {}
            return self.__deleted_worksheets

    def empty_trash(self, username):
        """
        Empty the trash for the given user.

        INPUT:

        -  ``username`` - a string

        This empties the trash for the given user and cleans up all files
        associated with the worksheets that are in the trash.

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.user_manager().add_user('sage','sage','sage@sagemath.org',force=True)
            sage: W = nb.new_worksheet_with_title_from_text('Sage', owner='sage')
            sage: W._notebook = nb
            sage: W.move_to_trash('sage')
            sage: nb.worksheet_names()
            ['sage/0']
            sage: nb.empty_trash('sage')
            sage: nb.worksheet_names()
            []
        """
        X = self.get_worksheets_with_viewer(username)
        X = [W for W in X if W.is_trashed(username)]
        for W in X:
            W.delete_user(username)
            if W.owner() is None:
                self.delete_worksheet(W.filename())

    def worksheet_names(self):
        """
        Return a list of all the names of worksheets in this notebook.

        OUTPUT:

        - a list of strings.

        EXAMPLES:

        We make a new notebook with two users and two worksheets,
        then list their names::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.user_manager().add_user('sage','sage','sage@sagemath.org',force=True)
            sage: W = nb.new_worksheet_with_title_from_text('Sage', owner='sage')
            sage: nb.user_manager().add_user('wstein','sage','wstein@sagemath.org',force=True)
            sage: W2 = nb.new_worksheet_with_title_from_text('Elliptic Curves', owner='wstein')
            sage: nb.worksheet_names()
            ['sage/0', 'wstein/0']
        """
        W = self.__worksheets.keys()
        W.sort()
        return W


    ##########################################################
    # Information about the pool of worksheet compute servers
    ##########################################################

    def server_pool(self):
        return self.conf()['server_pool']

    def set_server_pool(self, servers):
        self.conf()['server_pool'] = servers

    def get_ulimit(self):
        try:
            return self.__ulimit
        except AttributeError:
            self.__ulimit = ''
            return ''

    def set_ulimit(self, ulimit):
        self.__ulimit = ulimit

    def get_server(self):
        P = self.server_pool()
        if P is None or len(P) == 0:
            return None
        try:
            self.__server_number = (self.__server_number + 1) % len(P)
            i = self.__server_number
        except AttributeError:
            self.__server_number = 0
            i = 0
        return P[i]

    def new_worksheet_process(self):
        """
        Return a new worksheet process object with parameters determined by
        configuration of this notebook server.
        """
        from sagenb.interfaces import (WorksheetProcess_ExpectImplementation,
                                       WorksheetProcess_ReferenceImplementation,
                                       WorksheetProcess_RemoteExpectImplementation)

        if USE_REFERENCE_WORKSHEET_PROCESSES:
            return WorksheetProcess_ReferenceImplementation()

        ulimit = self.get_ulimit()
        from sagenb.interfaces import ProcessLimits
        # We have to parse the ulimit format to our ProcessLimits.
        # The typical format is.
        # '-u 400 -v 1000000 -t 3600'
        # Despite -t being cputime for ulimit, we map it to walltime,
        # since that is the only thing that really makes sense for a
        # notebook server.
        #    -u --> max_processes
        #    -v --> max_vmem (but we divide by 1000)
        #    -t -- > max_walltime

        max_vmem = max_cputime = max_walltime = None
        tbl = {'v': None, 'u': None, 't': None}
        for x in ulimit.split('-'):
            for k in tbl.keys():
                if x.startswith(k): 
                    tbl[k] = int(x.split()[1].strip())
        if tbl['v'] is not None:
            tbl['v'] = tbl['v'] / 1000.0


        process_limits = ProcessLimits(max_vmem=tbl['v'], max_walltime=tbl['t'],
                                       max_processes=tbl['u'])

        server_pool = self.server_pool()
        if not server_pool or len(server_pool) == 0:
            return WorksheetProcess_ExpectImplementation(process_limits=process_limits)
        else:
            import random
            user_at_host = random.choice(server_pool)
            return WorksheetProcess_RemoteExpectImplementation(user_at_host=user_at_host,
                             process_limits=process_limits,
                             remote_python='python')


    def _python_command(self):
        """
        """
        try: 
            return self.__python_command
        except AttributeError: 
            pass



    ##########################################################
    # Configuration settings.
    ##########################################################
    def system(self, username=None):
        """
        The default math software system for new worksheets for a
        given user or the whole notebook (if username is None).
        """
        return self.user(username).conf()['default_system']

    def pretty_print(self, username=None):
        """
        The default typeset setting for new worksheets for
        a given user or the whole notebook (if username is None).

        TODO -- only implemented for the notebook right now
        """
        return self.user(username).conf()['default_pretty_print']

    def set_pretty_print(self, pretty_print):
        self.__pretty_print = pretty_print

    def color(self):
        """
        The default color scheme for the notebook.
        """
        try:
            return self.__color
        except AttributeError:
            self.__color = 'default'
            return self.__color

    def set_color(self, color):
        self.__color = color

    ##########################################################
    # The notebook history.
    ##########################################################
    def user_history(self, username):
        if not hasattr(self, '_user_history'):
            self._user_history = {}
        if username in self._user_history:
            return self._user_history[username]
        history = []
        for hunk in self.__storage.load_user_history(username):
            hunk = unicode_str(hunk)
            history.append(hunk)
        self._user_history[username] = history
        return history

    def create_new_worksheet_from_history(self, name, username, maxlen=None):
        W = self.create_new_worksheet(name, username)
        W.edit_save('Log Worksheet\n' + self.user_history_text(username, maxlen=None))
        return W

    def user_history_text(self, username, maxlen=None):
        history = self.user_history(username)
        if maxlen:
            history = history[-maxlen:]
        return '\n\n'.join([hunk.strip() for hunk in history])

    def add_to_user_history(self, entry, username):
        history = self.user_history(username)
        history.append(entry)
        maxlen = self.user_manager().user_conf(username)['max_history_length']
        while len(history) > maxlen:
            del history[0]


    ##########################################################
    # Importing and exporting worksheets to files
    ##########################################################
    def export_worksheet(self, worksheet_filename, output_filename, title=None):
        """
        Export a worksheet, creating a sws file on the file system.

        INPUT:

            -  ``worksheet_filename`` - a string e.g., 'username/id_number'

            -  ``output_filename`` - a string, e.g., 'worksheet.sws'

            - ``title`` - title to use for the exported worksheet (if
               None, just use current title)
        """
        S = self.__storage
        W = self.get_worksheet_with_filename(worksheet_filename)
        S.save_worksheet(W)
        username = W.owner()
        id_number = W.id_number()
        S.export_worksheet(username, id_number, output_filename, title=title)

    def worksheet(self, username, id_number=None):
        """
        Create a new worksheet with given id_number belonging to the
        user with given username, or return an already existing
        worksheet.  If id_number is None, creates a new worksheet
        using the next available new id_number for the given user.

        INPUT:

            - ``username`` -- string

            - ``id_number`` - nonnegative integer or None (default)
        """
        S = self.__storage
        if id_number is None:
            id_number = self.new_id_number(username)
        try:
            W = S.load_worksheet(username, id_number)
        except ValueError:
            W = S.create_worksheet(username, id_number)
        self.__worksheets[W.filename()] = W
        return W

    def new_id_number(self, username):
        """
        Find the next worksheet id for the given user.
        """
        u = self.user(username).conf()
        id_number = u['next_worksheet_id_number']
        if id_number == -1:  # need to initialize
            id_number = max([w.id_number() for w in self.worksheet_list_for_user(username)] + [-1]) + 1
        u['next_worksheet_id_number'] = id_number + 1
        return id_number

    def new_worksheet_with_title_from_text(self, text, owner):
        name, _ = worksheet.extract_name(text)
        W = self.create_new_worksheet(name, owner)
        return W

    def change_worksheet_key(self, old_key, new_key):
        ws = self.__worksheets
        W = ws[old_key]
        ws[new_key] = W
        del ws[old_key]

    def import_worksheet(self, filename, owner):
        r"""
        Import a worksheet with the given ``filename`` and set its
        ``owner``.  If the file extension is not recognized, raise a
        ValueError.

        INPUT:

        -  ``filename`` - a string

        -  ``owner`` - a string

        OUTPUT:

        -  ``worksheet`` - a newly created Worksheet instance

        EXAMPLES:

        We create a notebook and import a plain text worksheet
        into it.

        ::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: name = tmp_filename() + '.txt'
            sage: open(name,'w').write('foo\n{{{\n2+3\n}}}')
            sage: W = nb.import_worksheet(name, 'admin')

        W is our newly-created worksheet, with the 2+3 cell in it::

            sage: W.name()
            u'foo'
            sage: W.cell_list()
            [TextCell 0: foo, Cell 1: in=2+3, out=]
        """
        if not os.path.exists(filename):
            raise ValueError("no file %s" % filename)

        # Figure out the file extension
        ext = os.path.splitext(filename)[1]
        if ext.lower() == '.txt':
            # A plain text file with {{{'s that defines a worksheet (no graphics).
            W = self._import_worksheet_txt(filename, owner)
        elif ext.lower() == '.sws':
            # An sws file (really a tar.bz2) which defines a worksheet with graphics, etc.
            W = self._import_worksheet_sws(filename, owner)
        elif ext.lower() == '.html':
            # An html file, which should contain the static version of
            # a sage help page, as generated by Sphinx
            html = open(filename).read()

            cell_pattern = r"""{{{id=.*?///.*?}}}"""
            docutils_pattern = r"""<meta name="generator" content="Docutils \S+: http://docutils\.sourceforge\.net/" />"""
            sphinx_pattern = r"""Created using <a href="http://sphinx\.pocoo\.org/">Sphinx</a>"""

            if re.search(cell_pattern, html, re.DOTALL) is not None:
                W = self._import_worksheet_txt(filename, owner)
            elif re.search(docutils_pattern, html) is not None:
                W = self._import_worksheet_docutils_html(filename, owner)
            elif re.search(sphinx_pattern, html) is not None:
                W = self._import_worksheet_html(filename, owner)
            else:
                # Unrecognized html file
                # We do the default behavior, i.e. we import as if it was generated
                # by Sphinx web page
                W = self._import_worksheet_html(filename, owner)
        elif ext.lower() == '.rst':
            # A ReStructuredText file
            W = self._import_worksheet_rst(filename, owner)
        else:
            # We only support txt, sws, html and rst files
            raise ValueError("unknown extension '%s'" % ext)
        self.__worksheets[W.filename()] = W
        return W

    def _import_worksheet_txt(self, filename, owner):
        r"""
        Import a plain text file as a new worksheet.

        INPUT:

        -  ``filename`` - a string; a filename that ends in .txt

        -  ``owner`` - a string; the imported worksheet's owner

        OUTPUT:

        -  a new instance of Worksheet

        EXAMPLES:

        We write a plain text worksheet to a file and import it
        using this function.::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: name = tmp_filename() + '.txt'
            sage: open(name,'w').write('foo\n{{{\na = 10\n}}}')
            sage: W = nb._import_worksheet_txt(name, 'admin'); W
            admin/0: [TextCell 0: foo, Cell 1: in=a = 10, out=]
        """
        # Open the worksheet txt file and load it in.
        worksheet_txt = open(filename).read()
        # Create a new worksheet with the right title and owner.
        worksheet = self.new_worksheet_with_title_from_text(worksheet_txt, owner)
        # Set the new worksheet to have the contents specified by that file.
        worksheet.edit_save(worksheet_txt)
        return worksheet

    def _import_worksheet_sws(self, filename, username):
        r"""
        Import an sws format worksheet into this notebook as a new
        worksheet.

        INPUT:

        - ``filename`` - a string; a filename that ends in .sws;
           internally it must be a tar'd bz2'd file.

        - ``username`` - a string

        OUTPUT:

        - a new Worksheet instance

        EXAMPLES:

        We create a notebook, then make a worksheet from a plain text
        file first.::

            sage: nb = sagenb.notebook.notebook.load_notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: name = tmp_filename() + '.txt'
            sage: open(name,'w').write('{{{id=0\n2+3\n}}}')
            sage: W = nb.import_worksheet(name, 'admin')
            sage: W.filename()
            'admin/0'
            sage: sorted([w.filename() for w in nb.get_all_worksheets()])
            ['admin/0']

        We then export the worksheet to an sws file.::

            sage: sws = os.path.join(tmp_dir(), 'tmp.sws')
            sage: nb.export_worksheet(W.filename(), sws)

        Now we import the sws.::

            sage: W = nb._import_worksheet_sws(sws, 'admin')
            sage: nb._Notebook__worksheets[W.filename()] = W

        Yes, it's there now (as a new worksheet)::

            sage: sorted([w.filename() for w in nb.get_all_worksheets()])
            ['admin/0', 'admin/1']
        """
        id_number = self.new_id_number(username)
        worksheet = self.__storage.import_worksheet(username, id_number, filename)

        # I'm not at all convinced this is a good idea, since we
        # support multiple worksheets with the same title very well
        # already.  So it's commented out.
        # self.change_worksheet_name_to_avoid_collision(worksheet)

        return worksheet

    def _import_worksheet_html(self, filename, owner):
        r"""
        Import a static html help page generated by Sphinx as a new
        worksheet.

        INPUT:

        -  ``filename`` - a string; a filename that ends in .html

        -  ``owner`` - a string; the imported worksheet's owner

        OUTPUT:

        -  a new instance of Worksheet

        EXAMPLES:

        We write a plain text worksheet to a file and import it
        using this function.::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: name = tmp_filename() + '.html'
            sage: fd = open(name,'w')
            sage: fd.write(''.join([
            ....: '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"\n',
            ....: '  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n',
            ....: '\n',
            ....: '<html xmlns="http://www.w3.org/1999/xhtml">\n',
            ....: '  <head>\n',
            ....: '   <title>Test notebook &mdash; test</title>\n',
            ....: ' </head>\n',
            ....: '  <body>\n',
            ....: '   <div class="document">\n',
            ....: '      <div class="documentwrapper">\n',
            ....: '        <div class="bodywrapper">\n',
            ....: '          <div class="body">\n',
            ....: '<p>Here are some computations:</p>\n',
            ....: '\n',
            ....: '<div class="highlight-python"><div class="highlight"><pre>\n',
            ....: '<span class="gp">sage',
            ....: ': </span><span class="mi">1</span><span class="o">+</span><span class="mi">1</span>\n',
            ....: '<span class="go">2</span>\n',
            ....: '</pre></div></div>\n',
            ....: '\n',
            ....: '</div></div></div></div>\n',
            ....: '</body></html>']))
            sage: fd.close()
            sage: W = nb._import_worksheet_html(name, 'admin')
            sage: W.name()
            u'Test notebook -- test'
            sage: W.owner()
            'admin'
            sage: W.cell_list()
            [TextCell 1: <div class="document">
                  <div class="documentwrapper">
                    <div class="bodywrapper">
                      <div class="body">
            <p>Here are some computations:</p>
            <BLANKLINE>
            <div class="highlight-python">, Cell 0: in=1+1, out=
            2, TextCell 2: </div>
            <BLANKLINE>
            </div></div></div></div>]
            sage: cell = W.cell_list()[1]
            sage: cell.input_text()
            u'1+1'
            sage: cell.output_text()
            u'<pre class="shrunk">2</pre>'
        """
        # Inspired from sagenb.notebook.twist.WorksheetFile.render
        doc_page_html = open(filename).read()
        from .docHTMLProcessor import SphinxHTMLProcessor
        # FIXME: does SphinxHTMLProcessor raise an appropriate message
        # if the html file does not contain a Sphinx HTML page?
        doc_page = SphinxHTMLProcessor().process_doc_html(doc_page_html)

        from .misc import extract_title
        title = extract_title(doc_page_html).replace('&mdash;','--')

        worksheet = self.create_new_worksheet(title, owner)
        worksheet.edit_save(doc_page)

        # FIXME: An extra compute cell is always added to the end.
        # Pop it off.
        cells = worksheet.cell_list()
        cells.pop()

        return worksheet

    def _import_worksheet_rst(self, filename, owner):
        r"""
        Import a ReStructuredText file as a new worksheet.

        INPUT:

        -  ``filename`` - a string; a filename that ends in .rst

        -  ``owner`` - a string; the imported worksheet's owner

        OUTPUT:

        -  a new instance of Worksheet

        EXAMPLES:

            sage: sprompt = 'sage' + ':'
            sage: rst = '\n'.join(['=============',
            ....:     'Test Notebook',
            ....:     '=============',
            ....:     '',
            ....:     'Let\'s do some computations::',
            ....:     '',
            ....:     '    %s 2+2' % sprompt,
            ....:     '    4',
            ....:     '',
            ....:     '::',
            ....:     '',
            ....:     '    %s x^2' % sprompt,
            ....:     '    x^2'])
            sage: name = tmp_filename() + '.rst'
            sage: fd = open(name,'w')
            sage: fd.write(rst)
            sage: fd.close()
            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb._import_worksheet_rst(name, 'admin')
            sage: W.name()
            u'Test Notebook'
            sage: W.owner()
            'admin'
            sage: W.cell_list()
            [TextCell 2: <h1 class="title">Test Notebook</h1>
            <BLANKLINE>
            <p>Let's do some computations:</p>, Cell 0: in=2+2, out=
            4, Cell 1: in=x^2, out=
            x^2]
            sage: cell = W.cell_list()[1]
            sage: cell.input_text()
            u'2+2'
            sage: cell.output_text()
            u'<pre class="shrunk">4</pre>'

        """
        rst = open(filename).read()

        # docutils removes the backslashes if they are not escaped This is
        # not practical because backslashes are almost never escaped in
        # Sage docstrings written in ReST.  So if the user wants the
        # backslashes to be escaped automatically, he adds the comment 
        # ".. escape-backslashes" in the input file
        if re.search(r'^\.\.[ \t]+escape-backslashes', rst, re.MULTILINE) is not None:
            rst = rst.replace('\\','\\\\')

        # Do the translation rst -> html (using docutils)
        from docutils.core import publish_parts
        D = publish_parts(rst, writer_name='html')
        title = D['title']
        html = D['whole']

        # Do the translation html -> txt
        from .docHTMLProcessor import docutilsHTMLProcessor
        translator = docutilsHTMLProcessor()
        worksheet_txt = translator.process_doc_html(html)

        # Create worksheet
        worksheet = self.create_new_worksheet(title, owner)
        worksheet.edit_save(worksheet_txt)

        return worksheet

    def _import_worksheet_docutils_html(self, filename, owner):
        r"""
        Import a static html help page generated by docutils as a new
        worksheet.

        INPUT:

        -  ``filename`` - a string; a filename that ends in .html

        -  ``owner`` - a string; the imported worksheet's owner

        OUTPUT:

        -  a new instance of Worksheet

        EXAMPLES:

            sage: sprompt = 'sage' + ':'
            sage: rst = '\n'.join(['=============',
            ....:     'Test Notebook',
            ....:     '=============',
            ....:     '',
            ....:     'Let\'s do some computations::',
            ....:     '',
            ....:     '    %s 2+2' % sprompt,
            ....:     '    4',
            ....:     '',
            ....:     '::',
            ....:     '',
            ....:     '    %s x^2' % sprompt,
            ....:     '    x^2'])
            sage: from docutils.core import publish_string
            sage: html = publish_string(rst, writer_name='html')
            sage: name = tmp_filename() + '.html'
            sage: fd = open(name,'w')
            sage: fd.write(html)
            sage: fd.close()
            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb._import_worksheet_docutils_html(name, 'admin')
            sage: W.name()
            u'Test Notebook'
            sage: W.owner()
            'admin'
            sage: W.cell_list()
            [TextCell 2: <h1 class="title">Test Notebook</h1>
            <BLANKLINE>
            <p>Let's do some computations:</p>, Cell 0: in=2+2, out=
            4, Cell 1: in=x^2, out=
            x^2]
            sage: cell = W.cell_list()[1]
            sage: cell.input_text()
            u'2+2'
            sage: cell.output_text()
            u'<pre class="shrunk">4</pre>'

        """
        html = open(filename).read()

        # Do the translation html -> txt
        from .docHTMLProcessor import docutilsHTMLProcessor
        translator = docutilsHTMLProcessor()
        worksheet_txt = translator.process_doc_html(html)

        # Extract title
        from .worksheet import extract_name
        title, _ = extract_name(worksheet_txt)
        if title.startswith('<h1 class="title">'):
            title = title[18:]
        if title.endswith('</h1>'):
            title = title[:-5]

        # Create worksheet
        worksheet = self.create_new_worksheet(title, owner)
        worksheet.edit_save(worksheet_txt)

        return worksheet

    def change_worksheet_name_to_avoid_collision(self, worksheet):
        """
        Change the display name of the worksheet if there is already a
        worksheet with the same name as this one.
        """
        name = worksheet.name()
        display_names = [w.name() for w in self.get_worksheets_with_owner(worksheet.owner())]
        if name in display_names:
            j = name.rfind('(')
            if j != -1:
                name = name[:j].rstrip()
            i = 2
            while name + " (%s)" % i in display_names:
                i += 1
            name = name + " (%s)" % i
            worksheet.set_name(name)


    ##########################################################
    # Server configuration
    ##########################################################

    def conf(self):
        try:
            return self.__conf
        except AttributeError:
            C = server_conf.ServerConfiguration()
            # if we are newly creating a notebook, then we want to 
            # have a default model version of 1, currently
            # we can't just set the default value in server_conf.py 
            # to 1 since it would then be 1 for notebooks without the
            # model_version property
            # TODO: distinguish between a new server config default values
            #  and default values for missing properties
            C['model_version']=1
            self.__conf = C
            return C

    ##########################################################
    # Computing control
    ##########################################################
    def set_not_computing(self):
        # unpickled, no worksheets will think they are
        # being computed, since they clearly aren't (since
        # the server just started).
        for W in self.__worksheets.values():
            W.set_not_computing()

    def quit(self):
        for W in self.__worksheets.values():
            W.quit()

    def update_worksheet_processes(self):
        worksheet.update_worksheets()

    def quit_idle_worksheet_processes(self):
        timeout = self.conf()['idle_timeout']
        doc_timeout = self.conf()['doc_timeout']

        for W in self.__worksheets.values():
            if W.compute_process_has_been_started():
                if W.docbrowser():
                    W.quit_if_idle(doc_timeout)
                else:
                    W.quit_if_idle(timeout)

    def quit_worksheet(self, W):
        try:
            del self.__worksheets[W.filename()]
        except KeyError:
            pass

    ##########################################################
    # Worksheet HTML generation
    ##########################################################
    def worksheet_list_for_public(self, username, sort='last_edited', reverse=False, search=None):
        W = self.users_worksheets('pub')

        if search:
            W = [x for x in W if x.satisfies_search(search)]

        sort_worksheet_list(W, sort, reverse)  # changed W in place
        return W

    def worksheet_list_for_user(self, user, typ="active", sort='last_edited', reverse=False, search=None):
        X = self.get_worksheets_with_viewer(user)
        if typ == "trash":
            W = [x for x in X if x.is_trashed(user)]
        elif typ == "active":
            W = [x for x in X if x.is_active(user)]
        else: # typ must be archived
            W = [x for x in X if not (x.is_trashed(user) or x.is_active(user))]
        if search:
            W = [x for x in W if x.satisfies_search(search)]
        sort_worksheet_list(W, sort, reverse)  # changed W in place
        return W

    ##########################################################
    # Revision history for a worksheet
    ##########################################################
    def html_worksheet_revision_list(self, username, worksheet):
        r"""
        Return HTML for the revision list of a worksheet.

        INPUT:

        - ``username`` - a string

        - ``worksheet`` - an instance of Worksheet

        OUTPUT:

        - a string - the HTML for the revision list

        EXAMPLES::

            sage: from sagenb.flask_version import base # random output -- depends on warnings issued by other sage packages
            sage: app = base.create_app(tmp_dir(ext='.sagenb'))
            sage: ctx = app.app_context()
            sage: ctx.push()
            sage: nb = base.notebook
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: W.body()
            u'\n\n{{{id=1|\n\n///\n}}}'
            sage: W.save_snapshot('admin')
            sage: nb.html_worksheet_revision_list('admin', W)
            u'...Revision...Last Edited...ago...'
        """
        data = worksheet.snapshot_data()  # pairs ('how long ago', key)
        
        return template(os.path.join("html", "notebook", "worksheet_revision_list.html"),
                        data = data, worksheet = worksheet,
                        notebook = self,
                        username = username)


    def html_specific_revision(self, username, ws, rev):
        r"""
        Return the HTML for a specific revision of a worksheet.

        INPUT:

        - ``username`` - a string

        - ``ws`` - an instance of Worksheet

        - ``rev`` - a string containing the key of the revision

        OUTPUT:

        - a string - the revision rendered as HTML
        """
        t = time.time() - float(rev[:-4])
        time_ago = prettify_time_ago(t)

        filename = ws.get_snapshot_text_filename(rev)
        txt = bz2.decompress(open(filename).read())
        W = self.scratch_worksheet()
        W.set_name('Revision of ' + ws.name())
        W.delete_cells_directory()
        W.edit_save(txt)

        data = ws.snapshot_data()  # pairs ('how long ago', key)
        prev_rev = None
        next_rev = None
        for i in range(len(data)):
            if data[i][1] == rev:
                if i > 0:
                    prev_rev = data[i - 1][1]
                if i < len(data)-1:
                    next_rev = data[i + 1][1]
                break

        return template(os.path.join("html", "notebook", 
                                     "specific_revision.html"),
                        worksheet = W, # the revision, not the original!
                        username = username, rev = rev, prev_rev = prev_rev,
                        next_rev = next_rev, time_ago = time_ago)

    def html_share(self, worksheet, username):
        r"""
        Return the HTML for the "share" page of a worksheet.

        INPUT:

        - ``username`` - a string

        - ``worksheet`` - an instance of Worksheet

        OUTPUT:

        - string - the share page's HTML representation

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: nb.html_share(W, 'admin')
            u'...currently shared...add or remove collaborators...'
        """
        return template(os.path.join("html", "notebook", "worksheet_share.html"),
                        worksheet = worksheet,
                        notebook = self,
                        username = username)

    def html_download_or_delete_datafile(self, ws, username, filename):
        r"""
        Return the HTML for the download or delete datafile page.

        INPUT:

        - ``username`` - a string

        - ``ws`` - an instance of Worksheet

        - ``filename`` - a string; the name of the file

        OUTPUT:

        - a string - the page rendered as HTML

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: nb.html_download_or_delete_datafile(W, 'admin', 'bar')
            u'...Data file: bar...DATA is a special variable...uploaded...'
        """
        ext = os.path.splitext(filename)[1].lower()
        file_is_image, file_is_text = False, False
        text_file_content = ""

        if ext in ['.png', '.jpg', '.gif']:
            file_is_image = True
        if ext in ['.txt', '.tex', '.sage', '.spyx', '.py', '.f', '.f90', '.c']:
            file_is_text = True
            text_file_content = open(os.path.join(ws.data_directory(), filename)).read()
            # Detect the character encoding
            from BeautifulSoup import UnicodeDammit
            text_file_content = UnicodeDammit(text_file_content).unicode

        return template(os.path.join("html", "notebook", "download_or_delete_datafile.html"),
                        worksheet = ws, notebook = self,
                        username = username,
                        filename_ = filename,
                        file_is_image = file_is_image,
                        file_is_text = file_is_text,
                        text_file_content = text_file_content)


    ##########################################################
    # Accessing all worksheets with certain properties.
    ##########################################################
    def active_worksheets_for(self, username):
        # TODO: check if the worksheets are active
        #return [ws for ws in self.get_worksheets_with_viewer(username) if ws.is_active(username)]
        return self.users_worksheets_view(username)
    
    def get_all_worksheets(self):
        """
        We should only call this if the user is admin!
        """
        all_worksheets = []
        for username in self._user_manager.users():
            if username in ['_sage_', 'pub']:
                continue
            for w in self.users_worksheets(username):
                all_worksheets.append(w)
        return all_worksheets

    def get_worksheets_with_viewer(self, username):
        if self._user_manager.user_is_admin(username): return self.get_all_worksheets()
        return self.users_worksheets_view(username)

    def get_worksheets_with_owner(self, owner):
        return self.users_worksheets(owner)

    def get_worksheet_with_filename(self, filename):
        """
        Get the worksheet with the given filename.  If there is no
        such worksheet, raise a ``KeyError``.

        INPUT:

        - ``filename`` - a string

        OUTPUT:

        - a Worksheet instance
        """
        try:
            return self.__worksheets[filename]
        except KeyError:
            raise KeyError("No worksheet with filename '%s'" % filename)

    ###########################################################
    # Saving the whole notebook
    ###########################################################

    def save(self):
        """
        Save this notebook server to disk.
        """
        S = self.__storage
        S.save_users(self.user_manager().users())
        S.save_server_conf(self.conf())
        self._user_manager.save(S)
        # Save the non-doc-browser worksheets.
        for n, W in self.__worksheets.items():
            if not n.startswith('doc_browser'):
                S.save_worksheet(W)
        if hasattr(self, '_user_history'):
            for username, H in iteritems(self._user_history):
                S.save_user_history(username, H)

    def save_worksheet(self, W, conf_only=False):
        self.__storage.save_worksheet(W, conf_only=conf_only)

    def logout(self, username):
        r"""
        Do not do anything on logout (so far).
        
        In particular, do **NOT** stop all ``username``'s worksheets!
        """
        pass

    def delete_doc_browser_worksheets(self):
        for w in self.users_worksheets('_sage_'):
            if w.name().startswith('doc_browser'):
                self.delete_worksheet(w.filename())

    ###########################################################
    # HTML -- generate most html related to the whole notebook page
    ###########################################################
    def html_plain_text_window(self, worksheet, username):
        r"""
        Return HTML for the window that displays a plain text version
        of the worksheet.

        INPUT:

        -  ``worksheet`` - a Worksheet instance

        -  ``username`` - a string

        OUTPUT:

        - a string - the plain text window rendered as HTML

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: nb.html_plain_text_window(W, 'admin')
            u'...pre class="plaintext"...cell_intext...textfield...'
        """
        plain_text = worksheet.plain_text(prompts=True, banner=False)
        plain_text = escape(plain_text).strip()

        return template(os.path.join("html", "notebook", "plain_text_window.html"),
                        worksheet = worksheet,
                        notebook = self,
                        username = username, plain_text = plain_text,
                        MATHJAX = MATHJAX, JEDITABLE_TINYMCE = JEDITABLE_TINYMCE)

    def html_edit_window(self, worksheet, username):
        r"""
        Return HTML for a window for editing ``worksheet``.

        INPUT:

        - ``username`` - a string containing the username

        - ``worksheet`` - a Worksheet instance

        OUTPUT:

        - a string - the editing window's HTML representation

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: nb.html_edit_window(W, 'admin')
            u'...textarea class="plaintextedit"...{{{id=1|...//...}}}...'
        """

        return template(os.path.join("html", "notebook", "edit_window.html"),
                        worksheet = worksheet,
                        notebook = self,
                        username = username)

    def html_beforepublish_window(self, worksheet, username):
        r"""
        Return HTML for the warning and decision page displayed prior
        to publishing the given worksheet.

        INPUT:

        - ``worksheet`` - an instance of Worksheet

        - ``username`` - a string

        OUTPUT:

        - a string - the pre-publication page rendered as HTML

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: nb.html_beforepublish_window(W, 'admin')
            u'...want to publish this worksheet?...re-publish when changes...'
        """
        msg = """You can publish your worksheet to the Internet, where anyone will be able to access and view it online.
        Your worksheet will be assigned a unique address (URL) that you can send to your friends and colleagues.<br/><br/>
        Do you want to publish this worksheet?<br/><br/>
        <form method="get" action=".">
        <input type="hidden" name="yes" value="" />
        <input type="submit" value="Yes" style="margin-left:10px" />
        <input type="button" value="No" style="margin-left:5px" onClick="parent.location=\'../'"><br/><br/>
        <input type="checkbox" name="auto" style="margin-left:13px" /> Automatically re-publish when changes are made and saved
        </form>
        """
        return template(os.path.join("html", "notebook", "beforepublish_window.html"),
                        worksheet = worksheet,
                        notebook = self,
                        username = username)

    def html_afterpublish_window(self, worksheet, username, url, dtime):
        r"""
        Return HTML for a given worksheet's post-publication page.

        INPUT:

        - ``worksheet`` - an instance of Worksheet

        - ``username`` - a string

        - ``url`` - a string representing the URL of the published
          worksheet

        - ``dtime`` - an instance of time.struct_time representing the
          publishing time

        OUTPUT:

        - a string - the post-publication page rendered as HTML
        """
        from time import strftime
        time = strftime("%B %d, %Y %I:%M %p", dtime)

        return template(os.path.join("html", "notebook", "afterpublish_window.html"),
                        worksheet = worksheet,
                        notebook = self,
                        username = username, url = url, time = time)

    def html_upload_data_window(self, ws, username):
        r"""
        Return HTML for the "Upload Data" window.

        INPUT:

        - ``worksheet`` - an instance of Worksheet

        - ``username`` - a string

        OUTPUT:

        - a string - the HTML representation of the data upload window

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: nb.html_upload_data_window(W, 'admin')
            u'...Upload or Create Data File...Browse...url...name of a new...'
        """
        return template(os.path.join("html", "notebook", "upload_data_window.html"),
                        worksheet = ws, username = username)

    def html(self, worksheet_filename=None, username='guest', admin=False, 
             do_print=False):
        r"""
        Return the HTML for a worksheet's index page.

        INPUT:

        - ``worksheet_filename`` - a string (default: None)

        - ``username`` - a string (default: 'guest')

        - ``admin`` - a bool (default: False)

        OUTPUT:

        - a string - the worksheet rendered as HTML

        EXAMPLES::

            sage: nb = sagenb.notebook.notebook.Notebook(tmp_dir(ext='.sagenb'))
            sage: nb.create_default_users('password')
            sage: W = nb.create_new_worksheet('Test', 'admin')
            sage: nb.html(W.filename(), 'admin')
            u'...Test...cell_input...if (e.shiftKey)...state_number...'
        """
        if worksheet_filename is None or worksheet_filename == '':
            worksheet_filename = None
            W = None
        else:
            try:
                W = self.get_worksheet_with_filename(worksheet_filename)
            except KeyError:
                W = None

        from flask import current_app
        if W is None:
            return current_app.message(gettext("The worksheet does not exist"), username=username)

        if W.docbrowser() or W.is_published():
            if W.is_published() or self.user_manager().user_is_guest(username):
                template_page = os.path.join('html', 'notebook', 'guest_worksheet_page.html')
            else:
                template_page = os.path.join("html", "notebook", "doc_page.html")
        elif do_print:
            template_page = os.path.join('html', 'notebook', 'print_worksheet.html')
        else:
            template_page = os.path.join("html", "notebook", "worksheet_page.html")

        return template(template_page, worksheet = W,
                        notebook = self, do_print=do_print,
                        username = username)

    def upgrade_model(self):
        """
        Upgrade the model, if needed.

        - Version 0 (or non-existent model version, which defaults to 0): Original flask notebook
        - Version 1: shared worksheet data cached in the User object
        """
        model_version=self.conf()['model_version']
        if model_version is None or model_version<1:
            print("Upgrading model version to version 1")
            # this uses code from get_all_worksheets()
            user_manager = self.user_manager()
            num_users=0
            for username in self._user_manager.users():
                num_users+=1
                if num_users%1000==0:
                    print('Upgraded %d users' % num_users)
                if username in ['_sage_', 'pub']:
                    continue
                try:
                    for w in self.users_worksheets(username):
                        owner = w.owner()
                        id_number = w.id_number()
                        collaborators = w.collaborators()
                        for u in collaborators:
                            try:
                                user_manager.user(u).viewable_worksheets().add((owner, id_number))
                            except KeyError:
                                # user doesn't exist
                                pass
                except (UnicodeEncodeError, OSError):
                    # Catch UnicodeEncodeError because sometimes a username has a non-ascii character
                    # Catch OSError since sometimes when moving user directories (which happens
                    #   automatically when getting user's worksheets), OSError: [Errno 39] Directory not empty
                    #   is thrown (we should be using shutil.move instead, probably)
                    # users with these problems won't have their sharing cached, but they will probably have
                    # problems logging in anyway, so they probably won't notice not having shared worksheets
                    import sys
                    import traceback
                    print('Error on username %s' % username.encode('utf8'),
                          file=sys.stderr)
                    print(traceback.format_exc(), file=sys.stderr)
                    pass
            print('Done upgrading to model version 1')
            self.conf()['model_version'] = 1
        
####################################################################

def load_notebook(dir, interface=None, port=None, secure=None, user_manager=None):
    """
    Load and return a notebook from a given directory.  Create a new
    one in that directory, if one isn't already there.

    INPUT:

    -  ``dir`` - a string that defines a directory name

    -  ``interface`` - the address of the interface the server listens at

    -  ``port`` - the port the server listens on

    -  ``secure`` - whether the notebook is secure

    OUTPUT:

    - a Notebook instance
    """
    if not dir.endswith('.sagenb'):
        if not os.path.exists(dir + '.sagenb') and os.path.exists(os.path.join(dir, 'nb.sobj')):
            try:
                nb = migrate_old_notebook_v1(dir)
            except KeyboardInterrupt:
                raise KeyboardInterrupt("Interrupted notebook migration.  Delete the directory '%s' and try again." % (os.path.abspath(dir+'.sagenb')))
            return nb
        dir += '.sagenb'

    dir = make_path_relative(dir)
    nb = Notebook(dir)
    nb.interface = interface
    nb.port = port
    nb.secure = secure


    # Install this copy of the notebook in misc.py as *the*
    # global notebook object used for computations.  This is
    # mainly to avoid circular references, etc.  This also means
    # only one notebook can actually be used at any point.
    import sagenb.notebook.misc
    sagenb.notebook.misc.notebook = nb

    return nb

def migrate_old_notebook_v1(dir):
    """
    Back up and migrates an old saved version of notebook to the new one (`sagenb`)
    """
    nb_sobj = os.path.join(dir, 'nb.sobj')
    old_nb = pickle.loads(open(nb_sobj).read())

    ######################################################################
    # Tell user what is going on and make a backup
    ######################################################################

    print("")
    print("*" * 80)
    print("*")
    print("* The Sage notebook at")
    print("*")
    print("*      '%s'" % os.path.abspath(dir))
    print("*")
    print("* will be upgraded to a new format and stored in")
    print("*")
    print("*      '%s.sagenb'." % os.path.abspath(dir))
    print("*")
    print("* Your existing notebook will not be modified in any way.")
    print("*")
    print("*" * 80)
    print("")
    ans = raw_input("Would like to continue? [YES or no] ").lower()
    if ans not in ['', 'y', 'yes']:
        raise RuntimeError("User aborted upgrade.")

    # Create new notebook
    new_nb = Notebook(dir + '.sagenb')

    # Define a function for transfering the attributes of one object to another.
    def transfer_attributes(old, new, attributes):
        for attr_old, attr_new in attributes:
            if hasattr(old, attr_old):
                setattr(new, attr_new, getattr(old, attr_old))

    # Transfer all the notebook attributes to our new notebook object

    new_nb.conf().confs = old_nb.conf().confs
    for t in ['pretty_print', 'server_pool', 'ulimit', 'system']:
        if hasattr(old_nb, '_Notebook__' + t):
            new_nb.conf().confs[t] = getattr(old_nb, '_Notebook__' + t)

    # Now update the user data from the old notebook to the new one:
    print("Migrating %s user accounts..." % len(old_nb.user_manager().users()))
    users = new_nb.user_manager().users()
    for username, old_user in iteritems(old_nb.user_manager().users()):
        new_user = user.User(old_user.username(), '',
                             old_user.get_email(), old_user.account_type())
        new_user.set_hashed_password(old_user.password())
        transfer_attributes(old_user, new_user,
                             [('_User__email_confirmed', '_email_confirmed'),
                             ('_User__temporary_password', '_temporary_password'),
                             ('_User__is_suspended', '_is_suspended')])
        # Fix the __conf field, which is also an instance of a class
        new_user.conf().confs = old_user.conf().confs
        users[new_user.username()] = new_user

    ######################################################################
    # Set the worksheets of the new notebook equal to the ones from
    # the old one.
    ######################################################################

    def migrate_old_worksheet(old_worksheet):
        """
        Migrates an old worksheet to the new format.
        """
        old_ws_dirname = old_ws._Worksheet__filename.partition(os.path.sep)[-1]
        new_ws = new_nb.worksheet(old_ws.owner(), old_ws_dirname)

        # some ugly creation of new attributes from what used to be stored
        tags = {}
        try:
            for user, val in iteritems(old_ws._Worksheet__user_view):
                if isinstance(user, str):
                    # There was a bug in the old notebook where sometimes the
                    # user was the *module* "user", so we don't include that
                    # invalid data.
                    tags[user] = [val]
        except AttributeError:
            pass
        import time
        last_change = (old_ws.last_to_edit(), old_ws.last_edited())
        try:
            published_id_number = int(os.path.split(old_ws._Worksheet__published_version)[1])
        except AttributeError:
            published_id_number = None

        ws_pub = old_ws.worksheet_that_was_published().filename().split('/')
        ws_pub = (ws_pub[0], int(ws_pub[1]))

        obj = {'name': old_ws.name(), 'system': old_ws.system(),
               'viewers': old_ws.viewers(), 
               'collaborators' :old_ws.collaborators(),
               'pretty_print': old_ws.pretty_print(), 
               'ratings': old_ws.ratings(),
               'auto_publish': old_ws.is_auto_publish(), 'tags': tags,
               'last_change': last_change,
               'published_id_number': published_id_number,
               'worksheet_that_was_published': ws_pub
               }

        new_ws.reconstruct_from_basic(obj)

        base = os.path.join(dir, 'worksheets', old_ws.filename())
        worksheet_file = os.path.join(base, 'worksheet.txt')
        if os.path.exists(worksheet_file):
            text = open(worksheet_file).read()
            # delete first two lines -- we don't embed the title or
            # system in the worksheet text anymore.
            i = text.find('\n')
            text=text[i+1:]
            i = text.find('\n')
            text=text[i+1:]
            new_ws.edit_save(text)

        # copy over the DATA directory and cells directories
        try:
            dest = new_ws.data_directory()
            if os.path.exists(dest): 
                shutil.rmtree(dest)
            shutil.copytree(old_ws.data_directory(), dest)
        except Exception as msg:
            print(msg)

        try:
            if os.path.exists(old_ws.cells_directory()):
                dest = new_ws.cells_directory()
                if os.path.exists(dest): 
                    shutil.rmtree(dest)
                shutil.copytree(old_ws.cells_directory(), dest)
        except Exception as msg:
            print(msg)


        return new_ws

    worksheets = WorksheetDict(new_nb)
    num_worksheets = len(old_nb._Notebook__worksheets)
    print("Migrating (at most) %s worksheets..." % num_worksheets)
    from sage.misc.all import walltime
    tm = walltime()
    i = 0
    for ws_name, old_ws in iteritems(old_nb._Notebook__worksheets):
        if old_ws.docbrowser(): continue
        i += 1
        if i % 25==0:
            percent = i / float(num_worksheets)
            # total_time * percent = time_so_far, so
            # remaining_time = total_time - time_so_far = time_so_far*(1/percent - 1)
            print("    Migrated %s (of %s) worksheets (about %.0f seconds remaining)" % (
                i, num_worksheets, walltime(tm) * (1 / percent - 1)))
        new_ws = migrate_old_worksheet(old_ws)
        worksheets[new_ws.filename()] = new_ws
    new_nb._Notebook__worksheets = worksheets

    # Migrating history
    new_nb._user_history = {}
    for username in old_nb.user_manager().users().keys():
        history_file = os.path.join(dir, 'worksheets', username, 'history.sobj')
        if os.path.exists(history_file):
            new_nb._user_history[username] = pickle.loads(open(history_file).read())

    # Save our newly migrated notebook to disk
    new_nb.save()

    print("Worksheet migration completed.")
    return new_nb

def make_path_relative(dir):
    r"""
    Replace an absolute path with a relative path, if possible.
    Otherwise, return the given path.

    INPUT:

    - ``dir`` - a string containing, e.g., a directory name

    OUTPUT:

    - a string
    """
    base, file = os.path.split(dir)
    if os.path.exists(file):
        return file
    return dir

##########################################################
# Misc
##########################################################


def sort_worksheet_list(v, sort, reverse):
    """
    Sort a given list on a given key, in a given order.

    INPUT:

    - ``sort`` - a string; 'last_edited', 'owner', 'rating', or 'name'

    - ``reverse`` - a bool; if True, reverse the order of the sort.

    OUTPUT:

    - the sorted list
    """
    f = None
    if sort == 'last_edited':
        def c(a):
            return a.last_edited()
        reverse = not reverse
        f = c
    elif sort == 'name':
        def c(a):
            return (a.name().lower(), -a.last_edited())
        f = c
    elif sort == 'owner':
        def c(a):
            return (a.owner().lower(), -a.last_edited())
        f = c
    elif sort == "rating":
        def c(a):
            return (a.rating(), -a.last_edited())
        reverse = not reverse
        f = c
    else:
        raise ValueError("invalid sort key '%s'" % sort)
    v.sort(key=f, reverse=reverse)