-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmuscatConversion.php
More file actions
executable file
·3328 lines (2813 loc) · 124 KB
/
Copy pathmuscatConversion.php
File metadata and controls
executable file
·3328 lines (2813 loc) · 124 KB
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
<?php
# Class to manage Muscat data conversion
class muscatConversion extends frontControllerApplication
{
# Define the types, describing each representation of the data as it passes through each conversion stage
private $types = array (
'muscatview' => array ( // Sharded records
'label' => 'Muscat editing view',
'icon' => 'page_white',
'title' => 'The data as it would be seen if editing in Muscat',
'errorHtml' => "The 'muscatview' version of record <em>%s</em> could not be retrieved, which indicates a database error. Please contact the Webmaster.",
'fields' => array ('recordId', 'field', 'value'),
'idField' => 'recordId',
'orderBy' => 'recordId, line',
'class' => 'regulated',
'public' => false,
),
'rawdata' => array ( // Sharded records
'label' => 'Raw data',
'icon' => 'page_white_text',
'title' => 'The raw data as exported by Muscat',
'errorHtml' => "There is no such record <em>%s</em>. Please try searching again.",
'fields' => array ('recordId', 'field', 'value'),
'idField' => 'recordId',
'orderBy' => 'recordId, line',
'class' => 'compressed', // 'regulated'
'public' => false,
),
'processed' => array ( // Sharded records
'label' => 'Processed version',
'icon' => 'page',
'title' => 'The data as exported by Muscat',
'errorHtml' => "The 'processed' version of record <em>%s</em> could not be retrieved, which indicates a database error. Please contact the Webmaster.",
'fields' => array ('recordId', 'field', 'xPath', 'value'),
'idField' => 'recordId',
'orderBy' => 'recordId, line',
'class' => 'compressed',
'public' => false,
),
'xml' => array (
'label' => 'Muscat as XML',
'icon' => 'page_white_code',
'title' => 'Representation of the Muscat data as XML, via the defined Schema',
'errorHtml' => "The XML representation of the Muscat record <em>%s</em> could not be retrieved, which indicates a database error. Please contact the Webmaster.",
'fields' => array ('id', 'xml'),
'idField' => 'id',
'orderBy' => 'id',
'class' => false,
'public' => false,
),
'marc' => array (
'label' => 'MARC record', // Gets overwritten in public UI
'icon' => 'page_white_code_red',
'title' => "The publication's record as raw MARC21 data",
'errorHtml' => "The MARC21 representation of the Muscat record <em>%s</em> could not be retrieved, which indicates a database error. Please contact the Webmaster.",
'fields' => array ('id', 'mergeType', 'mergeVoyagerId', 'marc', 'bibcheckErrors'),
'idField' => 'id',
'orderBy' => 'id',
'class' => false,
'public' => true,
),
'presented' => array (
'label' => 'Presented', // Gets overwritten in public UI
'icon' => 'page_white_star',
'title' => 'Listing of the publication as an easy-to-read record',
'errorHtml' => "The presented version of the Muscat record <em>%s</em> could not be retrieved, which indicates a database error. Please contact the Webmaster.",
'fields' => array ('id', 'mergeType', 'mergeVoyagerId', 'marc', 'bibcheckErrors'),
'idField' => 'id',
'orderBy' => 'id',
'class' => false,
'public' => true,
),
);
# Function to assign defaults additional to the general application defaults
public function defaults ()
{
# Specify available arguments as defaults or as NULL (to represent a required argument)
$defaults = array (
'applicationName' => 'Muscat conversion project',
'administrators' => true,
'hostname' => 'localhost',
'database' => 'muscatconversion', // Requires SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, INDEX
'username' => NULL,
'password' => NULL,
'table' => false, // Not used
'debugMode' => false,
'paginationRecordsPerPageDefault' => 50,
'div' => strtolower (__CLASS__),
'useFeedback' => false,
'importLog' => '%applicationRoot/exports-tmp/importlog.txt',
'mergingEnabled' => false,
'tabUlClass' => 'tabsflat',
);
# Return the defaults
return $defaults;
}
# Function to assign supported actions
public function actions ()
{
# Define available tasks
$actions = array (
'home' => array (
'description' => false,
'url' => '',
'tab' => ($this->userIsAdministrator ? '<img src="/images/icons/house.png" alt="Home" border="0" />' : 'Search the catalogue'),
'icon' => ($this->userIsAdministrator ? NULL : 'magnifier'),
),
'reports' => array (
'description' => false,
'url' => 'reports/',
'tab' => 'Reports',
'icon' => 'asterisk_orange',
'administrator' => true,
),
'reportdownload' => array (
'description' => 'Export',
'url' => 'reports/',
'export' => true,
'administrator' => true,
),
'tests' => array (
'description' => false,
'url' => 'tests/',
'tab' => 'Tests',
'icon' => 'bug',
'administrator' => true,
),
'records' => array (
'description' => 'Browse records',
'url' => 'records/',
'tab' => ($this->userIsAdministrator ? 'Records' : 'Browse records'),
'icon' => 'application_double',
),
'record' => array (
'description' => 'View a record',
'url' => 'records/%id/',
'usetab' => ($this->userIsAdministrator ? 'records' : 'home' /* i.e. search */),
),
'marcxml' => array (
'description' => 'Export a record as MARCXML',
'url' => 'records/%id/muscat%id.marcxml.xml',
'export' => true,
),
'fields' => array (
'description' => false,
'url' => 'fields/',
'tab' => 'Fields',
'icon' => 'chart_organisation',
'administrator' => true,
),
'search' => array (
'description' => 'Search the catalogue',
'url' => 'search/',
'tab' => ($this->userIsAdministrator ? 'Search' : NULL),
'icon' => 'magnifier',
'usetab' => ($this->userIsAdministrator ? false : 'home'),
),
'postmigration' => array (
'description' => 'Post-migration tasks',
'url' => 'postmigration/',
'tab' => 'Post-migration',
'icon' => 'script',
'administrator' => true,
),
'import' => array (
'description' => 'Import',
'url' => 'import/',
'tab' => 'Import',
'icon' => 'database_refresh',
'administrator' => true,
),
'schema' => array (
'description' => 'Schema',
'subtab' => 'Schema',
'icon' => 'tag',
'parent' => 'admin',
'allowDuringImport' => true,
'administrator' => true,
),
'marcparser' => array (
'description' => 'MARC21 parser definition',
'subtab' => 'MARC21 parser definition',
'url' => 'marcparser.html',
'icon' => 'chart_line',
'parent' => 'admin',
'allowDuringImport' => true,
'administrator' => true,
),
'transliterator' => array (
'description' => 'Reverse-transliteration definition',
'subtab' => 'Reverse-transliteration definition',
'url' => 'transliterator.html',
'icon' => 'arrow_refresh',
'parent' => 'admin',
'allowDuringImport' => true,
'administrator' => true,
),
'merge' => array (
'description' => 'Merge definition',
'subtab' => 'Merge definition',
'url' => 'merge.html',
'icon' => 'arrow_merge',
'parent' => 'admin',
'allowDuringImport' => true,
'administrator' => true,
),
'loc' => array (
'description' => 'LoC names',
'subtab' => 'LoC names',
'url' => 'loc.html',
'icon' => 'cd',
'parent' => 'admin',
'administrator' => true,
),
'othernames' => array (
'description' => 'Other names data',
'subtab' => 'Other names data',
'url' => 'othernames.html',
'icon' => 'cd',
'parent' => 'admin',
'administrator' => true,
),
'selection' => array (
'description' => 'List for selected import',
'subtab' => 'Selected import',
'url' => 'selection.html',
'icon' => 'database_refresh',
'parent' => 'admin',
'allowDuringImport' => true,
'administrator' => true,
),
'udc' => array (
'description' => 'UDC codes and keywords',
'subtab' => 'UDC',
'url' => 'udc/',
'icon' => 'application_view_list',
'parent' => 'admin',
'allowDuringImport' => true,
'administrator' => true,
),
'export' => array (
'description' => 'Export MARC21 output',
'tab' => 'Export',
'url' => 'export/',
'icon' => 'database_go',
'allowDuringImport' => true,
'administrator' => true,
),
'data' => array (
'description' => 'AJAX endpoint',
'url' => 'data.json',
'export' => true,
'allowDuringImport' => true,
),
);
# Return the actions
return $actions;
}
# Database structure definition
public function databaseStructure ()
{
return "
CREATE TABLE IF NOT EXISTS `administrators` (
`username` varchar(191) NOT NULL COMMENT 'Username' PRIMARY KEY,
`active` enum('','Yes','No') NOT NULL DEFAULT 'Yes' COMMENT 'Currently active?',
`privilege` enum('Administrator','Restricted administrator') NOT NULL DEFAULT 'Administrator' COMMENT 'Administrator level'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='System administrators';
CREATE TABLE IF NOT EXISTS `marcparserdefinition` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Automatic key' PRIMARY KEY,
`definition` text NOT NULL COMMENT 'Parser definition',
`savedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Automatic timestamp'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='MARC parser definition';
CREATE TABLE IF NOT EXISTS `reversetransliterationdefinition` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Automatic key' PRIMARY KEY,
`definition` text NOT NULL COMMENT 'Parser definition',
`savedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Automatic timestamp'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='MARC parser definition';
CREATE TABLE `selectiondefinition` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Automatic key' PRIMARY KEY,
`tests` int(1) NOT NULL DEFAULT '1' COMMENT 'Include records used by the test system?',
`definition` mediumtext NOT NULL COMMENT 'Parser definition',
`createdBy` varchar(255) NOT NULL COMMENT 'Created by user',
`savedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'Automatic timestamp'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='MARC parser definition';
";
}
# Additional processing, pre-actions
public function mainPreActions ()
{
# Set title for public access for general users
if (!$this->userIsAdministrator) {
$this->settings['applicationName'] = 'SPRI library catalogue';
}
# Ensure any code errors are not visible to general users
if (!$this->userIsAdministrator) {
ini_set ('display_errors', false);
}
# Enable feedback page for search users
if (!$this->userIsAdministrator) {
$this->settings['useFeedback'] = true;
}
# Force tests virtual page to the tests tab
if ($this->action == 'reports') {
if ($this->item == 'tests') {
$this->tabForced = 'tests';
}
}
}
# Additional processing
public function main ()
{
# Add other settings
$this->exportsDirectory = $this->applicationRoot . '/exports/';
$this->exportsProcessingTmp = $this->applicationRoot . '/exports-tmp/';
# Determine the import lockfile location
$this->lockfile = $this->exportsProcessingTmp . 'lockfile.txt';
# Determine the errors logfile location, used for logging import errors
$this->errorsFile = $_SERVER['DOCUMENT_ROOT'] . $this->baseUrl . '/errors.html';
# Determine if the user for search purposes is internal, so that unsuppressed data can be shown
$hostname = gethostbyaddr ($_SERVER['REMOTE_ADDR']);
$this->searchUserIsInternal = ($this->userIsAdministrator || preg_match ('/cam\.ac\.uk$/', $hostname));
# Show if an import is running, and prevent a second import running
if ($this->userIsAdministrator) { // Do not show the warning to public search users or issue e-mails
if ($importHtml = $this->importInProgress (24, $blockUi = false)) {
if (!isSet ($this->actions[$this->action]['export'])) { // Show the warning unless using AJAX data
$html = $importHtml;
if ($this->action == 'import') {
$html .= $this->importLogHtml ('Import progress');
}
echo $html;
}
if ($this->action == 'import') {
return false;
}
}
}
# Determine and show the export date
$isExportType = (isSet ($this->actions[$this->action]['export']) && $this->actions[$this->action]['export']);
if (!$isExportType) {
$this->exportDateDescription = $this->getExportDate ();
if ($this->userIsAdministrator) {
echo "\n<p id=\"exportdate\">{$this->exportDateDescription}</p>";
}
}
# Define unicode symbols
$this->doubleDagger = chr(0xe2).chr(0x80).chr(0xa1);
# Create a handle to the transliteration module
$this->transliteration = new transliteration ($this);
# Create a handle to the MARC conversion module
$this->marcConversion = new marcConversion ($this, $this->transliteration);
# Create a handle to the reports module
$this->reports = new reports ($this, $this->marcConversion);
$this->reportsList = $this->reports->getReportsList ();
$this->listingsList = $this->reports->getListingsList ();
# Determine which reports are informational reports
$this->reportStatuses = $this->getReportStatuses ();
# Merge the listings array into the main reports list
$this->reportsList += $this->listingsList;
# Load the import system
$this->import = new import ($this, $this->marcConversion, $this->transliteration, $this->reports, $this->exportsProcessingTmp, $this->errorsFile);
# Show note for public access
if (!$this->userIsAdministrator) {
echo "\n<div class=\"graybox\">
<p class=\"warning\"><strong>Please note: You are viewing the legacy database of the Scott Polar Research Institute Library catalogue. It is no longer being updated, so does not reliably reflect our current library holdings.</strong></p>
<p class=\"warning\"><strong>Please <a href=\"https://idiscover.lib.cam.ac.uk/primo-explore/search?vid=44CAM_PROD&lang=en_US&tab=cam_lib_coll&search_scope=SCOP_SCO&sortby=rank\">search for material in iDiscover</a> for up-to-date information about the library collection.</strong></p>
</div>
<br />
";
}
}
# Function to get the export date
private function getExportDate ()
{
return $this->databaseConnection->getTableComment ($this->settings['database'], 'catalogue_rawdata');
}
# Function to determine the status of each report
private function getReportStatuses ()
{
# Start a list of informational reports
$reportStatuses = array ();
# Start a registry of listings-type reports that implement a count
$this->countableListings = array ();
# Loop through each report and each listing, detecting the status, and rewriting the name
$this->reportsList = $this->parseReportNames ($this->reportsList , $reportStatuses, $this->countableListings);
$this->listingsList = $this->parseReportNames ($this->listingsList, $reportStatuses, $this->countableListings);
# Return the status list
return $reportStatuses;
}
# Helper function to strip any flag from report key names
private function parseReportNames ($reportsRaw, &$reportStatuses, &$countableListings)
{
# Loop through each report, detecting whether each report is informational, and rewriting the name
$reports = array (); // Array of report key names without flag appended
foreach ($reportsRaw as $key => $value) {
if (preg_match ('/^(.+)_(info|postmigration|problem|problemok)(|_countable)$/', $key, $matches)) {
$key = $matches[1];
$reportStatuses[$key] = $matches[2];
$reports[$key] = $value; // Register under new name
if ($matches[3]) {
$countableListings[] = $key;
}
} else {
$reportStatuses[$key] = NULL; // Unknown status
}
$reports[$key] = $value; // Recreated list, with any _info stripped
}
# Return the rewritten list
return $reports;
}
# Home page
public function home ()
{
# If a public user, mutate to show the search page instead
if (!$this->userIsAdministrator) {
$this->search ();
return;
}
# Welcome
$html = "\n<h2>Welcome</h2>";
$html .= $this->reportsJumplist ();
$html .= "\n<p>This administrative system enables Library staff at SPRI to get an overview of problems with Muscat records so that they can be prepared for eventual export to Voyager.</p>";
# Reports
$html .= "\n<p class=\"right\">Or filter to: <a href=\"{$this->baseUrl}/postmigration/\">post-migration only</a></p>";
$html .= "\n<h3>Reports available</h3>";
$html .= $this->reportsTable ();
# Statistics
$html .= "\n<h3>Record summary</h3>";
$html .= $this->statisticsTable ();
# Show the HTML
echo $html;
}
# Function to list the reports
public function reports ($id = false)
{
# Start the HTML
$html = '';
# If no specified report, create a listing of reports
if (!$id) {
# Compile the HTML
$html .= "\n<h2>Reports</h2>";
$html .= $this->reportsJumplist ();
$html .= "\n<p>This page lists the various reports that check for data errors or provide an informational overview of aspects of the data.</p>";
$html .= $this->reportsTable ();
# Show the HTML and end
echo $html;
return true;
}
# Ensure the report ID is valid
if (!isSet ($this->reportsList[$id])) {
$html .= "\n<h2>Reports</h2>";
$html .= $this->reportsJumplist ($id);
$html .= "\n<p>There is no such report <em>" . htmlspecialchars ($id) . "</em>. Please check the URL and try again.</p>";
echo $html;
return false;
}
# Show the title
$html .= "\n<h2>Report: " . htmlspecialchars (ucfirst ($this->reportsList[$id])) . '</h2>';
$html .= $this->reportsJumplist ($id);
# View the report
$html .= $this->viewResults ($id);
# Show the HTML
echo $html;
}
# Function to create a reports list
private function reportsTable ($filterStatus = false)
{
# Get the list of reports
$reports = $this->getReports ();
# Filter if required
if ($filterStatus) {
foreach ($reports as $report => $description) {
if ($this->reportStatuses[$report] != $filterStatus) {
unset ($reports[$report]);
}
}
}
# Create a key to show report types
$reportTypes = array (
'ok' => 'OK',
'problem' => 'Problems',
'postmigration' => 'Post-migration',
'info' => 'Informational',
);
$types = array ();
foreach ($reportTypes as $type => $label) {
$types[] = "<strong class=\"{$type}\">{$label}</strong>";
}
$keyHtml = "\n<p id=\"reportskey\">Key: " . implode (' ', $types) . '</p>';
# Get the counts
$counts = $this->getCounts ();
# Get the total number of records
$stats = $this->getStats ();
$totalRecords = $stats['totalRecords'];
# Mark problem reports with no errors as OK
foreach ($this->reportStatuses as $key => $status) {
if ($status == 'problem' || $status == 'problemok') {
if (array_key_exists ($key, $counts)) {
if ($counts[$key] == 0 || $status == 'problemok') {
$this->reportStatuses[$key] = 'ok';
}
}
}
}
# Get the post-migration descriptions
$postmigrationDescriptions = $this->reports->postmigrationDescriptions ();
# Convert to an HTML list
$table = array ();
foreach ($reports as $report => $description) {
$key = $report . ($this->reportStatuses[$report] ? ' ' . $this->reportStatuses[$report] : ''); // Add CSS class if status known
$link = $this->reportLink ($report);
$table[$key]['Description'] = "<a href=\"{$link}\">" . ucfirst (htmlspecialchars ($description)) . '</a>';
if ($filterStatus == 'postmigration') {
$table[$key]['Description'] = '<h4>' . $table[$key]['Description'] . '</h4>';
$table[$key]['Description'] .= '<p>' . (isSet ($postmigrationDescriptions[$report]) ? $postmigrationDescriptions[$report] : '<em class="comment">[No description yet]</em>') . '</p>';
}
$table[$key]['Problems?'] = (($this->isListing ($report) && !in_array ($report, $this->countableListings)) ? '<span class="faded right">n/a</span>' : ($counts[$report] ? '<span class="warning right">' . number_format ($counts[$report]) : '<span class="success right">' . 'None') . '</span>');
$percentage = ($counts[$report] ? round (100 * ($counts[$report] / $totalRecords), 2) . '%' : '-');
$table[$key]['%'] = ($this->isListing ($report) ? '<span class="faded right">n/a</span>' : '<span class="comment right">' . ($percentage === '0%' ? '0.01%' : $percentage) . '</span>');
}
# Compile the HTML
$html = $keyHtml;
$html .= application::htmlTable ($table, array (), 'reports lines', $keyAsFirstColumn = false, false, $allowHtml = true, false, false, $addRowKeyClasses = true);
# Return the HTML
return $html;
}
# Function to determine if the specified report is a listing type
public function isListing ($report)
{
return (array_key_exists ($report, $this->listingsList));
}
# Function to get the counts
private function getCounts ()
{
# Get the list of reports
$reports = $this->getReports ();
# Get the counts
$query = "SELECT report, COUNT(*) AS total FROM reportresults GROUP BY report;";
$data = $this->databaseConnection->getPairs ($query);
# Ensure that each report type has a count
$counts = array ();
foreach ($reports as $id => $description) {
$counts[$id] = (isSet ($data[$id]) ? $data[$id] : 0);
}
# Return the counts
return $counts;
}
# Function to create a reports jumplist
private function reportsJumplist ($current = false)
{
# Determine the front reports page link
$frontpage = $this->reportLink ();
# Get the counts
$counts = $this->getCounts ();
# Create the list
$droplist = array ();
$droplist[$frontpage] = '';
foreach ($this->reportsList as $report => $description) {
$link = $this->reportLink ($report);
$description = (mb_strlen ($description) > 50 ? mb_substr ($description, 0, 50) . '...' : $description); // Truncate
$droplist[$link] = ucfirst ($description) . ($this->isListing ($report) ? '' : ' (' . number_format ($counts[$report]) . ')');
}
# Create a link to the selected item
$selected = $this->reportLink ($current);
# Compile the HTML and register a processor
$html = application::htmlJumplist ($droplist, $selected, $this->baseUrl . '/', $name = 'reportsjumplist', $parentTabLevel = 0, $class = 'reportsjumplist', 'Switch to: ');
# Return the HTML
return $html;
}
# Function to link a report
private function reportLink ($report = false)
{
return $this->baseUrl . ($report != 'tests' ? '/reports/' : '/') . ($report ? htmlspecialchars ($report) . '/' : '');
}
# Function to get the list of reports
public function getReports ()
{
# Ensure each report exists
foreach ($this->reportsList as $report => $description) {
$methodName = 'report_' . $report;
if (!method_exists ($this->reports, $methodName)) {
unset ($this->reportsList[$report]);
}
}
# Return the list
return $this->reportsList;
}
# Function to view results of a report
private function viewResults ($id)
{
# Determine the description
$description = 'This report shows ' . $this->reportsList[$id] . '.';
# Start the HTML With the description
$html = "\n<div class=\"graybox\">";
if (!$this->isListing ($id)) {
$html .= "\n<p id=\"exportlink\" class=\"right\"><a href=\"{$this->baseUrl}/reports/{$id}/{$id}.csv\">Export as CSV</a></p>";
}
$html .= "\n<p><strong>" . htmlspecialchars ($description) . '</strong></p>';
$html .= "\n</div>";
# Show the records for this query (having regard to any page number supplied via the URL)
if ($this->isListing ($id)) {
$viewMethod = "report_{$id}_view";
$html .= $this->reports->{$viewMethod} ();
} else {
$baseLink = '/reports/' . $id . '/';
$html .= $this->recordListing ($id, false, array (), $baseLink, true);
}
# Return the HTML
return $html;
}
# Function to list the records as an index of all records
public function records ()
{
# Start the HTML
$html = '';
# Show the search form
$id = $this->recordSearchForm ($html);
# If a valid record has been found, redirect to it
if ($id) {
$url = $_SERVER['_SITE_URL'] . $this->recordLink ($id);
application::sendHeader (301, $url, $html);
echo $html;
return true;
}
# Browsing mode
$html .= "\n<p><br /><br /><strong>Or browse</strong> through the records:</p>";
$resultBrowse = $this->recordBrowser ($html);
# Show the HTML and end
echo $html;
return true;
}
# Function to export a record as MARCXML
public function marcxml ($id)
{
# Run the record page in MARCXML mode
return $this->record ($id, true);
}
# Function to show a record
public function record ($id, $marcXmlMode = false)
{
# Start the HTML
$html = '';
# Do a quick check to ensure the record exists, ending if not
if (!$this->getRecords ($id, 'xml')) {
$errorHtml = "There is no such record <em>{$id}</em>.";
$html .= "\n<p>{$errorHtml}</p>";
echo $html;
application::sendHeader (404);
return false;
}
# Enable jQuery, needed for previous/next keyboard navigation, and tabbing
$html .= "\n\n\n" . '<script type="text/javascript" src="//code.jquery.com/jquery.min.js"></script>';
# Add previous/next links
$previousNextLinks = $this->previousNextLinks ($id);
$html .= "\n<p>Record #<strong>{$id}</strong>:</p>";
$html .= $previousNextLinks;
# Get the data, in order, starting with the most basic version, ending if any fail
$tabs = array ();
$i = 0;
foreach ($this->types as $type => $attributes) {
if (!$this->types[$type]['public'] && !$this->userIsAdministrator) {continue;} // Hide tab if not public but viewing publicly
if (!$tabs[$type] = $this->recordFieldValueTable ($id, $type, $errorHtml)) {
if ($i == 0) { // First one is the master record; if it does not exist, assume this is actually a genuinely non-existent record
$errorHtml = "There is no such record <em>{$id}</em>.";
}
$html .= "\n<p>{$errorHtml}</p>";
application::sendHeader (404);
echo $html;
return false;
}
$i++;
}
# In export mode, export the data as now assembled, and end
if ($marcXmlMode) {
return $this->exportMarcXML ($id, $this->marcRecordDynamic['record']);
}
# In public view, rename the presented record tab label
if (!$this->userIsAdministrator) {
$this->types['presented']['label'] = 'Main publication details';
}
# Compile the labels, whose ordering is used for the tabbing
$labels = array ();
$typesReverseOrder = array_reverse ($this->types, true);
$i = 1;
foreach ($typesReverseOrder as $type => $attributes) {
if (!$this->types[$type]['public'] && !$this->userIsAdministrator) {continue;} // Hide tab if not public but viewing publicly
$labels[$type] = "<span accesskey=\"" . $i++ . "\" title=\"{$attributes['title']}\"><img src=\"/images/icons/{$attributes['icon']}.png\" alt=\"\" border=\"0\" /> " . $attributes['label'] . '</span>';
}
# Load into tabs and render
$jQuery = new jQuery (false, false, false, $jQueryLoaded = true);
$jQuery->tabs ($labels, $tabs);
$html .= $jQuery->getHtml ();
// $html .= application::dumpData ($record, false, true);
# Show the HTML
echo $html;
}
# Function to export MARC as MARCXML
private function exportMarcXML ($id, $marc)
{
# Save the record to a temp file
$mrkFile = "/tmp/muscat{$id}.mrk";
file_put_contents ($mrkFile, $marc);
# Convert to .mrk
$createMarcExport = new createMarcExport ($this, $applicationRoot = NULL, $recordProcessingOrder = NULL);
$createMarcExport->reformatMarcToVoyagerStyle ($mrkFile);
# Convert to MARCXML
$marcEditPath = '/usr/local/bin/marcedit/cmarcedit.exe';
$mrcFile = "/tmp/muscat{$id}.mrc";
$marcXmlFile = "/tmp/muscat{$id}.marcxml.xml";
$command = "mono {$marcEditPath} -s {$mrkFile} -d {$mrcFile} -make && mono {$marcEditPath} -s {$mrcFile} -d {$marcXmlFile} -marcxml";
exec ($command, $output, $unixReturnValue);
if ($unixReturnValue == 2) {
echo "<p class=\"warning\">Execution of <tt>/usr/local/bin/marcedit/cmarcedit.exe</tt> failed with Permission denied - ensure the webserver user can read <tt>/usr/local/bin/marcedit/</tt>.</p>";
return false;
}
# Read the MARCXML file
$marcXml = file_get_contents ($marcXmlFile);
# Remove the mrk, mrc, and MARCXML files
unlink ($mrkFile);
unlink ($mrcFile);
unlink ($marcXmlFile);
# Reformat the XML to be easier to read
$dom = new DOMDocument ();
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML ($marcXml);
$marcXml = $dom->saveXML ();
# Send XML headers
header ('Content-type: text/xml; charset=utf8');
# Force download rather than view
$filenameBase = "muscat{$id}.marcxml";
$filenameBase .= '._savedAt' . date ('Ymd-His');
$filename = $filenameBase . '.xml';
header ('Content-disposition: attachment; filename=' . $filename);
# Transmit the XML
echo $marcXml;
}
# Function to create previous/next record links
private function previousNextLinks ($id)
{
# Start the HTML
$html = '';
# Ensure records are public in public access mode
$constraint = '';
if (!$this->searchUserIsInternal) {
$constraint = " AND status IN('migratewithitem','migrate')";
}
# Get the data
$safeRangeOptimisation = 1000; // Optimisation to reduce SQL rows evaluated to this number (as identified using EXPLAIN), despite ID already being indexed
$query = "SELECT
(SELECT MAX(id) AS id FROM searchindex WHERE id < {$id} AND id > ({$id} - {$safeRangeOptimisation}) {$constraint}) AS previous,
(SELECT MIN(id) AS id FROM searchindex WHERE id > {$id} AND id < ({$id} + {$safeRangeOptimisation}) {$constraint}) AS next
;";
$data = $this->databaseConnection->getOne ($query);
# Create a list
$list = array ();
$list[] = ($data['previous'] ? '<a id="previous" href="' . "{$this->baseUrl}/records/{$data['previous']}/" . '"><img src="/images/icons/control_rewind_blue.png" alt="Previous record" border="0" /></a>' : '');
$list[] = '#' . $id;
$list[] = ($data['next'] ? '<a id="next" href="' . "{$this->baseUrl}/records/{$data['next']}/" . '"><img src="/images/icons/control_fastforward_blue.png" alt="Next record" border="0" /></a>' : '');
# Compile the HTML
$html = application::htmlUl ($list, 0, 'previousnextlinks');
# Add keyboard navigation; see: https://stackoverflow.com/questions/12682157/
$html .= '
<script language="javascript" type="text/javascript">
$(function() {
var keymap = {};
keymap[ 37 ] = "#previous"; // Left
keymap[ 39 ] = "#next"; // Right
$( document ).on( "keyup", function(event) {
var href;
var selector = keymap[event.which];
// if the key pressed was in our map, check for the href
if (selector) {
if ($(selector).length) { // If actually present
window.location = $(selector).attr ("href");
}
}
});
});
</script>
';
# Return the HTML
return $html;
}
# Function to create a record field/value table
private function recordFieldValueTable ($id, $type, &$errorHtml = false)
{
# Get the data or end
$linkFields = ($type != 'xml');
if (!$record = $this->getRecords ($id, $type, $convertEntities = true, $linkFields)) {
if (!in_array ($type, array ('marc', 'presented'))) { // MARC and presented formats are both created dynamically, so should not be a fatal error
$errorHtml = sprintf ($this->types[$type]['errorHtml'], $id);
return false;
}
}
# Regenerate MARC data on the fly (for MARC and presented versions), so that changes in code can be immediately viewed
if (in_array ($type, array ('marc', 'presented'))) {
if (!isSet ($this->marcRecordDynamic)) { // Cache for next type that uses it, to save running convertToMarc twice
$data = $this->getRecords ($id, 'xml', false, false, $searchStable = (!$this->userIsAdministrator));
$marcParserDefinition = $this->import->getMarcParserDefinition ();
$mergeDefinition = $this->import->parseMergeDefinition ($this->import->getMergeDefinition ());
$marcRecord = $this->marcConversion->convertToMarc ($marcParserDefinition, $data['xml'], $mergeDefinition, $record['mergeType'], $record['mergeVoyagerId'], $stripLeaderInMerge = false /* Do not strip for dynamic merge; however it is stripped in the actual import */); // Overwrite with dynamic read, maintaining other fields (e.g. merge data)
$this->marcRecordDynamic = array (
'record' => $marcRecord,
'marcErrorHtml' => $this->marcConversion->getErrorHtml (),
'marcPreMerge' => $this->marcConversion->getMarcPreMerge (),
'sourceRegistry' => $this->marcConversion->getSourceRegistry (),
'itemRecords' => $this->marcConversion->getItemRecords (),
'filterTokens' => $this->marcConversion->getFilterTokensString (),
'status' => $this->marcConversion->getStatus (),
);
}
}
# Render the result
switch ($type) {
# Presentation record
case 'presented':
$output = $this->presentedRecord ($this->marcRecordDynamic['record']);
break;
# Text records
case 'marc':
$output = '';
$marcXmlLink = "<a rel=\"nofollow\" href=\"{$this->baseUrl}/records/{$id}/muscat{$id}.marcxml.xml\">MARCXML</a>";
if ($this->userIsAdministrator) {
$output = "\n<p>The MARC output uses the <a target=\"_blank\" href=\"{$this->baseUrl}/marcparser.html\">parser definition</a> to do the mapping from the XML representation.</p>";
if ($record['bibcheckErrors']) {
$output .= "\n<pre>" . "\n<p class=\"warning\">Bibcheck " . (substr_count ($record['bibcheckErrors'], "\n") ? 'errors' : 'error') . ":</p>" . $record['bibcheckErrors'] . "\n</pre>";
}
if ($this->marcRecordDynamic['marcErrorHtml']) {
$output .= $this->marcRecordDynamic['marcErrorHtml'];
}
$output .= "\n<div class=\"graybox marc\">";
$output .= "\n<p id=\"exporttarget\">";
$output .= "Target <a href=\"{$this->baseUrl}/export/\">export</a> group: <strong>" . $this->formatMigrationStatus ($this->marcRecordDynamic['status']) . '</strong> ';
$output .= "Filter tokens: <strong>" . ($this->marcRecordDynamic['filterTokens'] ? htmlspecialchars ($this->marcRecordDynamic['filterTokens']) : '-') . '</strong> ';
$output .= "Item records: <strong>" . ($this->marcRecordDynamic['itemRecords'] ? $this->marcRecordDynamic['itemRecords'] : '-') . '</strong> ';
$output .= $marcXmlLink;
$output .= '</p>';
if ($record['mergeType']) {
$output .= "\n<p>Note: this record has <strong>merge data</strong> (managed according to the <a href=\"{$this->baseUrl}/merge.html\" target=\"_blank\">merge specification</a>), shown underneath.</p>";
}
if ($record['mergeType']) {
$output .= "\n" . '<p class="colourkey">Colour key: <span class="sourcem">Muscat</span> / <span class="sourcev">Voyager</span> / <span class="stripped">Stripped</span></p>';
}
} else {
$output .= "\n<p id=\"exporttarget\">";
$output .= $marcXmlLink;
$output .= '</p>';
}
$output .= "\n<pre>" . $this->showSourceRegistry ($this->highlightSubfields (htmlspecialchars ($this->marcRecordDynamic['record'])), $this->marcRecordDynamic['sourceRegistry']) . "\n</pre>";
if ($this->userIsAdministrator) {
if ($record['mergeType']) {
$output .= "\n<h3>Merge data</h3>";
$mergeTypes = $this->marcConversion->getMergeTypes ();
$output .= "\n<p>Merge type: {$record['mergeType']}" . (isSet ($mergeTypes[$record['mergeType']]) ? " ({$mergeTypes[$record['mergeType']]})" : '') . "\n<br />Voyager ID: #{$record['mergeVoyagerId']}.</p>";
$output .= "\n<h4>Pre-merge record from Muscat:</h4>";
$output .= "\n<pre>" . $this->highlightSubfields (htmlspecialchars ($this->marcRecordDynamic['marcPreMerge'])) . "\n</pre>";
$output .= "\n<h4>Existing Voyager record:</h4>";
$voyagerRecord = $this->marcConversion->getExistingVoyagerRecord ($record['mergeVoyagerId'], $stripLeaderInMerge = false, $voyagerRecordErrorText); // Although it is wasteful to regenerate this, the alternative is messily passing back the record and error text as references through convertToMarc()
$output .= "\n<pre>" . ($voyagerRecord ? $this->highlightSubfields (htmlspecialchars ($voyagerRecord)) : $voyagerRecordErrorText) . "\n</pre>";
}
$output .= "\n</div>";