This file is indexed.

/usr/share/refdb/www/index.php is in refdb-www 1.0.2-3ubuntu1.

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
<?php
/*==================================================

index.php

RefDB Web Interface

This file provides a web-based interface for RefDB. It supports all basic operations: 
e.g query, edit/update and delete.

The same file (with includes, stylesheets and related files) is used for all operations 
and pages.

This version was written more or less from scratch by by Daniel Paul O'Donnell and 
Dominik Reusser. Some sections were adapted from the previous RefDB web interface.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   
   You should have received a copy of the GNU General Public License
   along with this program; if not, see <http://www.gnu.org/licenses/>

===================================================*/

/*-----------------------------------------------------------------------

Part 1: Some initialisation

This section prepares initial values and variables, and calls essential includes, functions, 
and objects

-------------------------------------------------------------------------*/

// First start session (see http://ca.php.net/session_start). This allows variables to be kept alive as long as the browser is engaged. 
session_start();

// Set the error reporting (http://ca.php.net/error-reporting and http://ca.php.net/manual/en/ref.errorfunc.php). E_ALL for debugging, E_ERROR for publication
error_reporting(E_ALL); // debugging error level
//error_reporting(E_ERROR); // publication error level

// Load refdb interface
require_once "includes/refdblib.inc.php";

// Load functions
require_once "includes/functions.inc.php";

//Set session variables
// Note: it is not clear this is necessary $refdbc="refdbc", etc., maybe enough 
// This is also where path names are set during install.
    
$_SESSION["refdbc"]="/usr/bin/refdbc";
$_SESSION["refdba"]="/usr/bin/refdba";
$_SESSION["path"]="/usr/bin";
$refdbc=$_SESSION["refdbc"];
$refdba=$_SESSION["refdba"];


/*=================================================

PART 2: Check for cookies from previous session

The login screen allows users to "remember me on this computer". If the "remember
me button is checked, user name, database, and password are stored in cookies.

This section checks whether the cookies exist and are complete. If they are it uses 
their values to establish the session; otherwise it directs the user to the login screen.

This section could be cleaned up:

1) There is probably a better (more secure) way of handling Login information
2) The database cookie is odd: it is set to "remember me" whatever the user does

=================================================*/

/* Username and password Cookie (refdb) */
// Check for availability and completeness of the existing refdb session cookie
// A complete cookie has values for both $name and $passwd.
if (isset($_COOKIE['refdb'])) {
  // If either is missing or set to null, kill the session.
  if (!isset($_COOKIE['refdb']['name'])||!isset($_COOKIE['refdb']['passwd'])) {
    // Delete any remaining parts of the cookie array by setting the components to more than one year in the past.
    setcookie('refdb[name]', "", time() - 3600 * 24 * 400);
    setcookie('refdb[passwd]', "", time() - 3600 * 24 * 400);
    setcookie('database', "", time() - 3600 * 24 * 400);

    // Now destroy the PHP $_SESSION variables: see the comments in http://ca.php.net/manual/en/function.session-unset.php
    /* Note: Removed session_unset following advice at http://ca.php.net/manual/en/function.session-destroy.php: 
                "Note:  Only use session_unset() for older deprecated code that does not use $_SESSION.") */
    $_SESSION=array();
    session_destroy();
            
    // Now start the session again, because we'll need it to be started before we log on
    session_start();
    // Set a warning for use on the login page indicating what we have done
    $warning="There was a problem closing your last session.<br/>Please re-enter your username and password.";
  }
  //If the refdb cookie has values for both $username and $passwd, use the cookie values to set the session variables
  else {
    $_SESSION['passwd']=$_COOKIE['refdb']['passwd'];
    $_SESSION['name']=$_COOKIE['refdb']['name'];
  }
}
// If the refdb cookie is missing or incomplete, there may be input from the login screen, or we may need 
// to go to the login screen for the first time
else {
  // Case 1: We have come here from the login form
  // Check if there is input from the login form use that we can use
  if (isset($_POST['name'])&&isset($_POST['passwd'])) {
    // If both name and passwd are set, check whether they both have values other than ""
    if (($_POST['name']!="")&&($_POST['passwd']!="")) {

      //this is an attempt at a validity checker. It doesn't work though: even if you pass, you end up at the login screen
      /*        $username=escapeshellarg($_POST['name']);
        $passwd=escapeshellarg($_POST['passwd']);
                $testcmd="$refdbc -u $username -w $passwd -C listdb -c cat";
                exec($testcmd,$lines,$exit_state);
                switch ($exit_state) {
                            case 0:
                                $login="true";
                            case 1:
                                $login="false";
                        }
                if ($login=="true") { */
      $_SESSION["passwd"]=$_POST['passwd'];
      $_SESSION["name"]=$_POST['name'];
      // Establish new refdb cookie 
      // Check if the remember me box was checked
      if (isset($_POST['rememberMe'])) {
	// if yes, set $duration to 1 year for the cookie
	$duration=time() + 3600 * 24 * 365;
      } 
      else {
	// otherwise set the duration for this session only (i.e. null)
	$duration=0;
      }
      // Now set new cookies using form data we have just converted to session data
      setcookie ("refdb[name]", $_SESSION['name'], $duration);
      setcookie ("refdb[passwd]", $_SESSION['passwd'], $duration);
    }
    // if one or both of the $username and $passwd variables are not set, set a warning for use on the login form
    else {
      $warning="Please supply a valid username and password";
    }
  }
  // Case 2: The user has not been here before as far as we can tell and is going to be sent to the login screen
  // Set the warning for use on the login form
  else {
    $warning="Please supply a username and password";
  }
}

// This checks whether the database has been selected on the form
// If it has, it sets a new cookie.
if (isset($_POST['selectedDatabase'])){
  $_SESSION['database']=$_POST['selectedDatabase'];
  //remember database for one year anyway . It is not checked if name and password do not exist
  setcookie ("database", $_SESSION['database'],time() + 3600 * 24 * 365);
}
        
/* Database Cookie (database) */ 
//Does a database cookie already exist? If so, use its values
if (isset($_COOKIE['database'])) {
  $_SESSION['database']=stripQuotes($_COOKIE['database']);
}

// Preferences
if (!session_is_registered('reference_limit')) {
  $_SESSION['reference_limit'] = 10;
}

if (!session_is_registered('index_limit')) {
  $_SESSION['index_limit'] = 50;
}

/*=================================================

PART 3 Decide where to go

Now we check whether after all this, we have a session name and passwd. If we do not, we go
to the login form. If we do, we check to see whether we have a $thisPage variable.
    
The two usual choices for a first hit on the URL are Login (if nothing is set) or Search (if
the session variables are set but not the $thisPage).
After the first search or login, the $thisPage variable becomes more common. 

=================================================*/

// First we check whether session name or password variables have been set above.
if (!isset($_SESSION['name'])||!isset($_SESSION['passwd'])) {
  // If either has not been set, then we set this page to Login, since we will need to login
  $thisPage="Login";
}
// If both session variables have been set, then we are logged in. 
else {
  //First let's escape the $passwd and $username variables so the can be passed to the shell from here on
  /* SECURITY note: $_SESSION['name'] and $_SESSION['passwd'] should not be used hereafter. */
  $username=escapeshellarg($_SESSION['name']);
  $passwd=escapeshellarg($_SESSION['passwd']);
        
  $my_refdba = new RefDB($username, $passwd, "", "", $refdba);
  $my_refdbc = new RefDB($username, $passwd, "", "", $refdbc);

  $operation="";
  $ID="";
  // If $sendQuery is set we are being sent an operation. Check if it is set.
  if(isset($_POST['sendQuery'])) {
    $sendQuery=$_POST['sendQuery'];
    // Three types of $sendQuery (edit, delete, and display) require extraction of an ID number from the variable value; check if that's what we are looking at.
    if (substr($sendQuery,0,4)=="edit") {
      $operation="edit";
      $ID=substr($sendQuery,5);
    }
    elseif (substr($sendQuery,0,6)=="delete") {
      $operation="delete";
      $ID=substr($sendQuery,7);
    }
    elseif (substr($sendQuery,0,7)=="display") {
      $operation="display";
      $citekey=substr($sendQuery,8);
    }
    elseif ($sendQuery=="next") {
      $_SESSION['offset'] += $_SESSION['limit'];
      $_SESSION['repeat'] = 1;
      $operation="Search";
    }
    elseif ($sendQuery=="previous") {
      $_SESSION['offset'] -= $_SESSION['limit'];
      if ($_SESSION['offset'] < 0) {
	$_SESSION['offset'] = 0;
      }
      $_SESSION['repeat'] = 1;
      $operation="Search";
    }
    elseif ($sendQuery=="nextindex") {
      $_SESSION['offset'] += $_SESSION['limit'];
      $_SESSION['repeat'] = 1;
      $operation="Search Indices";
    }
    elseif ($sendQuery=="previousindex") {
      $_SESSION['offset'] -= $_SESSION['limit'];
      if ($_SESSION['offset'] < 0) {
	$_SESSION['offset'] = 0;
      }
      $_SESSION['repeat'] = 1;
      $operation="Search Indices";
    }
    elseif ($sendQuery=="Set preferences") {
      // do some simple value checks
      // prefs_set is set in any case. The value remains 0 if all went ok
      // If the value is > 0, something went wrong and the Preferences page
      // can use the value to see which variable caused a problem. The first
      // variable adds 2^0, the second one 2^1 and so on.
      $_SESSION['prefs_set'] = 0;
      if ((int)$_POST['reference_limit'] > 0) {
	$_SESSION['reference_limit'] = $_POST['reference_limit'];
      }
      else {
	$_SESSION['reference_limit'] = 1;
	$_SESSION['prefs_set'] += 1;
      }

      if ((int)$_POST['index_limit'] > 1) {
	$_SESSION['index_limit'] = $_POST['index_limit'];
      }
      else {
	$_SESSION['index_limit'] = 1;
	$_SESSION['prefs_set'] += 2;
      }
    }
    //Check if $sendQuery is a legal value
    elseif ($sendQuery=="Login"||
            $sendQuery=="Confirm deletion"||
            $sendQuery=="Cancel deletion"||
            $sendQuery=="Add reference"||
            $sendQuery=="Send File"||
            $sendQuery=="Search") {
      $operation=$sendQuery;
    }
    // if $sendQuery is none of the above, then it is illegal and needs to be cleaned out 
    else {
      unset($sendQuery);
      $operation="Illegal operation";
    }
  }
  else { // sendQuery was not set. Reset the session variables used in repeated queries
    $_SESSION['limit'] = $_SESSION['reference_limit'];
    $_SESSION['offset'] = 0;
    $_SESSION['repeat'] = 0;
    $_SESSION['totalhits'] = 0;
    unset($_SESSION['terms']);
    unset($_SESSION['kajqueryfield']);
  }



  // Now let's check whether thisPage has been set: if it has, we are responding to a user request; if it is not,
  // we are supposed to go to the default (Search) page.
  if(isset($_REQUEST['thisPage'])) {
    $thisPage=$_REQUEST['thisPage'];
    // SECURITY: compare $thisPage to a list of legal values; if it doesn't match, change it to the default (Search)
    if ($thisPage=="Search"||
	$thisPage=="Search results"||
	$thisPage=="Index results"||
	$thisPage=="Confirm"||                
	$thisPage=="Logout"||
	$thisPage=="Login"||
	$thisPage=="Search indices"||
	$thisPage=="Add-Edit-Delete"||
	$thisPage=="Upload"||
	$thisPage=="External databases"||
	$thisPage=="Preferences"||
	$thisPage=="Help") {
      $thisPage=$thisPage;
    }
    else {
      $thisPage="Search";
    }
  }
  else {
    $thisPage="Search";
  }
}

// Now we need to act on the $thisPage variable:
// If $thisPage is "logout"--i.e. the user has requested to logout, we need to kill the cookies and everything before anything
// is sent to the browser

if ($thisPage=="Logout") {
  // First delete the cookie array by setting the components to more than one year in the past.
  setcookie('refdb[name]', "", time() - 3600 * 24 * 400);
  setcookie('refdb[passwd]', "", time() - 3600 * 24 * 400);
  setcookie('database', "", time() - 3600 * 24 * 400);
  // Then destroy the PHP $_SESSION variables: see the comments in http://ca.php.net/manual/en/function.session-unset.php
  // (note Removed session_unset following advice at http://ca.php.net/manual/en/function.session-destroy.php: 
  // "Note:  Only use session_unset() for older deprecated code that does not use $_SESSION.")
  $_SESSION=array();
  session_destroy();        
}

// No  matter what happens next, we are going to need a doctype and head
// include_once('php/logo.inc.php');
echo "<!DOCTYPE html SYSTEM \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n";
echo "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n";
echo "    <head>\n";
echo "        <title>Refdb: " . $thisPage . "</title>\n";
echo "        <link href=\"css/main.css\" type=\"text/css\" rel=\"stylesheet\"/>\n";
echo "        <link href=\"css/navigationlist.css\" type=\"text/css\" rel=\"stylesheet\"/>\n";        
echo "        <link href=\"css/refdb-frequency.css\" type=\"text/css\" rel=\"stylesheet\" title=\"RefDB frequency\"/>\n";
echo "        <link href=\"css/refdb.css\" type=\"text/css\" rel=\"alternate stylesheet\" title=\"RefDB\"/>\n";
echo "        <meta http-equiv=\"content-type\" content=\"text-html; charset=utf-8\"/>";
echo "    </head>\n";
echo "    <body>\n";    
echo "        <div id=\"header\">\n";
echo "            <div id=\"status\">\n";
//check if there is a session name set; if there is, get the user name from it for the status box
//  echo "<p>DEBUG: session db went to:".$_SESSION['database'].".username went to:".$username."thisPage went to:".$thisPage."</p>";
if (isset($username) && !($thisPage=="Logout")) { 
  echo "                    <form action=\"" . $_SERVER['PHP_SELF'] . "\" method=\"post\">\n";
  echo "                        <p>You are logged in as <strong>" .htmlentities($username)."</strong>.<br/>\n";
  echo "                            Database:"; 
  echo "                                <select name=\"selectedDatabase\" onchange=\"this.form.submit();\">\n";
  $_SESSION['databases']=$my_refdbc->listdb("");

  // I cannot infer from the code nor find out by "echo" debugging where those extra single quotes come from. Running just about anything through stripQuotes solves the "invalid database" error message though (MH)
  if(!isset($_SESSION['database'])) {
    $_SESSION['database']=stripQuotes($_SESSION['databases'][0]); 
  }
  $selected = FALSE;
  foreach($_SESSION['databases'] as $aDatabase) {
    echo "<option value=\"".htmlentities(stripQuotes($aDatabase))."\"";
    //Mark the selected database as selected in the list
    if(stripQuotes($_SESSION['database']) == $aDatabase) {
      $selected=TRUE;
      $_SESSION['database'] = stripQuotes($aDatabase);
      echo " selected=\"selected\"";
    }
    echo">".htmlentities(stripQuotes($aDatabase))."</option>\n";
  }
  echo "                                </select><br/>\n";
  if(!$selected){
    echo" <p> Selected Database ".  $_SESSION['database'].  " is not valid, using ".  $_SESSION['databases'][0].  " instead";
    $_SESSION['database']=stripQuotes($_SESSION['databases'][0]); 

  }
  /*echo "                                <input type=\"submit\" name=\"sendQuery\" value=\"change\"/><br/>\n";*/
  echo "                                <a href=\"index.php?thisPage=Logout\">Switch User/Logout</a><br/>\n";
  echo "                    </form>\n";
  //SECURITY: Escaping database here, do not use from
  //SESSION herafter
  //We also made sure, the database really exists.
  $database=escapeshellarg($_SESSION['database']);
}
// If the session name has not been set, indicate that we are not logged in.
else {
  echo "                    <strong>Not logged in.</strong>\n";
}

// The getversion() function does not require a valid username/password combo so we'll just create a fake client. The 'real' clients may not yet be available if we're still on the login screen
$my_fakeclient = new RefDB("", "", "", "", $refdba);
$version = $my_fakeclient->getversion();
$version=$version[0];
$version=str_replace("markus@mhoenicka.de","",$version);
$version=str_replace("refdba ","",$version);
echo "        </div>\n";
echo "       <div id=\"logo\">\n";
echo "            <p>\n";
echo "                <a href=\"http://refdb.sourceforge.net\">\n";
echo "                    <img src=\"images/refdb.png\" alt=\"Refdb Logo.\" id=\"main_logo\"/>\n";
echo "                </a>\n";
//echo "                Reference manager and bibliography tool. Version $version";
echo "            </p>\n";
echo "        </div>\n";
echo "     </div>\n";

// If this page is neither Login nor Logout, add a navigation list
if ($thisPage!="Logout"&&$thisPage!="Login") {
  /* todo: is there a better place? */
  $my_refdbc->selectdb($database);
            
  // if $thisPage is not login, add navigation list as well
  //include_once('php/navigationlist.inc.php');
  echo "             <div id=\"navigationlist\">\n";
  echo "                <ul>\n";
  echo "                    <li";
  //check to see if $thisPage is matches any of the tabs and set the tab to current if it does
  /* NOTE: Not all $thisPage values match tabs: result screens, edit screens, and confirmation screens don't because a user cannot logically 
                        to these navigate these pages directly */ 
  if ($thisPage=="Search") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php\">Search records</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Search indices") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Search indices\">Search indices</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Add-Edit-Delete") {
    // The Add-Edit-Delete Page has three functions; you can only navigate to it if you want to add a new entry to
    // the database; if you are editing or deleting an entry you are sent there as a result of your action on another 
    // form. For this reason we need to check whether the $operation was set to either "edit" or "delete." If either is, then no
    // "currentpage" is set; if neither is, then we have got here by selecting the "Add an Entry" tab and currentpage should be set
    if ($operation != "edit"
	&& $operation != "delete"
	&& $operation != "display") {
      echo " id=\"currentpage\"";
    }
  }
  echo "><a href=\"index.php?thisPage=Add-Edit-Delete\">Add Reference</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Upload") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Upload\">Upload from local file</a></li>\n";
  echo "                    <li";
  if ($thisPage=="External databases") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=External databases\">External databases</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Preferences") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Preferences\">Preferences</a></li>\n";
  echo "                    <li";
  if ($thisPage=="Help") {
    echo " id=\"currentpage\"";
  }
  echo "><a href=\"index.php?thisPage=Help\">Help</a></li>\n";
  echo "                </ul>\n";
  echo "            </div>\n";
}
// No matter what $thisPage was, we are going to need body text. Add appropriate content based on the nature of the $thisPage variable
switch($thisPage) {
  /***************************************************************************************************************
                
                LOGOUT
                
  ****************************************************************************************************************/
 case('Logout'):
   // if $thisPage is Logout, we have already run the scripts to kill the session. This content informs the user of this fact.
   echo "<div id=\"login\">";
   echo "    <h1>Logout</h1>";
   echo "    <p>You have successfully logged out.<br/>You will need to log in again to access Refdb.</p>";
   echo "    <p><a href=\"index.php?thisPage=Login\">Return to Login Screen</a></p>";
   echo "</div>";
   break;
   /***************************************************************************************************************
                
                LOGIN
                
   ****************************************************************************************************************/
 case('Login'):
   // If $thisPage is Login, just add login form at this point
   echo "<div id=\"login\">\n";
   echo "    <h1>Login</h1>\n";
   echo "    <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Search\" method=\"post\" enctype=\"multipart/form-data\">\n";
   //Add any warnings collected above
   if (isset($warning)) {
     echo "<div class=\"warning\"><p><strong class=\"warning\">" . $warning . "</strong></p></div>\n";
     unset($warning);
   }
   echo "        <p>Username:<br/><input type=\"text\" name=\"name\" size=\"16\" maxlength=\"16\"/></p>\n";
   echo "        <p>Password:<br/><input type=\"password\" name=\"passwd\" size=\"16\" maxlength=\"16\"/></p>\n";
   echo "        <p>Remember me on this computer <input type=\"checkbox\" name=\"rememberMe\" value=\"rememberMe\"/></p>\n";
   echo "        <p><input id=\"loginbutton\" type=\"submit\" name=\"sendQuery\" value=\"Login\"/></p>\n";
   echo "    </form>\n";
   echo "</div>\n";
   break;
   /***************************************************************************************************************
                
                ADD-EDIT-DELETE
                
                Add-Edit-Delete all use the same form. But different content and operations are used depending on which  we want
                As a result we need to treat each operation separately in this section depending on the value of $operation:
                
                1) if $operation=="delete" go to delete
                2) if $operation=="edit" go to edit
                3) otherwise, go to add
                
   ****************************************************************************************************************/
 case('Add-Edit-Delete'):

   /*-------------------------------------------------------------------------------------------------------
                    Delete

                    If $operation=="delete" we come here.
                    This page pulls the entry that is to be deleted from refdb, presents it and the refdb delete command to the user and asks them
                    to confirm that this is what they want to do.
                    -------------------------------------------------------------------------------------------------------*/
   if ($operation=="delete") {

     // define variables
     $searchcmd=$_POST['searchcmd'];
     $searchdelTerms=":ID:=$ID";
     $searchdelcmd=$corecmd . $searchdelTerms;
     $delTerms=" -C deleteref $ID";
     $delcmd=$ID;
     $displaydelcmd = $displaycmd . $delTerms;
                
     // search refdb for entry that is to be deleted
     $lines = $my_refdbc->getref("risx", "ALL", "", "", "", "", "", "", $searchdelTerms);

     // print form
     echo "        <div id=\"content\">\n";
     echo "            <h2>Confirm deletion</h2>\n";
     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Confirm\" method=\"POST\" enctype=\"multipart/form-data\">\n";
     echo "                <h3 class=\"warning\"><strong>Warning! This operation cannot be undone</strong></h3>\n";
     echo "                <p>You have requested that Refdb delete the following reference. This operation cannot be undone.</p>\n";
     echo "                <div style=\"margin-left:1em;margin-right:1em;border:thin gray solid;font-size:70%;\">\n";
                        
     // print entry that is to be deleted; "false" refers to whether or not we need buttons to appear in this area (we don't)
     risx_xhtmlprocessor($lines,"false");
     echo "                <p>If you are sure you want this entry to be deleted permanently from your bibliography, select <strong>Delete!</strong>.";
     echo "                    Otherwise choose <strong>Cancel!</strong> or use your browser's back button.</p>\n";
     echo "                <p>(If you select <strong>Delete!</strong>, the following command will be sent to the server:" . $displaydelcmd . ").</p>\n";
     echo "                <p><button type=\"submit\" name=\"sendQuery\" value=\"Confirm deletion\">Delete!</button>&#x00A0;";
     echo "                    <button type=\"submit\" name=\"sendQuery\" value=\"Cancel deletion\">Cancel!</button></p>\n"; 
     echo "                <p class=\"hidden\"><input type=\"hidden\" name=\"delcmd\" value=\"" . $ID . "\"/>\n";
     echo "                    <input type=\"hidden\" name=\"searchcmd\" value=\"" . $searchcmd . "\"/>\n";
     echo "                 </p>\n";
     echo "            </form>\n";
     echo "        </div>\n";
     unset($operation);
   }

   /*--------------------------------------------------------------

          display: display a dataset in a particular format

--------------------------------------------------------------------*/

   else if ($operation == "display") {
     // search refdb for entry that is to be edited
     $format = $_REQUEST["format$citekey"];
     //     echo "<p>format went to $format, id went to $ID</p>";
     $lines = $my_refdbc->getref($format, "ALL", "", "", "", "", "", "", ":CK:=$citekey");
     $formats = array("ris" => "RIS",
		 "risx" => "risx",
		 "mods" => "MODS",
		 "bibtex" => "bibtex",
		 "db31" => "DocBook SGML",
		 "db31x" => "DocBook 4 XML",
		 "db50x" => "DocBook 5 XML",
		 "teix" => "TEI P4",
		 "tei5x" => "TEI P5");
     $my_format = $formats[$format];
     echo "        <div id=\"content\">\n";
     echo "            <h2>Display dataset <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$citekey\">$citekey</a> as $my_format</h2>\n";
     echo "            <pre>";
     foreach ($lines as $line) {
       // postprocess lines, e.g. substitute <>
       $fixed_line = str_replace(array("<", ">"), array("&lt;", "&gt;"), $line);
       echo "<p>$fixed_line</p>";
     }
     echo "            </pre>";
     echo "         </div>";
     unset($operation);
   }

   /*-------------------------------------------------------------------------------------------------------
                    Edit and Add

                    If $operation!="delete" we come here.

                    -------------------------------------------------------------------------------------------------------*/
   else {
     $fields = array("ID", "sec_primary","AU","TI","N2","KW","sec_secondary",
		     "A2", "JF", "JO", "J1", "J2", "T2", "sec_tertiary",
		     "A3", "T3", "sec_publication", "VL", "IS", "CY",
		     "PB", "SN", "AD", "PY", "Y2", "SP", "EP", "N1",
		     "sec_shelf", "RP", "AV", "UR", "L1", "U1", "U2", "U3",
		     "U4", "U5", "M1", "M2", "M3");
     $dateFields = array( "PY", "Y2");
     $datePartFields= array( "PYyear", "PYmonth", "PYday", "PYother", "Y2year", "Y2month", "Y2day", "Y2other");
     $allFields= array_merge($fields, $datePartFields);
     $auFields= array("AU", "A2", "A3", "KW");
     $reverseAuFields = array_flip($auFields);
     //Entries in the Form
     $formfields=array();
     //Checked Fields
     $myFields=array();
     //Checked Array Fields
     $arrayFields=array();

     /*--------------------------------------------------------------------------------------------------- 
                        Case 2a $operation=="edit"
                        -----------------------------------------------------------------------------------------------------*/
     if ($operation=="edit") {
       // search refdb for entry that is to be edited
       $lines = $my_refdbc->getref("ris", "ALL", "", "", "", "", "", "", ":ID:=$ID");
       // Parse RIS for form

       $myFields=parseRSS ($lines);
       //ToDO remove the line below once we are only using checked fields in myField for creation of the form --DR
       $formfields=$myFields;
       //extract($RIS,EXTR_OVERWRITE);
     } 
     /*--------------------------------------------------------------------------------------------------- 
                        Case 2b default (="Add")
                        
                        If $thisPage=="Add-Edit-Delete, but $operation has not been set, we end up here
                        -----------------------------------------------------------------------------------------------------*/
     else {
       $sendQuery="";
       if(isset($_POST['formTY'])){
	 $formfields['TY'] = $_POST['formTY'];
       } 
       else {
	 $formfields['TY'] = "";
       }
       //Sequence defines also execution sequence for import and Form
       //We can check the entire field for an entry (invalidText) and replace it by some alternative text altText
       $invalidText = array( "PYyear" => "YYYY" , 
			     "PYmonth" => "NoMonth" , 
			     "PYday" => "NoDay" , 
			     "PYother" => "Other:",
			     "Y2year" => "YYYY" , 
			     "Y2month" => "NoMonth" , 
			     "Y2day" => "NoDay" , 
			     "Y2other" => "Other:"
			     );
       $altText = array("PYyear" => "", 
			"PYmonth" =>"" , 
			"PYday" =>""  , 
			"PYother" =>"",
			"Y2year" => "", 
			"Y2month" =>"" , 
			"Y2day" =>""  , 
			"Y2other" =>""
			);
       //We can also search for any number regular expressions and replace those field         first  s    repl  second  s    repl
       $searchReplaceText = array("AU" => array(array(", ", ","), array( "; ", ";")),
				  "A2" => array(array(", ", ","), array( "; ", ";")),
				  "A3" => array(array(", ", ","), array( "; ", ";")),
				  "KW" => array(array(", ", ",")),
				  "TY" => array(array("short", ""))  //short entries just have different forms (treated in $referencetype)
				  );
       foreach($allFields as $field){
	 $name='form'.$field;
	 if (isset($_POST[$name])) {
	   //Initialize all fields to avoid undefined fields $myFields[$field] = "";
	   $formfields[$field] = $_POST[$name]; //Replaces formXX
	   //include checks here for security reasons. All fields should be checked in the end
	   if(isset($invalidText[$field]) && $formfields[$field]==$invalidText[$field] ){
	     $formfields[$field]=$altText[$field];
	   }
	   if(isset($searchReplaceText[$field])){
	     foreach($searchReplaceText[$field] as $searchRepl){
	       $formfields[$field] = str_replace($searchRepl[0], $searchRepl[1],  $formfields[$field]);
	     }
	   }
	   //later on we check wheter the ID comes from RefDB or from the Form itself based on the fact whether myFields['ID'] exists
	   //if($field!="ID"){
	   $myFields[$field] = $formfields[$field]; //$XX is replaced my myFields['XX'];
	   //}
	 }
       }
       //compile publication year from multiple fields
       foreach($dateFields as $dateField){
	 if(isset($formfields[$dateField.'year'])){
	   $myFields[$dateField]=$formfields[$dateField.'year'];
	   if(isset($formfields[$dateField.'month'])){
	     $myFields[$dateField].= "/" . $formfields[$dateField.'month'];
	     if(isset($formfields[$dateField.'day'])){
	       $myFields[$dateField].="/" . $formfields[$dateField.'day'];
	       if(isset($formfields[$dateField.'other'])){
		 $myFields[$dateField].="/" . $formfields[$dateField.'other'];// Publication Year: YYYY/MM/DD/Otherinfo
	       }
	     }
	   }
	 }
       }
       //clear up formAU~A3
       foreach($auFields as $field){
	 $separator=";";
	 if(isset($formfields[$field])){
	   //$$ arrayFields is a multidimensional array. Each key, e.g. "KW", has a value consisting of an array of all KW entries
	   $arrayFields[$field] = explode($separator,$formfields[$field]);
	 }
       }
     } // end if ($operation=="edit")

     if ($operation=="Add reference") {
       $entry=""; // initialise entry text
       //Debugging output:
       //echo "<div type=\"content\">\n";

       /*
       echo "<p> dumping fields: \n";
       var_dump($fields);
       echo "</p><p> dumping arrayFields: \n";
       var_dump($arrayFields);
       echo "</p><p> dumping myFields: \n";
       var_dump($myFields);
       echo "</p><p> dumping formfields: \n";
       var_dump($formfields);
       echo "</p>";
       */

       // before adding the data to the database, we need to reverse-translate
       // whatever htmlentities() did to the data
       $un_htmlentities = get_html_translation_table(HTML_ENTITIES);
       $rev_un_htmlentities = array_flip($un_htmlentities);

       //ToDo Change code such that the following is not necessary anymore
       //$myFields['ID']=$ID;
       $tempfield =  str_replace("short", "", $formfields['TY']);
       $myFields['TY']=$tempfield;

       // write out the tag lines. Avoid empty tags
       foreach(array_merge(array("TY"),$fields) as $field){
	 //For authors and keywords add each element

	 if(array_key_exists($field, $reverseAuFields)){
	   foreach($arrayFields[$field] as $author){
	     if (isset($author) && strlen($author) > 0) {
	       $entry.= $field."  - ".trim(stripslashes(strtr($author, $rev_un_htmlentities)))."\n";
	     }
	   }
	 } 
	 else {
	   //for nonauthor and nonkeyword fields add field as is
	   if(isset($myFields[$field]) && strlen($myFields[$field]) > 0){
	     $entry.= $field."  - ".stripslashes(strtr($myFields[$field], $rev_un_htmlentities))."\n";
	   }
	 }
       }
       // terminate the RIS dataset
       $entry .= "ER  - \n";

       // currently the reference data are written to a temporary file and imported from that
       // todo: make this workaround unnecessary, needs work in refdblib.inc.php

       $tempFile=tempnam("/tmp", "refdb"); // make sure filename is unique - we may not be alone
       $fh=fopen($tempFile, 'w') or die("can't open file");
#       fwrite($fh, htmlentities($entry));
       fwrite($fh, $entry);
       fclose($fh);
       
       // if the ID field is set to an alphanumeric value, we're supposed to update, else add
       $lines = array(); // initialize as empty array
       if(isset($myFields["ID"]) && preg_match('/^[^0-9]+/', $myFields["ID"])){
	 $lines = $my_refdbc->updateref_from_file("", $tempFile, "ris", "UTF-8");
       }
       else {
	 $lines = $my_refdbc->addref_from_file("", $tempFile, "ris", "UTF-8");
       }
       unlink($tempFile); // clean up our trash

       $num_success = 0;
       $num_failed = 0;
       $my_citekey = "";

       foreach ($lines as $line) {
	 $resultfields = explode(':', $line);
	 $status = $resultfields[0];

	 // store citekey for later use. urlencoding $citekey should not be required as refdbd strips off offending characters anyway
	 if ($status == "406") {
	   $my_citekey = $resultfields[2];
	 }
	 if ($status == "408") {
	   $num_success++;
	 }
	 else if ($status == "413") {
	   $num_success++;
	 }
	 else if ($status == "414") {
	   $num_failed++;
	 }
       }

       if ($num_success > 0) {
	 // print form
	 echo "        <div id=\"content\">\n";
	 if(isset($myFields["ID"]) && preg_match('/^[^0-9]+/', $myFields["ID"])){
	   echo "            <h2>Successfully updated</h2>\n";
	   echo "                <p>The following entry has been successfully updated in your database as <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$my_citekey\">$my_citekey</a>:</p>\n<p>";
	 }
	 else {
	   echo "            <h2>Successfully added</h2>\n";
	   echo "                <p>The following entry has been successfully added to your database as <a href=\"index.php?thisPage=Search%20results&query=:CK:%3d$my_citekey\">$my_citekey</a>:</p>\n<p>";
	 }
	 echo "                <div style=\"margin-left:1em;margin-right:1em;border:thin gray solid;font-size:70%;\">\n"; 
	 echo "                    <pre>" . $entry . "</pre>";
	 echo "        </div>\n";
       } 
       else {
	 echo "        <div id=\"content\">\n";
	 echo "            <h2>Error while adding new entry</h2>\n";
	 echo "                <p>The following entry has <b>not</b> been successfully added to your database.</p>\n<p>";
	 echo "                <div style=\"margin-left:1em;margin-right:1em;border:thin gray solid;font-size:70%;\">\n"; 
	 echo "                    <pre>" . $entry . "</pre>";
	 echo "        </div>\n";
       }
     } 
     else {
       // print form
       echo "        <div id=\"content\">\n";
       $addeditWarning="<br/><strong>Do not use any markup (e.g. html &lt;b&gt;) in your entries</strong>.";
       if ($operation=="edit") {
	 echo "            <h2><a id=\"simple\" name=\"simple\">";
	 echo "Edit reference";
	 echo "</a></h2>\n";
	 echo "            <p>This form allows you to edit pre-existing entries in the database. $addeditWarning</p>\n";
       }
       else {
	 echo "            <h2><a id=\"simple\" name=\"simple\">";
	 echo "Add reference";
	 echo "</a></h2>\n";
	 echo "            <p>This form allows you to add new references to the database. $addeditWarning</p>\n";
       }
       echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Add-Edit-Delete\" method=\"POST\" enctype=\"multipart/form-data\">\n";
       echo "                \n<!-- Supplied by REFDB BOX -->\n";
       echo "                <div id=\"identification\" class=\"bibliographicform\" style=\"background:#DAE0D2;\">\n";
       echo "                    <h3>Citation Identification</h3>\n";
       echo "                                                            <p><strong>Citation Key:</strong>&#x00A0;<input class=\"searchText\" type=\"text\" name=\"formID\""; 
       if (isset($formfields['ID'])&&$formfields['ID']!="") {
	 echo " value=\"".$formfields['ID']."\"";
       }
       echo " size=\"20\" style=\"background: #C0C0C0;color:inherit;\"/>";
       if (isset($formfields['ID'])&&$formfields['ID']!="") {
	 echo "                            &#x00A0;<strong>(RefDB ID:</strong> <strong>#$ID</strong>)</strong>\n";
       }
       echo "<br/>(To be set by RefDB. Only expert users should edit this box. Mistakes may corrupt your data)\n";
       echo "                            </p>\n";
       echo "                </div>\n";
       echo "                <div id=\"formTY\" class=\"bibliographicform\">\n";
       echo "                    <h3>Reference Type</h3>\n";
       echo "                    <table>\n";
       echo "                        \n<!-- Reference Type -->\n";
       echo "                        <tr>\n";
       echo "                            <td class=\"formlabel\"><strong>Reference type</strong>:</td>\n"; 
       echo "                            <td class=\"forminput\">\n";
       form_selection($formfields['TY']);
       echo "                            </td>\n";
       echo "                        </tr>\n";
       echo "                    </table>\n";
       echo "                </div>\n";                        
       //***********************************************************************************************
       //Shorter way to create form!!!!!!!!!!!!!!
       //Here I would include the $fields later on
       foreach($fields as $theField){
	 if($theField == "ID"){
	   // A very dirty hack because ID-field is so far generated separately above. But needs to
	   // be in list in order to be read. TODO: Fixme
	 } 
	 else {
	   //Date fields require an array of defaults
	   if(in_array($theField, $dateFields)) {
	     if(isset($formfields[$theField.'year'])){
	       $defaultValue['year']=$formfields[$theField.'year'];
	     } 
	     else {
	       $defaultValue['year']="";
	     }
	     if(isset($formfields[$theField.'month'])){
	       $defaultValue['month']= $formfields[$theField.'month'];
	     } 
	     else {
	       $defaultValue['month']="";
	     }
	     if(isset($formfields[$theField.'day'])){
	       $defaultValue['day']= $formfields[$theField.'day'];
	     } 
	     else {
	       $defaultValue['day']="";
	     }
	     if(isset($formfields[$theField.'other'])){
	       $defaultValue['other']=$formfields[$theField.'other'];
	     } 
	     else {
	       $defaultValue['other']="";
	     }
	   } 
	   elseif(isset($myFields[$theField])){
	     $defaultValue = $myFields[$theField];
	   } 
	   else {
	     $defaultValue = "";
	   }
	   generateFormPart($formfields['TY'],$theField, $defaultValue);
	 }
       }
       echo "                </table>\n";
       echo "            </div>\n";
       echo "            <p id=\"addReference\"><button type=\"submit\" name=\"sendQuery\" value=\"Add reference\">";
       if ($operation=="edit") {
	 echo "Update reference";
       }
       else {
	 echo "Add reference";
       }
       echo "</button></p>\n";
       echo "        </form>\n";
       echo "    </div>\n";
       if (isset($operation)) {
	 unset($operation);
       }
     }
   }
   break;

   /*========================================================================

          Upload 
                    
                    This page is used to upload files for inclusion in a database
                    
                    ========================================================================*/
 case('Upload'):
   echo "<div id=\"content\">\n";
   echo "<form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Confirm\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   echo "<h2><a id=\"simple\" name=\"simple\">Import references</a></h2>\n";
   echo "<p>Add references from a file here. The following file types are recognized automatically:</p>\n<ul>";

   // dynamically create a list of supported input data formats

   // these are supported by default
   echo "<li>RIS</li>\n<li>risx</li>\n";

   // these need converters provided by refdb
   if (!is_null(nwhich("bib2ris-utf8"))) {
     echo "<li>BibTeX</li>\n";
   }

   // temporarily disabled as we cannot distinguish it from "good" RIS
   //   if (!is_null(nwhich("en2ris"))) {
   //     echo "<li>EndNote (tagged)</li>\n";
   //   }

   if (!is_null(nwhich("marc2ris"))) {
     echo "<li>MARC21 and UNIMARC</li>\n";
   }

   if (!is_null(nwhich("med2ris"))) {
     echo "<li>Pubmed (tagged and XML)</li>\n";
   }

   // these need bibutils. xml2ris is required for all of these converters
   if (!is_null(nwhich("xml2ris"))) {
     echo "<li>MODS</li>\n";
     if (!is_null(nwhich("copac2xml"))) {
       echo "<li>COPAC</li>\n";
     }
     if (!is_null(nwhich("endx2xml"))) {
       echo "<li>EndNote XML</li>\n";
     }
     if (!is_null(nwhich("isi2xml"))) {
       echo "<li>ISI</li>\n";
     }
   }

   // RIS, risx, and exports from the web of science</p>\n";
   echo "</ul>\n";
   echo "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"3000000\">\n";
   echo "File to import: <input name=\"userfile\" type=\"file\">\n";
   echo "<input type=\"submit\" name=\"sendQuery\" value=\"Send File\"/>\n";
   break;
   /*========================================================================
                    
                    Confirm

                    You come to this page from the Delete page after selecting confirming or canceling a deletion process. This page reports on
                    the results.

                    ========================================================================*/
 case('Confirm'):
   // define variables
   if (isset($_REQUEST['searchcmd'])) {
     $searchcmd=$_REQUEST['searchcmd'];
   }
   if (isset($_REQUEST['delcmd'])) {
     $delcmd=$_REQUEST['delcmd'];
   }
   echo "        <div id=\"content\">\n";
   // do whatever was selected
   if ($sendQuery=="Confirm deletion") {
     $lines = $my_refdbc->deleteref($delcmd);
     echo "<h2>Entry has been deleted</h2>\n";
     echo "<p>The requested entry has been permanently deleted from your database using the following";
   }
   elseif ($sendQuery=='Cancel deletion') {
     echo "<h2>Requested deletion has been cancelled</h2>\n";
     echo "<p>Your request has been cancelled. The entry has <strong>not</strong> been deleted.</p>\n";
   }
   elseif($sendQuery=='Send File') {
     if (!isset($_FILES['userfile'])
	 || !isset($_FILES['userfile']['name'])
	 || strlen($_FILES['userfile']['name']) == 0) {
       echo "Error: no file was specified";
     }
     else {
       $uploaddir='/tmp/';
       $filename=$uploaddir . $_FILES['userfile']['name'];
       echo "<pre>\n";
       if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filename)) {
	 echo "File is valid, and was successfully uploaded.  Here's some more debugging info:\n";
       } 
       else {
	 echo "Error while uploading file! Error:\n";
	 print($_FILES['userfile']['error']."\n");
	 echo "<a href=\"http://de.php.net/manual/de/features.file-upload.errors.php\" target=\"_blank\">error codes</a>\n";
       }
       echo "</pre>\n";
       importFile($filename, $my_refdbc);
     }
   }
   else {
     echo "<h2>Undefined error</h2>\n";
     echo "<p>Something has gone wrong, but we're not sure what it is.</p>\n";
   }
   echo "<p><a href=\"index.php\">Return to search form</a></p>\n";
   break;

   /*========================================================================
                    
                    Search results
                    
                    This page displays search results. You get here from the search screen after a successful search. Like all output forms, 
                    this page does not have an associated tab in the navigation list. This is because you cannot navigate to it--i.e. it is produced 
                    by refdb and the php. Moreover, as a user, you want to be able to select an arbitrary form from this point, including the 
                    form that produced these results. 
                    
                    ========================================================================*/
 case('Search results'):
   if ($_SESSION['repeat'] == 0) {
     // this is an original search. 'repeat' will be 1 only if we page
     // through a result set. In that case we don't have to build the
     // query again. Instead, we re-run the previous query but with a
     // different limit:offset

     //This array is used to build the query that will be sent to the getref command for the advanced search on the query page
     $fields=array("anyauthor"=>":AX:",
		   "anytitle"=>":TX:",
		   "anyjournal"=>":JX:",
		   "author"=>":A1:",
		   "editor"=>":A2:", 
		   "seditor"=>":A3:", 
		   "title"=>":TI:",
		   "booktitle"=>":T2:",
		   "seriestitle"=>":T3:",
		   "journaltitle"=>":JF:",
		   "shortjournaltitle"=>":JO:",
		   "publicationyear"=>":PY:",
		   "keyword"=>":KW:",
		   "Notes"=>":N1:",
		   "Abstract"=>":N2:",
		   "Address"=>":AD:",
		   "Reprint"=>":RP:",
		   "ISSN"=>":SN:",
		   "URL"=>":UR:",
		   "Publisher"=>":PB:",
		   "City"=>":CY:",
		   "U1"=>":U1:",
		   "U2"=>":U2:",
		   "U3"=>":U3:",
		   "U4"=>":U4:",
		   "U5"=>":U5:",
		   "M1"=>":M1:",
		   "M2"=>":M2:",
		   "M3"=>":M3:"
		   );

     //These are the logical operators used in the advanced search
     $ops=array("and"=>"AND",
		"or"=>"OR",
		"not"=>"NOT"
		);

     $equals=array("exact"=>"=",
		   "contains"=>"~",
		   "beginswith"=> "=^",
		   "endswith"=> "=$"
		   );

     // build base refdbc command

     if(isset($_POST['query'])){
       // for expert queries, currently not used
       $terms =$_POST['query'];
     } 
     elseif(isset($_POST['simplequery']) && $_POST['simplequery'] != "") {
       // search string in all fields
       $query="'".$_POST['simplequery']."'";
       $terms="";
       if (is_numeric($query)) {
	 $terms=":AX:~$query OR :TX:~$query OR :KW:~$query OR :UR:~$query OR :L1:~$query OR :L2:~$query OR :L3:~$query OR :L4:~$query OR :JX:~$query OR :RP:~$query OR :N1:~$query OR :AV:~$query OR :TY:~$query OR :PY:=$query OR :Y2:=$query OR :ID:=$query OR :CK:~$query OR :SN:~$query OR :N2:~$query OR :SP:~$query OR :EP:~$query OR :VL:~$query OR :IS:~$query OR :AD:~$query OR :CY:~$query OR :PB:~$query OR :U1:~$query OR :U2:~$query OR :U3:~$query OR :U4:~$query OR :U5:~$query OR :TO:~$query OR :AR:~$query OR :OS:~$query OR :DG:~$query OR :RT:~$query OR :CI:~$query OR :CU:~$query OR :SE:~$query OR :RE:~$query OR :MT:~$query OR :NV:~$query OR :EI:~$query OR :CO:~$query OR :CF:~$query OR :RN:~$query OR :CL:~$query OR :SC:~$query OR :PN:~$query OR :CN:~$query";
       }
       else {
	 $terms=":AX:~$query OR :TX:~$query OR :KW:~$query OR :UR:~$query OR :L1:~$query OR :L2:~$query OR :L3:~$query OR :L4:~$query OR :JX:~$query OR :RP:~$query OR :N1:~$query OR :AV:~$query OR :TY:~$query OR :CK:~$query OR :SN:~$query OR :N2:~$query OR :SP:~$query OR :EP:~$query OR :VL:~$query OR :IS:~$query OR :AD:~$query OR :CY:~$query OR :PB:~$query OR :U1:~$query OR :U2:~$query OR :U3:~$query OR :U4:~$query OR :U5:~$query OR :TO:~$query OR :AR:~$query OR :OS:~$query OR :DG:~$query OR :RT:~$query OR :CI:~$query OR :CU:~$query OR :SE:~$query OR :RE:~$query OR :MT:~$query OR :NV:~$query OR :EI:~$query OR :CO:~$query OR :CF:~$query OR :RN:~$query OR :CL:~$query OR :SC:~$query OR :PN:~$query OR :CN:~$query";
       }	 
     }
     elseif((isset($_POST['citationkey']) && $_POST['citationkey'] != "")
	    || (isset($_POST['doi']) && $_POST['doi'] != "")) {
       $citationkey=$_POST['citationkey'];
       $doi=$_POST['doi'];
       $terms="";
       if ($citationkey!="") {
	 $terms = ":CK:="."$citationkey";
       }
       else if ($doi != "") {
	 $terms = ":DO:="."$doi";
       }
     }
     elseif(isset($_POST['simplequery1'])) {
       $simplequery1=$_POST['simplequery1'];
       $simplequery2=$_POST['simplequery2'];
       $simplequery3=$_POST['simplequery3'];
       $simplequery4=$_POST['simplequery4'];
       $simplequery5=$_POST['simplequery5'];
       $simplequery6=$_POST['simplequery6'];
       $simplequery7=$_POST['simplequery7'];
       $simplequery8=$_POST['simplequery8'];
       $advancedquery1=$_POST['advancedquery1'];
       $advancedquery2=$_POST['advancedquery2'];
       $advancedquery3=$_POST['advancedquery3'];
       $advancedquery4=$_POST['advancedquery4'];
       $advancedquery1equals=$_POST['advancedquery1equals'];
       $advancedquery2equals=$_POST['advancedquery2equals'];
       $advancedquery3equals=$_POST['advancedquery3equals'];
       $advancedquery4equals=$_POST['advancedquery4equals'];
       $advancedquery1op=$_POST['advancedquery1op'];
       $advancedquery2op=$_POST['advancedquery2op'];
       $advancedquery3op=$_POST['advancedquery3op'];
       $advancedquery1field=$_POST['advancedquery1field'];
       $advancedquery2field=$_POST['advancedquery2field'];
       $advancedquery3field=$_POST['advancedquery3equals'];
       $advancedquery4field=$_POST['advancedquery4field'];
       //set search terms to NULL in order to begin building search
       $terms="";
       //build simple search. This assigns a variable that we will use to try to figure out if a field is to be used or not
       $first=true;
       //check if simplequeryAX is empty
       if ($simplequery1!="") {
	 //add search terms acquired from this field
	 $terms=":AX:~"."$simplequery1"." ";
	 //set $first to false so that we won't treat any additional fields that way
	 $first=false;
       }
       if ($simplequery2!="") {
	 //add search terms acquired from this field
	 if ($first) {
	   $terms=$terms.":PY:=".$simplequery2." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".":PY:"."=".$simplequery2." ";
	 }
       }
       if ($simplequery3!="") {
	 //add search terms acquired from this field
	 if ($first) {
	   $terms=$terms.":TX:"."~".$simplequery3." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".":TX:"."~".$simplequery3." ";
	 }
       }
       if ($simplequery4!="") {
	 //add search terms acquired from this field
	 if ($first) {
	   $terms=$terms.":JX:"."~".$simplequery4." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".":JX:"."~".$simplequery4." ";
	 }
       }
       if ($simplequery5!="") {
	 //add search terms acquired from this field
	 if ($first) {
	   $terms=$terms.":VL:"."~".$simplequery5." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".":VL:"."~".$simplequery5." ";
	 }
       }
       if ($simplequery6!="") {
	 //add search terms acquired from this field
	 if ($first) {
	   $terms=$terms.":IS:"."~".$simplequery6." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".":IS:"."~".$simplequery6." ";
	 }
       }
       if ($simplequery7!="") {
	 //add search terms acquired from this field
	 if ($first) {
	   $terms=$terms.":SP:"."~".$simplequery7." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".":SP:"."~".$simplequery7." ";
	 }
       }
       if ($simplequery8!="") {
	 //add search terms acquired from this field
	 if ($first) {
	   $terms=$terms.":KW:"."~".$simplequery5." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".":KW:"."~".$simplequery5." ";
	 }
       }
       if ($advancedquery1!="") {
	 //we should rewrite these so that a date choice has EQUALS as the $equals field, no matter what the user has chosen.
	 $field1=$fields[$advancedquery1field];
	 $equals1=$equals[$advancedquery1equals];
	 if ($first) {
	   $terms=$terms.$field1.$equals1.$advancedquery1." ";
	   $first=false;
	 }
	 else {
	   $terms=$terms."AND"." ".$field1.$equals1.$advancedquery1." ";
	 }
       }
       if ($advancedquery2!="") {
	 $field2=$fields[$advancedquery2field];
	 $equals2=$equals[$advancedquery2equals];
	 if ($first) {
	   $terms=$terms.$field2.$equals2.$advancedquery2." ";
	   $first=false;
	 }
	 else {
	   $op1=$ops[$advancedquery1op];
	   $terms=$terms.$op1." ".$field2.$equals2.$advancedquery2." ";
	 }
       }
       if ($advancedquery3!="") {
	 $field3=$fields[$advancedquery3field];
	 $equals3=$equals[$advancedquery3equals];
	 if ($first) {
	   $terms=$terms.$field3.$equals3.$advancedquery3." ";
	   $first=false;
	 }
	 else {
	   $op2=$ops[$advancedquery2op];
	   $terms=$terms.$op2." ".$field3.$equals3.$advancedquery3." ";
	 }
       }
       if ($advancedquery4!="") {
	 $field4=$fields[$advancedquery4field];
	 $equals4=$equals[$advancedquery4equals];
	 if ($first) {
	   $terms=$terms.$field4.$equals4.$advancedquery4." ";
	   $first=false;
	 }
	 else {
	   $op3=$ops[$advancedquery3op];
	   $terms=$terms.$op3." ".$field4.$equals4.$advancedquery4." ";
	 }
       }
       /*                        // Build the commandline query --> removed because it wasn't working
                        elseif($sendQuery=="Send command line query" ) {
                            $cmd=$commandlinequery;
                            $terms=$terms;
                        } */
       /*                        //  Query terms if you've returned from a search
                        elseif ($sendQuery=="Return to Search Results" ) {
                            $terms=$return;
                        } */
     } 
     elseif (isset($_REQUEST['query'])) {
       $raw_terms=$_REQUEST['query'];

       // escape regexp special characters
       $in_array = array('[', ']', '(', ')', '{', '}', '^', '$', '.', '+', '*', '?', '|');
       $out_array = array('\\[', '\\]', '\\(', '\\)', '\\{', '\\}', '\\^', '\\$', '\\.', '\\+', '\\*', '\\?', '\\|');
       $terms=str_replace($in_array, $out_array, $raw_terms);
       $terms = "'$terms'";
     }
   //   else {
     //No valid query, branching to Search
     //TODO This does not work yet. Work with include later on
   //     $thisPage = "Search";
   //     echo "<div id=\"content\">";
   //     echo "    <p>Sorry! Your request was an invalid search</p>";
   //     echo "</div>";
   //     break;
   //   }
   // Build final command by adding terms we have constructed to command built earlier. 
     $_SESSION['terms'] = $terms;
     $limit = $_SESSION['reference_limit'];
     $offset = 0;
     $lines = $my_refdbc->countref("", "", $terms);
     $_SESSION['totalhits'] = preg_replace('/.*:(\d+) .*/', '\1', $lines[0]);
   }
   else { // repeat search
     $terms = $_SESSION['terms'];
     $limit=$_SESSION['limit'];
     $offset=$_SESSION['offset'];
   }

   //check if the database has been set. If not give warning
   if ($database=="") {
     echo "        <div id=\"content\">\n";
     echo "            <h2>Database error</h2>\n";
     echo "            <p>Please select a database.</p>";
     echo "        </div>";
   }
   else {

     if ($offset > 0) {
       $lines = $my_refdbc->getref("risx", "", "", "", "", "$limit:$offset", "", "1", $terms);
     }
     else {
       $lines = $my_refdbc->getref("risx", "", "", "", "", "$limit", "", "1", $terms);
     }
     
     //Report on results
     //first set hits variable to hold count
     $hits="";
     $str=str_replace("<entry", "entry", $lines, $count);
     $hits=$count;
     //If count is 0, indicate there were no hits
     if ($hits<1) {
       $hits="no";
       $resultsnumber="results";
     }
     // Otherwise make $hits equal to the number of hits
     elseif ($hits==1) {
       $resultsnumber="result";
     }
     else {
       $resultsnumber="results";
     }

     $from_ref = $_SESSION['offset']+1;
     $to_ref = $_SESSION['offset'] + $_SESSION['limit'];
     if ($to_ref > $_SESSION['totalhits']) {
       $to_ref = $_SESSION['totalhits'];
     }
     echo "        <div id=\"content\">\n";
     echo "            <h2>Matching References</h2>\n";
     //     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Add-Edit-Delete\" method=\"POST\" enctype=\"multipart/form-data\">\n"; 
     /* echo "                <p><!-- removed for the moment because I don't know how to process arbitrary numbers of checkboxes ";
                        echo "                    <input type=\"submit\" value=\"Delete selected references\" name=\"sendQuery\"/>&#00A0;";
//                        echo "                    <input type=\"submit\" value=\"Add selected references to Personal List\" name=\"sendQuery\"/>&#X00A0;";
//                        echo "                    <input type=\"submit\" value=\"Remove selected references from Personal List\" name=\"sendQuery\"/>--></p>\n"; */
     echo "                <p>Your search for <strong>" .$terms . "</strong> generated <strong>" . $_SESSION['totalhits'] . "</strong> " . $resultsnumber . ".</p>";
     if ($_SESSION['totalhits'] > $_SESSION['limit']) {
       echo "<p>Displaying datasets " . $from_ref . " to " . $to_ref . ".</p>";
     }
     //     echo "<br/>\n";
     // display the paging buttons only if appropriate
     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Search results\" method=\"POST\" enctype=\"multipart/form-data\">\n"; 
     if ($offset > 0 || $hits == $limit) {
       echo "<p>";
       if ($offset > 0) {
	 echo "<button name=\"sendQuery\" type=\"submit\" value=\"previous\">previous</button>";
       }
       if ($hits == $limit) {
	 echo "<button name=\"sendQuery\" type=\"submit\" value=\"next\">next</button>";
       }
       echo "</p>\n";
     }
     echo "            </form>\n";
     //     echo "                    (RefDB command: <code>" . $displaysearchcmd . "</code>)</p>\n";

     echo "                <p>Back to <a href=\"index.php\">Search screen</a>.</p>\n"; 
     // If the search had results, display them:
     $lineNumber=1;
     $checkboxNumber=risx_xhtmlprocessor ($lines,"true");

     //     echo "                <p class=\"hidden\"><input type=\"hidden\" name=\"terms\" value=\"" . $terms . "\"/>\n";
     // echo "                <input type=\"hidden\" name=\"scope\" value=\"" . $scope . "\"/>\n";
     //     echo "                <input type=\"hidden\" name=\"searchcmd\" value=\"" . $searchcmd . "\"/>\n";
     //     echo "                <input type=\"hidden\" name=\"numberOfCheckBoxes\" value=\"" . $checkboxNumber . "\"/></p>\n";
     //     echo "            </form>\n";

     // display the paging buttons only if appropriate
     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Search results\" method=\"POST\" enctype=\"multipart/form-data\">\n"; 
     echo "<p>";
     if ($offset > 0) {
       echo "<button name=\"sendQuery\" type=\"submit\" value=\"previous\">previous</button>";
     }
     if ($hits == $limit) {
       echo "<button name=\"sendQuery\" type=\"submit\" value=\"next\">next</button>";
     }
     echo "</p>\n";
     echo "            </form>\n";

     echo "        </div>\n";
   }
   break;
   /*========================================================================
                
                Help
                
                ========================================================================*/
 case('Help'):
   echo "    <div id=\"content\">\n";
   echo "           <h2>Help and Manuals</h2>\n";
   echo "           <p>The help function and manual for this version of PHP_RefDB is not yet complete. In the mean time, here are links to manuals and instructions for the command line engine.</p>\n";
   echo "           <ul>\n";
   echo "           <li><a href=\"http://refdb.sourceforge.net/manual/index.html\"><em>RefDB Handbook</em></a>: A comprehensive manual to the RefDB suite.</li>\n";
   echo "           <li><a href=\"http://refdb.sourceforge.net/tutorial/book1.html\"><em>RefDB Tutorial</em></a>: A users manual aimed at the needs of clients rather than administrators.</li>\n";
   echo "           </ul>\n";
   echo "   </div>\n";
   break;
   /*========================================================================

                Preferences
                
                ========================================================================*/
 case('Preferences'):
   echo "<div id=\"content\">";
   echo "    <h2>User Preferences</h2>";
   if (session_is_registered('prefs_set')) {
     if ($_SESSION['prefs_set']==0) {
       echo "    <h3 class=\"ok\">successfully changed</h3>\n";
     }
     else {
       echo "    <h3 class=\"warn\">preferences changed, values corrected</h3>\n";
     }
   }
   echo "    <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Preferences\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   if (session_is_registered('prefs_set') && ($_SESSION['prefs_set'] & 1)) {
     echo "    <p class=\"warn\">Number of references per page <input type=\"text\" name=\"reference_limit\" size=\"5\" maxlength=\"5\" value=\"" . $_SESSION['reference_limit'] . "\"></p>";
   }
   else {
     echo "    <p>Number of references per page <input type=\"text\" name=\"reference_limit\" size=\"5\" maxlength=\"5\" value=\"" . $_SESSION['reference_limit'] . "\"></p>";
   }

   if (session_is_registered('prefs_set') && ($_SESSION['prefs_set'] & 2)) {
     echo "    <p class=\"warn\">Number of index entries per page <input type=\"text\" name=\"index_limit\" size=\"5\" maxlength=\"5\" value=\"" . $_SESSION['index_limit'] . "\"></p>";
   }
   else {
     echo "    <p>Number of index entries per page <input type=\"text\" name=\"index_limit\" size=\"5\" maxlength=\"5\" value=\"" . $_SESSION['index_limit'] . "\"></p>";
   }
   echo "    <p><input type=\"submit\" name=\"sendQuery\" value=\"Set preferences\"></p>";
   echo "    </form>\n";
   echo "</div>";
   if (session_is_registered('prefs_set')) {
     session_unregister('prefs_set');
   }
   break;
   /*========================================================================
                
                Index Results
                
                ========================================================================*/
 case('Index results'):
   if ($_SESSION['repeat'] == 0) {
     // this is an original search. 'repeat' will be 1 only if we page
     // through a result set. In that case we don't have to build the
     // query again. Instead, we re-run the previous query but with a
     // different limit:offset

     //if field is not set go to the form
     if (!isset($_POST['kajqueryfield'])||!isset($_POST['kajquery'])){
       $thisPage ='Search indices'; 
     }
     // Otherwise show results
     else{ 
       //build the command
       $kajqueryfield = $_POST['kajqueryfield'];
       $kajquery = $_POST['kajquery'];
       $short = selectTag($_POST['kajqueryfield']);
                        
       $in_array = array('[', ']', '(', ')', '{', '}', '^', '$', '.', '+', '*', '?', '|');
       $out_array = array('\\[', '\\]', '\\(', '\\)', '\\{', '\\}', '\\^', '\\$', '\\.', '\\+', '\\*', '\\?', '\\|');
       $terms=str_replace($in_array, $out_array, $kajquery);
       $terms = "'$terms'";

       $_SESSION['terms'] = $terms;
       $limit = $_SESSION['index_limit'];
       $offset = 0;
       $_SESSION['kajqueryfield'] = $kajqueryfield;

       switch($kajqueryfield) {
       case "keyword":
	 $lines = $my_refdbc->getkw("", "", $terms);
	 break;
       case "author":
	 $lines = $my_refdbc->getau("", "", $terms);
	 break;
       case "editor":
	 $lines = $my_refdbc->geted("", "", $terms);
	 break;
       case "seditor":
	 $lines = $my_refdbc->getas("", "", $terms);
	 break;
       case "journalfull":
	 $lines = $my_refdbc->getjf("f", "", "", $terms);
	 break;
       case "journalabbrev":
	 $lines = $my_refdbc->getjo("f", "", "", $terms);
	 break;
       case "journalabbrev1":
	 $lines = $my_refdbc->getj1("f", "", "", $terms);
	 break;
       case "journalabbrev2":
	 $lines = $my_refdbc->getj2("f", "", "", $terms);
	 break;
       }
       $_SESSION['totalhits'] = count($lines);
     }
   }
   else { // repeat search
     $kajquery = $_SESSION['terms'];
     $limit=$_SESSION['limit'];
     $offset=$_SESSION['offset'];
     $kajqueryfield = $_SESSION['kajqueryfield'];
   }
   echo "<div id=\"content\">
                            <h2>Results</h2>
                            <h3>Your index search for <strong><em>" . $kajquery . "</em></strong> in <strong><em>". $kajqueryfield ."</em></strong> generated " . $_SESSION['totalhits'] . " entries.</h3>";
       
   $short = selectTag($kajqueryfield);

   if ($offset > 0) {
     $limit_string = $limit . ":" . $offset;
   }
   else {
     $limit_string = "$limit";
   }

   switch($kajqueryfield) {
   case "keyword":
     $lines = $my_refdbc->getkw($limit_string, "relfreq", $terms);
     break;
   case "author":
     $lines = $my_refdbc->getau($limit_string, "relfreq", $terms);
     break;
   case "editor":
     $lines = $my_refdbc->geted($limit_string, "relfreq", $terms);
     break;
   case "seditor":
     $lines = $my_refdbc->getas($limit_string, "relfreq", $terms);
     break;
   case "journalfull":
     $lines = $my_refdbc->getjf("f", $limit_string, "relfreq", $terms);
     break;
   case "journalabbrev":
     $lines = $my_refdbc->getjo("f", $limit_string, "relfreq", $terms);
     break;
   case "journalabbrev1":
     $lines = $my_refdbc->getj1("f", $limit_string, "relfreq", $terms);
     break;
   case "journalabbrev2":
     $lines = $my_refdbc->getj2("f", $limit_string, "relfreq", $terms);
     break;
   }

   $hits = count($lines);

   $from_ref = $_SESSION['offset']+1;
   $to_ref = $_SESSION['offset'] + $_SESSION['limit'];
   if ($to_ref > $_SESSION['totalhits']) {
     $to_ref = $_SESSION['totalhits'];
   }

   if ($_SESSION['totalhits'] > $_SESSION['limit']) {
     echo "<p>Displaying datasets " . $from_ref . " to " . $to_ref . ".</p>";
   }

   if ($lines) {
     // display the paging buttons only if appropriate
     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Index results\" method=\"POST\" enctype=\"multipart/form-data\">\n"; 
     if ($offset > 0 || $hits == $limit) {
       echo "<p>";
       if ($offset > 0) {
	 echo "<button name=\"sendQuery\" type=\"submit\" value=\"previousindex\">previous</button>";
       }
       if ($hits == $limit) {
	 echo "<button name=\"sendQuery\" type=\"submit\" value=\"nextindex\">next</button>";
       }
       echo "</p>\n";
     }
     echo "            </form>\n";

     foreach($lines as $line) {
       list($relfreq, $item) = explode(":", $line);
       echo "<p class='result relfreq$relfreq'>
                                    <a href=index.php?thisPage=Search%20results&query=".$short."~".urlencode("".$item."")." >" . 
	 str_replace(",", ", ", $item) . "
				  </a>
			       </p>\n";
     }

     // display the paging buttons only if appropriate
     echo "            <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Index results\" method=\"POST\" enctype=\"multipart/form-data\">\n"; 
     if ($offset > 0 || $hits == $limit) {
       echo "<p>";
       if ($offset > 0) {
	 echo "<button name=\"sendQuery\" type=\"submit\" value=\"previousindex\">previous</button>";
       }
       if ($hits == $limit) {
	 echo "<button name=\"sendQuery\" type=\"submit\" value=\"nextindex\">next</button>";
       }
       echo "</p>\n";
     }
     echo "            </form>\n";
   }
   else {
     echo "<p>Sorry, there were no results.</p>";
   }
   echo "</div>";
   break;

   /*========================================================================

                Search indices
                
                ========================================================================*/
 case('Search indices'):
   // include_once('php/searchIndices.inc.php');
   $_SESSION['limit'] = $_SESSION['index_limit'];
   $_SESSION['offset'] = 0;
   $_SESSION['repeat'] = 0;
   $_SESSION['totalhits'] = 0;
   unset($_SESSION['terms']);
   unset($_SESSION['kajqueryfield']);
   echo "    <div id=\"content\">\n";
   echo "        <h2>Search Indices</h2>\n";
   echo "        <p>Use this form to search Refdb's pre-compiled indices.</p>";
   echo "        <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Index results\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   //echo "        <form action=\"kajresult.php\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   echo "	    <p>\n";
   echo "	        <input type=\"text\" name=\"kajquery\"/> in ";
   echo "                <select name=\"kajqueryfield\">\n";
   echo "                    <option value=\"keyword\">keywords</option>\n";
   echo "	            <option value=\"author\">authors</option>\n";
   echo "	            <option value=\"editor\">editors</option>\n";
   echo "	            <option value=\"seditor\">series editors</option>\n";
   echo "	            <option value=\"journalfull\">journal (full)</option>\n";
   echo "	            <option value=\"journalabbrev\">journal (abbrev.)</option>\n";
   echo "	            <option value=\"journalcustabbrev1\">journal (custom abbrev. 1)</option>\n";
   echo "	            <option value=\"journalcustabbrev2\">journal (custom abbrev. 2)</option>\n";
   echo "	        </select>\n";
   echo "	    </p>\n";
   echo "	    <p>\n";
   echo "	        <input type=\"submit\" value=\"Send query\"/>\n";
   echo "	        <input type=\"reset\" value=\"Reset form\"/>\n";
   echo "	    </p>\n";
   echo "        </form>\n";
   echo "    </div>\n";        
   break;
   /*========================================================================

                External databases

                ========================================================================*/
 case('External databases'):
                
   if (function_exists('yaz_connect')) {

   
     function display_record($rec, $xslfile) {
       $xml = new DOMDocument;
       $xml->loadXML($rec);

       $xsl = new DOMDocument;
       $xsl ->load($xslfile);

       // Configure the transformer
       $proc = new XSLTProcessor;
       $proc->registerPHPFunctions();
       $proc->importStyleSheet($xsl); // attach the xsl rules

       echo $proc->transformToXML($xml);
     }

     /*
$processor = xslt_create();
    $parms = array('/_xml' => $rec);
    $res = xslt_process($processor, 'arg:/_xml', $xslfile, NULL, $parms);
    xslt_free($processor);
    $res = preg_replace("'</?html[^>]*>'", '', $res);
    print $res;
} */

     echo "<div id=\"content\">";
     echo "<h2>Search external resources</h2>";
     echo "<p>This search engine uses <a href=\"http://www.indexdata.dk/yaz/\">yaz</a> and <a href=\"http://www.indexdata.dk/phpyaz/\">phpyaz</a> to search selected Z39.50 servers. It is still very rudimentary, but it does allow you to search external sources.</p>";
                    
     // This adds  subtracts slashes from in front of apostrophes as requires by the PHP server's "magic quotes" status 
     function myAddSlashes( $string ) {
       if (get_magic_quotes_gpc()==1) {
	 return ( $string );
       }
       else {
	 return ( addslashes ( $string ) );
       }
     }
     $host="";
     $term="";
     if (isset($_POST['host'])) {
       $host=$_POST['host'];
     }
     if (isset($_POST['term'])) {                    
       $term=$_POST['term'];
     }
     $num_hosts=count($host);
     //The following checks the status of the term input and the number of hosts open. If either is null, then it displays the search field.

     echo " <form method=\"POST\">\n";
     echo "  <h2>Search</h2>\n";
     echo "  <p><input type=\"text\" size=\"30\" name=\"term\"/";
     if ($term) {
       echo " value=\"$term\"";
     }
     echo "> <input type=\"submit\" name=\"action\" value=\"Search\"/></p>\n";
     echo "  <p>Supported CCL fields: ti (title), au (author), ab (abstract), date, isbn and issn. You can combine fields using operators <code>and</code> and <code>or</code>: e.g. <code>ti=submarine and au=parrish thomas</code>.</p>";
     echo " <p><strong>Databases:</strong> <input type=\"checkbox\" checked=\"1\" name=\"host[]\" value=\"melvyl.cdlib.org/CDL90\"/>\n";
     echo "  MELVYL (University of California) \n";
     echo " <input type=\"checkbox\" checked=\"1\" echo\"  name=\"host[]\" value=\"z3950.loc.gov:7090/voyager\"/>\n";
     echo "  Library of Congress</p>&nbsp;";
     if (!empty($term)&&count($host)!=0) {
       //Define each property of bibl1 (todo: add year)
       $bib1["term"]="u=1016 s=pw t=l,r";
       $bib1["ti"]="u=4 s=pw t=l,r";
       $bib1["au"]="u=1003";
       $bib1["ab"]="u=62 s=pw t=l,r";
       $bib1["isbn"]="u=7 s=pw";
       $bib1["issn"]="u=8 s=pw";
       $bib1["date"]="u=30 r=o";
       // Repeat search terms back to user; htmlspecialchars ensures that things like & in input are rendered &amp;.
       // See http://ca3.php.net/htmlspecialchars
       echo "<hr/>";
       echo "<h2>Results</h2>";
       echo '<p>You searched for <strong>' . htmlspecialchars($term) . '</strong> <button type=\"submit\" name=\"thisPage\" value=\"External databases\"/>Clear results</button></p>';
       //Assigns ids to hosts: 1) begin with i=0, as long as i < that the num_hosts (defined above) keep adding 1 
       for ($i=0; $i < $num_hosts; $i++) {
	 //for each host assign an index id
	 $id[]=yaz_connect($host[$i]);
	 // Mapping CCL terms to RPN as defined above (bib1) for each search 
	 yaz_ccl_conf($id[$i], $bib1);
	 // Parse input against yaz_ccl_conf; if error report message; defines cclresult as output of parsing
	 if (!yaz_ccl_parse($id[$i], $term, &$cclresult)) {
	   echo '<p>Error: ' . $cclresult["errorstring"] . '</p><p><a href=\"index.php?thisPage=External databases\">Clear results</a></p>';
	   continue;
	 }
	 //Specify z39.50 preferred syntax for retrieval from the server 
	 yaz_syntax($id[$i],"usmarc");
	 //Prepare search (excuted by yaz_wait). Attributes are (resource id, string type [must be "rpn", string query). 
	 // cclresult is produced by yaz_ccl_parse above.
	 yaz_search($id[$i],"rpn",$cclresult["rpn"]);
	 // Specify number of records to be retrieved. (Should be called befiore yaz_search: http://www.php.net/manual/en/function.yaz-range.php). This is replaced below.
	 yaz_range($id[$i], 0, 0);
       }
       //Allows searches to be executed: returns when server completes or aborts.
       yaz_wait();
       //run through each host for counts
       for ($i=0; $i < $num_hosts; $i++) {
	 $count=yaz_hits($id[$i]);
	 //sets yaz_range in response to number of hits
	 if ($count >=4) {
	   $count=4;
	   yaz_range($id[$i], 1, $count);
	   //prepares for retrieval of number of records specified in yaz_range above
	   yaz_present($id[$i]);
	 }
	 //Allows searches to be executed: returns when server completes or aborts.
	 yaz_wait();
	 for ($i=0;  $i <$num_hosts; $i++) {
	   //add line, indicate the host
	   echo '<hr/>' . $host[$i] . ":";
	   //define error variable
	   $error=yaz_error($id[$i]);
	   //if there is an error, report it.
	   if (!empty($error)) {
	     echo "<p>Error: $error (<a href=\"index.php?thisPage=External databases\">Clear results</a>)</p>";
	   } 
	   //Otherwise report the number of hits
	   else {
	     $hits=yaz_hits($id[$i]);
	     echo "<p>Result Count $hits (<a href=\"index.php?thisPage=External databases\">Clear results</a>)</p>";
	   }
                                    
                                    
	   // Now present the output
	   echo '<ul>';
	   //Restrict following to 20 records
	   for ($p=1; $p <=20; $p++) {
	     // present record of idx in position p, in format "string"; convert marc-8 to utf-8
	     $rec=yaz_record($id[$i],$p,"xml; charset=marc-8,utf-8");
                                        
                                        
                                        
	     //if the record is empty go on to the next host?
	     if (empty($rec)) continue;
	     //Print the position number
	     echo "<p><strong>$p</strong>";
                                        
	     $xslfile="xsl/MARC21slim2English.xsl";
                                        
	     display_record($rec, $xslfile);
	     /* //Go through each record looking for \n and replacing it with html:br element
                                        echo ereg_replace("\n", "<br/>\n",$rec); */
	     echo "</p>";
	   }
	   echo '</ul>';
	 }
       }
     }
   }                            else {echo "<div id=\"content\">";
   echo "    <h2>Not available</h2>";
   echo "    <p>This feature requires the installation of <a href=\"http://www.indexdata.dk/yaz/\">yaz</a> and <a href=\"http://www.indexdata.dk/phpyaz/\">phpyaz</a>. Please install (or ask your system adminitrator to install) this software.</p>";
   echo "</div>";
   // include_once('php/externalsearchengine.inc.php');
   }
   echo "</div>";                
                
   break;
   /*========================================================================

                Search

                ========================================================================*/
   //                case('Search'):
 default :
   // include_once('php/searchform.inc.php');
   $_SESSION['limit'] = $_SESSION['reference_limit'];
   $_SESSION['offset'] = 0;
   $_SESSION['repeat'] = 0;
   $_SESSION['totalhits'] = 0;
   unset($_SESSION['terms']);
   echo "    <div id=\"content\">\n";
   echo "        <form action=\"" . $_SERVER['PHP_SELF'] . "?thisPage=Search results\" method=\"POST\" enctype=\"multipart/form-data\">\n";
   echo "            <div class=\"searchform\">\n";
   echo "                <h2><a id=\"simple\" name=\"simple\">Simple search</a></h2>\n";
   echo "                <p>This form performs a simple search for a string in all fields</p>\n";
   echo "                <strong>Find this</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery\"/><br/>\n";  
   echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "            </div>\n";
   echo "            <div class=\"searchform\">\n";
   echo "                <h2><a id=\"findid\" name=\"findid\">Search by unique identifier</a></h2>\n";
   echo "                <p>Use this form to retrieve a particular dataset with a known unique identifier, either the citation key <strong>or</strong> the Digital Objects Identifier (DOI).</p>\n";
   echo "                <strong>Citation key</strong>: <input class=\"searchText\" type=\"text\" name=\"citationkey\"/> ";  
   echo "                <strong>DOI</strong>: <input class=\"searchText\" type=\"text\" name=\"doi\"/><br/>\n";  
   echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "            </div>\n";
   echo "            <div class=\"searchform\">";
   echo "                <h2><a id=\"simplefield\" name=\"simplefield\">Simple field-based search</a></h2>\n";
   echo "                <p>This form allows you to search the most common fields. Enter as many or as few search terms as you wish. The search is case-insensitive. Multiple fields are combined using \"AND\" (i.e. filling in <strong>author</strong> and <strong>publication year</strong> will result in a search for <em>author <strong>AND</strong> publication year</em>."; 
   echo "                        You can also use the <a href=\"#advanced\">Advanced query</a> <!-- or the <a href=\"#commandline\">command-line interface</a>--> below.</p>\n";
   echo "                <p>\n";
   echo "                    <strong>Author/Editor/Translator</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery1\"/><br/>\n";  
   echo "                    <strong>Publication Year</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery2\"/><br/>\n";
   echo "                    <strong>Book/Chapter/Article Title</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery3\"/><br/>\n";
   echo "                    <strong>Journal Name or Abbreviation</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery4\"/><br/>\n";
   echo "                    <strong>Volume</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery5\"/> ";
   echo "                    <strong>Issue</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery6\"/> ";
   echo "                    <strong>Start page</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery7\"/><br/>\n";
   echo "                    <strong>Subject</strong>: <input class=\"searchText\" type=\"text\" name=\"simplequery8\"/><br/>\n";
   echo "               </p>\n";
   echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "           </div>\n";
   echo "            <div class=\"searchform\">";
   echo "           <h2><a id=\"advanced\" name=\"advanced\">Advanced query</a></h2>\n";
   echo "           <p>This form allows you to search any available field. The search is case-insensitive.";
   echo "                  You can also use the <a href=\"#simple\">simple search</a> above<!-- or the"; 
   echo "                    <a href=\"#commandline\">command-line interface</a> below-->.</p>\n";
   echo "           <p>\n";
   echo "                <select name=\"advancedquery1field\">\n";
   echo "                    <option value=\"anyauthor\" selected=\"selected\">Author/Editor (all)</option>\n";
   echo "                    <option value=\"anytitle\">Title (article/chapter/book/series)</option>\n";
   echo "                    <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                    <option value=\"\">---</option>\n";
   echo "                    <option value=\"author\">Author</option>\n";
   echo "                    <option value=\"editor\">Editor</option>\n";
   echo "                    <option value=\"seditor\">Series editor</option>\n";
   echo "                    <option value=\"title\">Article title</option>\n";
   echo "                    <option value=\"booktitle\">Book title</option>\n";
   echo "                    <option value=\"seriestitle\">Series title</option>\n";
   echo "                    <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                    <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                    <option value=\"publicationyear\">Publication year (EQUALS only)</option>\n";
   echo "                    <option value=\"keyword\">Keyword</option>\n";
   echo "                </select>\n";
   echo "                <select name=\"advancedquery1equals\">\n";
   echo "                    <option value=\"exact\">EQUALS</option>\n";
   echo "                    <option value=\"contains\" selected=\"selected\">INCLUDES</option>\n";
   echo "                    <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                    <option value=\"ends\">ENDS WITH</option>\n";
   echo "                    <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                </select>\n";
   echo "                <input class=\"searchText\" type=\"text\" name=\"advancedquery1\"/>\n"; 
   echo "                <select name=\"advancedquery1op\">\n";
   echo "                    <option value=\"and\" selected=\"selected\">AND</option>\n";
   echo "                    <option value=\"or\">OR</option>\n";
   echo "                    <option value=\"not\">AND NOT</option>\n";
   echo "                 </select>\n";
   echo "            </p>\n";
   echo "            <p>\n";
   echo "                <select name=\"advancedquery2field\">\n";
   echo "                    <option value=\"anyauthor\">Author/Editor (all)</option>\n";
   echo "                    <option value=\"anytitle\">Title (article/chapter/book/series)</option>\n";
   echo "                    <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                    <option value=\"\">---</option>\n";
   echo "                    <option value=\"author\">Author</option>\n";
   echo "                    <option value=\"editor\">Editor</option>\n";
   echo "                    <option value=\"seditor\">Series editor</option>\n";
   echo "                    <option value=\"title\">Article title</option>\n";
   echo "                    <option value=\"booktitle\">Book title</option>\n";
   echo "                    <option value=\"seriestitle\">Series title</option>\n";
   echo "                    <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                    <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                    <option value=\"publicationyear\" selected=\"selected\">Publication year (EQUALS only)</option>\n";
   echo "                    <option value=\"keyword\">Keyword</option>\n";
   echo "                </select>\n"; 
   echo "                <select name=\"advancedquery2equals\">\n";
   echo "                    <option value=\"exact\" selected=\"selected\">EQUALS</option>\n";
   echo "                    <option value=\"contains\">INCLUDES</option>\n";
   echo "                    <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                    <option value=\"ends\">ENDS WITH</option>\n";
   echo "                    <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                </select>\n";
   echo "                <input class=\"searchText\" type=\"text\" name=\"advancedquery2\"/>\n";
   echo "                <select name=\"advancedquery2op\">\n";
   echo "                    <option value=\"and\" selected=\"selected\">AND</option>\n";
   echo "                    <option value=\"or\">OR</option>\n";
   echo "                    <option value=\"not\">AND NOT</option>\n";
   echo "                 </select>\n";
   echo "              </p>\n";
   echo "              <p>\n";
   echo "                 <select name=\"advancedquery3field\">\n";
   echo "                     <option value=\"anyauthor\">Author/Editor (all)</option>\n";
   echo "                     <option value=\"anytitle\" selected=\"selected\">Title (article/chapter/book/series)</option>\n";
   echo "                     <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                     <option value=\"\">---</option>\n";
   echo "                     <option value=\"author\">Author</option>\n";
   echo "                     <option value=\"editor\">Editor</option>\n";
   echo "                     <option value=\"seditor\">Series editor</option>\n";
   echo "                     <option value=\"title\">Article title</option>\n";
   echo "                     <option value=\"booktitle\">Book title</option>\n";
   echo "                     <option value=\"seriestitle\">Series title</option>\n";
   echo "                     <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                     <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                     <option value=\"publicationyear\">Publication year (EQUALS only)</option>\n";
   echo "                     <option value=\"keyword\">Keyword</option>\n";
   echo "                 </select>\n";
   echo "                 <select name=\"advancedquery3equals\">\n";
   echo "                    <option value=\"exact\">EQUALS</option>\n";
   echo "                     <option value=\"contains\" selected=\"selected\">INCLUDES</option>\n";
   echo "                     <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                     <option value=\"ends\">ENDS WITH</option>\n";
   echo "                     <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                 </select>\n";
   echo "                 <input class=\"searchText\" type=\"text\" name=\"advancedquery3\"/>\n";
   echo "                 <select name=\"advancedquery3op\">\n";
   echo "                     <option value=\"and\">AND</option>\n";
   echo "                     <option value=\"or\">OR</option>\n";
   echo "                     <option value=\"not\">AND NOT</option>\n";
   echo "                 </select>\n";
   echo "              </p>\n";
   echo "              <p>\n";
   echo "                 <select name=\"advancedquery4field\">\n";
   echo "                     <option value=\"anyauthor\">Author/Editor (all)</option>\n";
   echo "                     <option value=\"anytitle\">Title (article/chapter/book/series)</option>\n";
   echo "                     <option value=\"anyjournal\">Journal (short/long)</option>\n";
   echo "                     <option value=\"\">---</option>\n";
   echo "                     <option value=\"author\">Author</option>\n";
   echo "                     <option value=\"editor\">Editor</option>\n";
   echo "                     <option value=\"seditor\">Series editor</option>\n";
   echo "                     <option value=\"title\">Article title</option>\n";
   echo "                     <option value=\"booktitle\">Book title</option>\n";
   echo "                     <option value=\"seriestitle\">Series title</option>\n";
   echo "                     <option value=\"journaltitle\">Journal title (full)</option>\n";
   echo "                     <option value=\"shortjournaltitle\">Journal title (short)</option>\n";
   echo "                     <option value=\"publicationyear\">Publication year (EQUALS only)</option>\n";
   echo "                     <option value=\"keyword\" selected=\"selected\">Keyword</option>\n";
   echo "                 </select>\n";
   echo "                 <select name=\"advancedquery4equals\">\n";
   echo "                    <option value=\"exact\">EQUALS</option>\n";
   echo "                     <option value=\"contains\" selected=\"selected\">INCLUDES</option>\n";
   echo "                     <option value=\"begins\">BEGINS WITH</option>\n";
   echo "                     <option value=\"ends\">ENDS WITH</option>\n";
   echo "                     <option value=\"regex\">REGULAR EXPRESSION</option>\n";
   echo "                 </select>\n";
   echo "                 <input class=\"searchText\" type=\"text\" name=\"advancedquery4\"/>.";
   echo "              </p>\n";
   echo "              <p><input type=\"submit\" name=\"sendQuery\" value=\"Search\"/></p>\n";
   echo "           </div>\n";
   /*                 This has been echoed out because I can't get it to work
                    echo "            <div class=\"searchform\">";
                    echo "<!--           <h2><a name=\"commandline\" id=\"commandline\">Command line query</a></h2>\n";
                    echo "               <p>This form allows you to use RefDB command line syntax directly. ";
                    echo "                   You can also use the <a href=\"#simple\">simple search</a> or <a href=\"#form\">advance query</a> forms above.</p>\n";
                    echo "               <p>Query string: <input type=\"text\" name=\"commandlinequery\" size=\"40\" maxlength=\"2048\"/></p>\n";
                    echo "               <p><input type=\"submit\" name=\"sendQuery\" value=\"Submit command line query\"/></p> -->\n";
                    echo " </div>";
   */
   echo "        </form>\n";
   echo "    </div>\n";
   break;
}

// footer
echo "        <div id=\"footer\">\n";
echo "            <p>Reference manager and bibliography tool. Version $version</p>\n";
echo "        </div>\n";
 
// close out the html
echo "    </body>\n";
echo "</html>\n";
?>