Repository navigation
Expand file tree
/
Copy patharticleModel.php
More file actions
executable file
·1375 lines (1084 loc) · 44.1 KB
/
Copy patharticleModel.php
File metadata and controls
executable file
·1375 lines (1084 loc) · 44.1 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
#!# *Name fields have become: EventIdentity / PersonIdentity / OrganisationIdentity
# Article model class for the MODES catalogue viewer
class articleModel
{
# Define sections
#!# Ideally this would be done as a field and dependency definition pattern
private $sections = array (
'id',
'moniker',
'type',
'status',
'collections',
'context',
'title',
'briefDescription',
'objectType',
'objectName', // Uses article
'medium',
'category',
'artist',
'classifiedNames', // Uses article
'fieldCollection', // Uses article
'materials', // Uses article
'numberOfItems', // Uses article
'note', // Uses article
'fullDescription', // Uses article
'relatedRecords', // Uses article
'dimensions', // Uses article
'placeName', // Uses article
'associatedPerson', // Uses article
'associatedOrganisation', // Uses article
'associatedExpedition', // Uses article
'images',
'imageFiles', // Filenames - deprecated
'imageBy', // Uses article
'imageColour', // Uses article
'navigationIds',
'navigationIdsAdditional',
);
# Constructor
public function __construct ($modesCatalogueApi, $settings, $databaseConnection)
{
# Convert parameters to class properties
$this->modesCatalogueApi = $modesCatalogueApi; // Handle to calling class
$this->settings = $settings;
$this->databaseConnection = $databaseConnection;
}
# Getter to return the structured data
public function getOne ($id, $collectionId = false, $imageSize = false, $imageShape = false, $includeXml = false)
{
# Get the data for the article; note that BINARY is used to force case sensitivity
$query = "
SELECT *
FROM {$this->settings['database']}.{$this->settings['table']}
WHERE
(Status != 'R' OR Status IS NULL)
AND BINARY id = :id
LIMIT 1
;";
$preparedStatementValues = array ('id' => $id);
# Get the record from the table or end
if (!$record = $this->databaseConnection->getOne ($query, false, true, $preparedStatementValues)) {
return array ('error' => 'There is no such record ID.');
}
# Decorate the record
$record = $this->decorateArticle ($record, $collectionId, $imageSize, $imageShape, array (), $includeXml);
# Return the record
return $record;
}
# Function to get articles data
public function getArticlesData ($baseUrl, $collection = false, $imageSize = false, $imageShape = false, $searchPhrase = false, $category = false, $material = false, $artist = false, $requireImages = false, $random = 0, $requestedPage = 1)
{
# Start a list of constraints
$where = array ();
$preparedStatementValues = array ();
$paginationRecordsPerPage = $this->settings['paginationRecordsPerPage'];
# Determine default ordering
#!# OLD DOCUMENTATION: "ORDER BY " is only needed for the general listings because the Museum/Art records are two sets of serial records. ORDER BY is not needed by default because the MyISAM storage means that the natural order coming out of Modes. Note that this however fails if ONLY id is returned
#!# This algorithm (splitting of _prefix and _suffix) can't solve the problem of records with a / in, i.e. Y: 69/10/1/55 still comes before Y: 69/10/1/6. However, it's a lot better than just sorting by id only. The only real fix is a unified catalogue file rather than two imports.
$orderByClause = ' ORDER BY id_prefix, id_suffix, id';
# Items must not be private
$where[] = "(Status != 'R' OR Status IS NULL)";
# Fix searches within a particular collection to match that collection's ID
#!# Need to rename as $collectionId
if ($collection) {
#!# NB Most of the time, $collection is already validated, so this is wasted CPU
# Get the collections
$collections = $this->modesCatalogueApi->getCollectionsData ($baseUrl);
# Validate the collection ID
if (!isSet ($collections[$collection])) {
return array ('error' => 'There is no such collection.');
}
$preparedStatementValues['collectionWithin'] = "%|{$collections[$collection]['collection']}|%"; // Collections are surrounded by |...|, whether one or more
$where[] = "Collection LIKE BINARY :collectionWithin";
} else {
#!# Not clear what this is for
$where[] = "(Collection != '' OR Collection IS NOT NULL)";
}
# Add limitation for randomisation
if ($random) {
$where[] = "(Status != 'P' OR Status IS NULL)";
$where[] = "`PhotographFilename` != ''";
$orderByClause = ' ORDER BY RAND()';
$paginationRecordsPerPage = $random; // Basically LIMIT
}
# Add limitation for requiring images
if ($requireImages) {
$where[] = "`PhotographFilename` != '' AND `PhotographFilename` IS NOT NULL";
}
# Make the search phrase safe
if ($searchPhrase) {
$searchPhrase = trim ($searchPhrase);
$preparedStatementValues['searchPhrase'] = $searchPhrase;
$preparedStatementValues['searchPhraseLike'] = '%' . $searchPhrase . '%';
$where[] = "(
id = :searchPhrase
OR Title LIKE :searchPhraseLike
OR BriefDescription LIKE :searchPhraseLike
OR Description LIKE :searchPhraseLike /* NB using description within the search slows it down a fair amount */
OR Artist LIKE :searchPhraseLike
OR Category LIKE :searchPhraseLike
OR Material LIKE :searchPhraseLike
)";
}
# Adjust category name
if ($category) {
$preparedStatementValues['category'] = $category;
$preparedStatementValues['categoryWithin'] = "%|{$category}|%";
$where[] = "(Category = :category OR Category LIKE :categoryWithin)";
}
#!# Mismatch between counts: /museum/catalogue/armc/materials/fabric+%3E+cotton/ has 39 items but /museum/catalogue/armc/materials/ says 43
if ($material) {
$preparedStatementValues['material'] = $material;
$preparedStatementValues['materialWithin'] = "%|{$material}|%";
$where[] = "(Material = :material OR Material LIKE :materialWithin)";
}
# Adjust artist name
if ($artist) {
$preparedStatementValues['artist'] = $artist;
$preparedStatementValues['artistWithin'] = "%|{$artist}|%";
$where[] = "(LOWER(Artist) = :artist OR Artist LIKE :artistWithin)";
}
# Define fields which will appear in the eventual output (not all of these exist in the actual data)
$filterToFields = array ('id', 'status', 'images', 'imageFiles', 'title', 'collections', 'briefDescription');
# Determine the fields to use
$fields = '*';
$fields .= ', data'; // #!# Needed for fields marked 'Uses article' as above; ideally this would only be included when required, as it is very large, but this requires a dependency definition system
# Assemble the query
$query = "SELECT
{$fields}
FROM {$this->settings['database']}.{$this->settings['table']}
WHERE " . implode (' AND ', $where)
. $orderByClause
. ';';
# Get the data via pagination
list ($data, $totalAvailable, $totalPages, $page, $actualMatchesReachedMaximum) = $this->databaseConnection->getDataViaPagination ($query, "{$this->settings['database']}.{$this->settings['table']}", true, $preparedStatementValues, array (), $paginationRecordsPerPage, $requestedPage);
# Decorate the data
foreach ($data as $id => $record) {
$data[$id] = $this->decorateArticle ($record, $collection, $imageSize, $imageShape, $filterToFields, false);
}
# Ensure the page is not being exceeded
if ($data) {
if ($requestedPage > $page) {
return array ('error' => 'Invalid page.');
}
}
# Lookup related terms
$relatedTerms = $this->getRelatedTerms ($searchPhrase);
# Assemble the data
$data = array (
'pagination' => array (
'count' => count ($data),
'total' => (int) $totalAvailable,
'page' => $page,
'totalPages' => $totalPages,
),
'relatedTerms' => $relatedTerms,
'articles' => $data,
);
# Return the data
return $data;
}
# Function to get lookups
#!# May be able to refactor further
private function getRelatedTerms ($searchPhrase)
{
# Return empty array if no search term
if (!$searchPhrase) {return array ();}
# Get all the lookups
$query = "SELECT Term,BroaderTerm,NarrowerTerm,SeeAlso,PreferredTerm,UseFor FROM {$this->settings['database']}.lookups;";
if (!$lookupsRaw = $this->databaseConnection->getData ($query, "{$this->settings['database']}.lookups")) {return false;}
foreach ($lookupsRaw as $key => $value) {
#!# Workaround for bug in database.php
unset ($lookupsRaw[$key]['Term']);
}
# Lower-case the keys
foreach ($lookupsRaw as $key => $value) {
$key = strtolower ($key);
$lookups[$key] = $value;
}
# End if none
$searchPhrase = strtolower (trim ($searchPhrase));
if (!isSet ($lookups[$searchPhrase])) {return false;}
# Loop through each element of the lookup
$result = array ();
foreach ($lookups[$searchPhrase] as $key => $item) {
if ($key == 'UseFor') {continue;}
if (!$item = str_replace ("\r\n", "\n", trim ($item))) {
continue;
}
$key = application::unCamelCase ($key);
$result[$key] = explode ("\n", $item);
}
if (!$result) {return false;}
# Return the result
return $result;
}
# Function to decorate an article
private function decorateArticle ($record, $collectionId, $imageSize, $imageShape, $filterToFields = array (), $includeXml = false)
{
# Determine the collections associated with this record
$this->collections = $this->parseCollections ($record['Collection']);
# Ensure the collection matches if a collection is specified
# If an automatic collection lookup is specified, use the first
if ($collectionId == '?') {
if ($this->collections) {
$collectionId = $this->collections[0];
}
}
# Convert the article XML data to an array
$article = xml::xml2array ($record['data'], false, false, false, false);
# Assemble the data
foreach ($this->sections as $section) {
if ($filterToFields) {
if (!in_array ($section, $filterToFields)) {continue;}
}
$function = 'get' . ucfirst ($section); // e.g. getDimensions
$data[$section] = $this->{$function} ($article, $record, $collectionId, $imageSize, $imageShape);
}
# Include the XML if required
if ($includeXml) {
$data['xml'] = $record['data'];
}
# Return the data
return $data;
}
# Function to parse the collection value
private function parseCollections ($string)
{
# Return empty array if none
if (!$string) {return array ();}
# Explode out
preg_match_all ('~\|([^|]+)\|~', $string, $matches); // i.e. |something| or |something||somethingelse| etc.
$collections = $matches[1]; // Array of all matches
# Return the list
return $collections;
}
/* Field implementations */
#!# Some of the lookups here should be replaced with XPath lookups
#!# ReproductionFilename,Reproduction/Filename no longer being used
# Function to obtain the ID
private function getId ($article_ignored, $record)
{
return $record['id'];
}
# Function to get the moniker
private function getMoniker ($article_ignored, $record)
{
return $this->modesCatalogueApi->monikerFromRecordId ($record['id']);
}
# Function to obtain the type
private function getType ($article, $record)
{
return $record['Type'];
}
# Function to obtain the status
private function getStatus ($article, $record)
{
return $record['Status'];
}
# Function to obtain the collections
private function getCollections ($article, $record)
{
#!# Hacky
# Convert each ID to a moniker
$collections = array ();
foreach ($this->collections as $index => $collectionId) {
$collections[$index] = $this->databaseConnection->selectOneField ($this->settings['database'], 'collections', 'id', array ('collection' => $collectionId));
}
return $collections;
}
# Function to obtain the context
#!# Aim to get rid of this field or document it better; currently it is used to check for 'ff' items and show a message
private function getContext ($article, $record)
{
return $record['Context'];
}
# Function to obtain the title
private function getTitle ($article, $record)
{
return ucfirst ($record['Title']);
}
# Function to obtain the brief description
private function getBriefDescription ($article, $record)
{
return $record['BriefDescription'];
}
# Function to obtain the object type
private function getObjectType ($article, $record)
{
# End if a picture
if ($record['Type'] == 'picture') {return NULL;}
# End if none
if (!$record['ObjectType']) {return false;}
# Return the object type
return ucfirst ($record['ObjectType']);
}
# Function to obtain the object name
private function getObjectName ($article, $record)
{
#!# Add support for multiple entries, e.g. /museum/catalogue/article/n747/ should have "Bag" and "nangmaut"
#!# Convert to array output type, and display line-by-line
# End if not present
if (!isSet ($article['Identification']) || !isSet ($article['Identification']['ObjectName']) || !isSet ($article['Identification']['ObjectName']['Keyword'])) {return NULL;}
# Obtain the object name
if (is_array ($article['Identification']['ObjectName']['Keyword']) && isSet ($article['Identification']['ObjectName']['Keyword']['Keyword'])) {
$objectName = $article['Identification']['ObjectName']['Keyword']['Keyword']; // Happens when /Note present, e.g. /article/y2010.52.4/
} else {
$objectName = $article['Identification']['ObjectName']['Keyword'];
}
# Return the object name
return $objectName;
}
# Function to obtain the medium, relevant only to pictures (e.g. 'Sketch', 'Watercolour', etc.)
private function getMedium ($article, $record)
{
# End if not a picture
if ($record['Type'] != 'picture') {return NULL;}
# End if none
if (!$record['ObjectType']) {return false;}
# Return the object type
return ucfirst ($record['ObjectType']);
}
# Function to obtain the category
private function getCategory ($article, $record)
{
# End if no category
if (!$record['Category']) {return NULL;}
return $record['Category'];
}
# Function to obtain the artist
private function getArtist ($article, $record)
{
# End if not an artist
if (!$record['Artist']) {return NULL;}
# Return the artist
return $record['Artist'];
}
# Function to parse classified names
private function getClassifiedNames ($article)
{
# End if no such section of the record
if (!isSet ($article['Identification']['Classification'])) {return false;}
# Normalise to multiple
$article['Identification']['Classification'] = $this->normaliseToMultiple ($article['Identification']['Classification']);
# Get each item
$classifiedNames = array ();
foreach ($article['Identification']['Classification'] as $index => $attributes) {
# Skip if no keyword
if (!isSet ($attributes['Keyword'])) {continue;}
# Assign the key
if (isSet ($attributes['System'])) {
$key = (isSet ($attributes['System']['System']) ? $attributes['System']['System'] : $attributes['System']); // Deal with cases with a note, e.g. /article/n30.2a-b/ and /api/article?id=N%3A+30%2F2a-b&collection=?
} else {
$key = '[Unknown system]';
}
# Assign the value
$value = $attributes['Keyword'];
# Convert values arranged as array(a,b,c) into (str) a > b > c
$value = $this->convertHierarchical ($value, $ucFirst = true); #!# ucfirst To be cleaned
# Add to the master array
$classifiedNames[$key] = $value;
}
# Define optional key name substitutions
$labels = array (
'Cultural affiliation - current' => 'Current cultural affiliation',
'Cultural affiliation - former' => 'Former cultural affiliation',
'Geographic area - current' => 'Current place name',
'Geographic area - former' => 'Former place name',
'Cultural affiliation - subgroup' => 'Cultural subgroup',
'Gender' => 'Gender', #!# Shouldn't be needed as these substitutions are optional
'gender' => 'Gender', #!# To be cleaned
'AAT' => 'Getty AAT', // NB If changing this, it must also be changed in the view/controller, as the autolinker depends on this phrase
);
$record = array ();
foreach ($classifiedNames as $key => $value) {
$label = (isSet ($labels[$key]) ? $labels[$key] : $key);
#!# Problem here is that can't have multiple, so need to append to $value if already exists, then adjust the view if required
$record[$label] = $value;
}
# Return the list
return $record;
}
# Function to parse field collection
#!# Not yet reviewed for potential refactorings
#!# /museum/catalogue/article/n246a-f/ has (person: "", organisation: "")
private function getFieldCollection ($article)
{
# End if no field collection group
if (!isSet ($article['FieldCollection'])) {return false;}
# Determine if the field collections is an associative array of collections or a single collection
#!# Is this still needed?
$fieldCollection = (isSet ($article['FieldCollection'][0]) ? $article['FieldCollection'][0] : $article['FieldCollection']);
# Determine field collection types
$types = array ('Person', 'Organisation', 'Place', 'Date', 'CollectionNumber');
# Create each item
$fields = array ();
foreach ($fieldCollection as $key => $value) {
# Skip if not in the array of field collection types
if (!in_array ($key, $types)) {continue;}
# Uppercase the keyname
$key = ucfirst (strtolower ($key));
# Skip if no value
if (!$value) {continue;}
# Person type
if ($key == 'Person') {
if (!isSet ($value['PersonIdentity'])) {continue;}
$value = $value['PersonIdentity']; // "<a href=\"{$this->baseUrl}/biographies/{$value['REFERENCE-NUMBER']}.html\">{$value['PERSON']}</a>";
}
# Organisation type
if ($key == 'Organisation') {
if (!isSet ($value['OrganisationIdentity'])) {continue;}
$value = $value['OrganisationIdentity']; // "<a href=\"{$this->baseUrl}/expeditions/{$value['REFERENCE-NUMBER']}.html\">{$value['CORPORATE-BODY']}</a>";
}
# Place type
if ($key == 'Place') {
if (!isSet ($value['PlaceName'])) {continue;}
$value = $value['PlaceName']; // "<a href=\"{$this->baseUrl}/biographies/{$value['REFERENCE-NUMBER']}.html\">{$value['PERSON']}</a>";
}
# Date type
if ($key == 'Date') {
# If an array, take only the first
#!# Ideally all would be used, but the NOTE field mapping to multiple DATE fields in MODES is inconsistent
if (is_array ($value)) {
foreach ($value as $subKey => $subValue) {
$value = $subValue;
break;
}
}
# String conversions
$value = str_replace ('=', '-', $value);
$value = str_replace ('.', '/', $value);
if ($value == 'nd') {$value = '[No date]';}
}
# Convert hierarchical values
$value = $this->convertHierarchical ($value);
# Skip if no value
if (!$value) {continue;}
# Add to the list
$fields[$key] = $value;
}
# Return the fields
return $fields;
}
# Function to get materials
private function getMaterials ($article)
{
# End if none
if (!isSet ($article['Description'])) {return array ();}
#!# /museum/catalogue/article/y2014.8a-i/
//application::dumpData ($article['Description']);
if (!isSet ($article['Description']['Material'])) {return array ();}
# If a simple string, convert to the nested structure used in most records
if (is_string ($article['Description']['Material'])) {
$article['Description']['Material'] = array ('Keyword' => $article['Description']['Material']);
}
# Normalise to multiple
$article['Description']['Material'] = $this->normaliseToMultiple ($article['Description']['Material']);
/* # We now have a structure like the following, with one or more materials, where the keyword for each is an array or a string:
Array
(
[0] => Array
(
[Keyword] => Array
(
[0] => skin
[1] => seal
)
)
[1] => Array
(
[Keyword] => paint
)
*/
# Add each material (each of which might have an (a,b) reference at the end)
$materials = array ();
foreach ($article['Description']['Material'] as $material) {
# Skip if no keyword
#!# Is this still needed?
// if (!isSet ($material['Keyword'])) {continue;}
# Convert Keyword if not already an array
if (!is_array ($material['Keyword'])) {
$material['Keyword'] = array ($material['Keyword']);
}
# Trim each Keyword
foreach ($material['Keyword'] as $index => $keyword) {
$material['Keyword'][$index] = trim ($keyword);
}
# If any keywords are empty, skip them
$empty = array ();
foreach ($material['Keyword'] as $index => $keyword) {
if (!strlen ($keyword)) {
unset ($material['Keyword'][$index]);
$empty[] = $index;
}
}
if ($empty) {
#!# Report to admin as error so that this can be fixed up; removed values are in $empty
#!# Known cases are: Y: 2009/31
}
# Skip this block if none
if (!$material['Keyword']) {continue;}
# Implode Keyword to string
$materialString = implode (' > ', $material['Keyword']);
# Add on Part if present
if (isSet ($material['Note'])) {
$part = trim ($material['Note']);
$materialString .= " ({$part})";
}
# Register the material
$materials[] = $materialString;
}
# Return the array
return $materials;
}
# Function to get the number of items
private function getNumberOfItems ($article)
{
# End if not present
if (!isSet ($article['NumberOfItems'])) {return false;}
# Normalise to flattened
$article['NumberOfItems'] = $this->normaliseToFlattened ($article['NumberOfItems']);
# Return the value, as an integer
return (int) $article['NumberOfItems'];
}
# Function to get the note
private function getNote ($article)
{
# End if not present
if (!isSet ($article['Identification'])) {return false;}
if (!isSet ($article['Identification']['Note'])) {return false;}
# If an array, take the first only (by observation, this avoids making some possibly private information public in Y: 2010/10/38)
#!# Report to admin as error so that this can be fixed up
#!# Known cases are: Y: 2010/10/38
if (is_array ($article['Identification']['Note'])) {
$article['Identification']['Note'] = $article['Identification']['Note'][0];
}
# Return the note
return $article['Identification']['Note'];
}
# Function to get the full description
private function getFullDescription ($article, $record)
{
# Full description is not relevant to pictures
if ($record['Type'] == 'picture') {return NULL;}
# If there is a Note as the first item at top level of the Description, just return that
#!# Report to admin as error so that this can be fixed up
# Known cases are: Y: 2014/8a-i
if (isSet ($article['Description']) && isSet ($article['Description'][0]) && isSet ($article['Description'][0]['Note'])) {
if (count ($article['Description'][0]) == 1) { // i.e. avoid cases like record N: 92a-b where the Note is amongst other fields
return $article['Description'][0]['Note'];
}
}
# Detect cases of /Description/[i]/Aspect and convert to /Description/Aspect/[i]
if (isSet ($article['Description']) && isSet ($article['Description'][0]) && isSet ($article['Description'][0]['Aspect'])) {
#!# Report to admin as error so that this can be fixed up
#!# Known cases are: N: 828a-c (which then shows the description three times, one for each part
foreach ($article['Description'] as $index => $descriptionBlock) {
$article['Description']['Aspect'][$index] = $descriptionBlock['Aspect'];
unset ($article['Description'][$index]);
}
}
# End if not present
if (!isSet ($article['Description'])) {return false;}
if (!isSet ($article['Description']['Aspect'])) {return false;}
if (!is_array ($article['Description']['Aspect'])) {return false;}
# Normalise to multiple
$article['Description']['Aspect'] = $this->normaliseToMultiple ($article['Description']['Aspect']);
# Loop through each description aspect
$descriptions = array ();
foreach ($article['Description']['Aspect'] as $item) {
# Skip if empty
#!# Is this required any more?
// if (!is_array ($item)) {continue;}
# Flatten SummaryText if nested, e.g. as required in record N: 55, where the SummaryText has an associated note
if (is_array ($item['SummaryText']) && isSet ($item['SummaryText']['SummaryText'])) {
$item['SummaryText'] = $item['SummaryText']['SummaryText'];
}
# Obtain the summary text
$description = $item['SummaryText'];
# Trim and ucfirst
$description = ucfirst (trim ($description));
# If the Part is nested, flatten
#!# Report to admin as error so that this can be fixed up
#!# Known cases are: N: 828a-c
$item['Part'] = $this->normaliseToFlattened ($item['Part']);
# Determine the part title
$part = ((isSet ($item['Part']) && $item['Part']) ? trim ($item['Part']) : false);
# If there is a part, and there is more than one item, prepend the part
if ($part) {
if (count ($article['Description']['Aspect']) > 1) {
#!# Why is the HTML working?
$description = '<em>' . $part . '</em>: ' . $description;
}
}
# Register the description
$descriptions[] = $description;
}
# Implode by double newline
$description = implode ("\n\n", $descriptions);
# Return the description
return $description;
}
# Function to get related records
private function getRelatedRecords ($article)
{
# End if not present
if (!isSet ($article['RelatedObject'])) {return array ();}
# End if none
if (!is_array ($article['RelatedObject'])) {return array ();}
# Normalise to multiple
$article['RelatedObject'] = $this->normaliseToMultiple ($article['RelatedObject']);
/* #!#
RelatedObject is a very inconsistent field and needs serious tidying in the data.
These sample records, picked at random, all have different layouts:
Y: 62/15/1
LS99/3/15
N: 26b
N: 433
Y: 76/7/1
N: 1767
*/
# Loop through each related object
$relatedObjects = array ();
foreach ($article['RelatedObject'] as $relatedRecord) {
# Skip if empty (which seems quite common)
if (empty ($relatedRecord)) {continue;}
# Skip if ObjectIdentity does not exist or is empty
if (!isSet ($relatedRecord['ObjectIdentity'])) {continue;}
if (!$relatedRecord['ObjectIdentity']) {continue;}
# Support format of an array containing single 'Number' value (e.g. record N: 26b): array ('Number' => value)
if (isSet ($relatedRecord['ObjectIdentity']['Number'])) {
# Skip if empty
#!# Report to admin as error so that this can be fixed up
#!# Known cases are: N: 1987
if (!strlen ($relatedRecord['ObjectIdentity']['Number'])) {continue;}
$relatedObjects[] = $relatedRecord['ObjectIdentity']['Number'];
continue;
}
# Support format of a simple list of values in a container called 'ObjectIdentity' (e.g. record Y: 76/7/2)
if (isSet ($relatedRecord['ObjectIdentity'][0])) {
$i = 0;
while (true) {
if (!isSet ($relatedRecord['ObjectIdentity'][$i])) {break;}
$relatedObjects[] = $relatedRecord['ObjectIdentity'][$i];
$i++;
}
}
# Support note field?
// $relatedObjects[] = $relatedRecord['Number'] . (isSet ($relatedRecord['Note']) ? "<br /> — Note: {$relatedRecord['Note']}" : '');
}
# Return the list
return $relatedObjects;
}
# Function to parse dimensions
private function getDimensions ($article, $record)
{
# End if no description
if (!isSet ($article['Description'])) {return false;}
# Ensure descriptions are specified as an set of items, even if only one
$article['Description'] = $this->normaliseToMultiple ($article['Description']);
# End if none
if (!$article['Description']) {return false;}
# Loop through each item
$dimensions = array ();
foreach ($article['Description'] as $descriptionIndex => $descriptionBlock) {
# Obtain the part title
$partTitle = $this->_getPartTitle ($descriptionBlock, $record['Type']);
# Obtain the dimensions, or end if none
if (!$partDimensions = $this->_getPartDimensions ($descriptionBlock)) {
continue;
}
# Register the item
$dimensions[$partTitle] = $partDimensions;
}
# Return the result
return $dimensions;
}
# Function to assemble a part title from a description block
#!# N: 246a has no title - consider what to do in these cases
private function _getPartTitle ($descriptionBlock, $recordType)
{
# Define the default
$default = ucfirst ($recordType);
# If Part is at the top level, move it into Aspect
if (isSet ($descriptionBlock['Part'])) {
$descriptionBlock['Aspect']['Part'] = $descriptionBlock['Part'];
#!# Report to admin as error so that this can be fixed up
#!# Known cases are: N: 352
}
# Part title is within the Aspect block of the Description; if none, return the default
if (!isSet ($descriptionBlock['Aspect'])) {
return $default;
}
# Get the part from each aspect
$partSubnames = array ();
$aspectBlocks = $this->normaliseToMultiple ($descriptionBlock['Aspect']);
foreach ($aspectBlocks as $aspectBlock) {
if (isSet ($aspectBlock['Part'])) {
$partSubnames[] = trim ($this->normaliseToFlattened ($aspectBlock['Part'])); // Flattening needed in e.g. record N: 199a-d; trim needed in e.g. record Y: 62/15/1
}
}
# If no part subnames found, return the default
if (!$partSubnames) {
return $default;
}
# If more than one (e.g. record Y: 62/15/1), combine
$part = implode (' & ', $partSubnames);
# Return the assembled title
return $part;
}
# Function to assemble a list dimensions of a part from a description block
private function _getPartDimensions ($descriptionBlock)
{
# Part title is within the Aspect block of the Description; if none, return the default; e.g. Y: 2014/8a-i where the first Description item contains only a note
if (!isSet ($descriptionBlock['Measurement'])) {return false;}
# Convert to multidimensional array, representing parts of the catalogued 'item' (e.g. a mortar and a pestle) if not already
$descriptionBlock['Measurement'] = $this->normaliseToMultiple ($descriptionBlock['Measurement']); // E.g. record Y: 62/15/32 has a single item
# End if none
if (!$descriptionBlock['Measurement']) {return false;}
# Assemble each dimension
$partDimensions = array ();
foreach ($descriptionBlock['Measurement'] as $measurementBlock) {
# Extract the name
$dimensionName = $measurementBlock['Dimension'];
# Skip if no value
if (!$measurementBlock['Reading']) {
#!# Report to admin as error so that this can be fixed up
#!# Known cases are: N: 352
continue;
}
# If the value is malformed, correct
if (is_array ($measurementBlock['Reading']['Value']) && isSet ($measurementBlock['Reading']['Value']['Value'])) {
$measurementBlock['Reading']['Value'] = $measurementBlock['Reading']['Value']['Value'];
#!# Report to admin as error so that this can be fixed up
#!# Known cases are: Y: 2014/8a-i
}
# Extract the value, unit and optional note
$value = $measurementBlock['Reading']['Value'];
$unit = $measurementBlock['Reading']['Unit'];
$note = '';
if (isSet ($measurementBlock['Reading']['Note'])) {
if (is_string ($measurementBlock['Reading']['Note']) && mb_strlen (trim ($measurementBlock['Reading']['Note']))) { // #!# /Description/Measurement/Reading/Note sometimes as /Description/Measurement/Reading/Note/[] in /api/article?id=Y%3A+2010%2F10%2F59&collection=? also /article/y2010.10.59/
$note = ' (' . $measurementBlock['Reading']['Note'] . ')'; // E.g. used on /article/y2010.10.93/
}
}
# Skip if no value
if (!$value) {continue;}
if ($value == '-') {continue;}
# Register the dimension
$partDimensions[$dimensionName] = $value . $unit . $note;
}
# End if no dimensions
if (!$partDimensions) {
#!# Remport to admin
#!# Known cases are Y: 2014/8a-i, item (g) - though that is probably a bogus entry as that record should have 8 items but 9 are listed
return array ('Dimensions' => '?');
}
# Re-sort, adding others to the list
$startOrder = array ('width', 'height', 'length', 'diameter'); /* which will be followed others, if present */
$partDimensions = application::resortStartOrder ($partDimensions, $startOrder);
# Return the dimensions list
return $partDimensions;
}
# Function to obtain the place name
private function getPlaceName ($article, $record)
{
# Only applies to image records
if ($record['Type'] != 'image') {return NULL;}