-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsymplecticPublicationsClient.php
executable file
·2597 lines (2141 loc) · 93.9 KB
/
symplecticPublicationsClient.php
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 create a publications database, implementing the Symplectic API
# Licence: GPL
# (c) Martin Lucas-Smith, University of Cambridge
# More info: https://github.com/camunigeog/symplectic-publications-client
#!# Consider adding support for direct upload of MP3 files, etc., in the same way as book covers
class symplecticPublicationsClient extends frontControllerApplication
{
# 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 (
'div' => strtolower (__CLASS__),
'applicationName' => 'Publications database',
'database' => 'publications',
'table' => 'publications',
'website' => NULL,
'apiUrl' => NULL,
'apiUsername' => false,
'apiPassword' => false,
'administrators' => 'administrators',
'tabUlClass' => 'tabsflat',
'yearsConsideredRecent' => 5,
'yearsConsideredRecentMainListing' => 2,
'hidingThreshold' => 5,
'canSplitIfTotal' => 10,
'additionalNameDefinitions' => array (),
'multisite' => false, // Whether the user/group/member functions cover more than one organisation
'getUsersFunction' => NULL,
'getGroupsFunction' => NULL,
'getGroupMembers' => NULL,
'cronUsername' => NULL,
'bookcoversLocation' => 'bookcovers/', // From baseUrl, or if starting with a slash, from DOCUMENT_ROOT
'bookcoversFormat' => 'png',
'bookcoversHeight' => 250,
'enableRelationships' => false, // Whether the relationships field in the API should be queried in limited circumstances
'organisationDescription' => 'Department', // String for all, or array to support multisite definitions
'corsDomains' => array (), // List of supported domains for JS embedding, respecting CORS
);
# Return the defaults
return $defaults;
}
# Define the supported types and their labels
private $types = array (
'book' => 'Books',
'preprint' => 'Pre-prints',
'journal-article' => 'Journal articles',
'chapter' => 'Book chapters',
'conference' => 'Conference proceedings',
'internet-publication' => 'Internet publications',
'report' => 'Reports',
'other' => 'Other publications',
'thesis-dissertation' => 'Theses / dissertations',
'c-19' => 'Working papers',
'software' => 'Software',
'presentation' => 'Presentations',
'media' => 'Media',
'performance' => 'Performances',
// '?' => 'Datasets',
// 'patent' => 'Patents',
// '?' => 'Compositions',
// '?' => 'Designs',
// '?' => 'Artefacts',
// '?' => 'Exhibitions',
// '?' => 'Scholarly editions',
// '?' => 'Posters',
);
# Define the types that should use listing by year
private $typesListingByYear = array (
'journal-article',
);
# Define the types that should use the expandability system
private $expandableTypes = array (
'chapter',
'journal-article',
'report',
'other',
);
# Function to assign additional actions
public function actions ()
{
# Specify additional actions
$actions = array (
'home' => array (
'description' => false,
'url' => '',
'icon' => 'house',
'tab' => 'Home',
),
'bookcover' => array (
'description' => 'Upload a book cover',
'url' => 'bookcover.html',
'icon' => 'book',
'tab' => 'Book cover',
'authentication' => true,
),
'recent' => array (
'description' => 'Most recent publications',
'url' => 'recent/',
'icon' => 'new',
'tab' => 'Recent',
),
'people' => array (
'description' => 'People',
'url' => 'people/',
'icon' => 'user',
'tab' => 'People',
),
'person' => array (
'description' => 'Publications of person',
'url' => 'people/%1/',
'usetab' => 'people',
),
'groups' => array (
'description' => 'Research groups',
'url' => 'groups/',
'icon' => 'group',
'tab' => 'Research groups',
),
'group' => array (
'description' => 'Publications of research group',
'url' => 'groups/%1/',
'usetab' => 'groups',
),
'statistics' => array (
'description' => 'Statistics',
'url' => 'statistics/',
'tab' => 'Statistics',
'administrator' => true,
),
'issues' => array (
'description' => 'Issues - data problems to be fixed',
'url' => 'issues.html',
'tab' => 'Issues',
'administrator' => true,
),
'import' => array (
'description' => 'Import data from Symplectic',
'url' => 'import/',
'icon' => 'database_refresh',
'tab' => 'Import',
'administrator' => true,
),
'api' => array (
'description' => 'API',
'url' => '%/json',
'authentication' => false,
'export' => true,
),
'cron' => array (
'description' => 'Cron hook for non-interactive processes',
'url' => 'cron/',
'authentication' => false,
'export' => true,
),
'retrieve' => array (
'description' => 'Retrieve raw data from the Symplectic API',
'url' => 'retrieve.html',
'parent' => 'admin',
'subtab' => 'Retrieve raw data',
'administrator' => true,
),
);
# Return the actions
return $actions;
}
# Database structure definition
public function databaseStructure ()
{
return "
CREATE TABLE `administrators` (
`crsid` varchar(10) NOT NULL PRIMARY KEY,
`active` enum('Y','N') NOT NULL DEFAULT 'Y',
`name` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Administrators';
CREATE TABLE `instances` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Automatic key' PRIMARY KEY,
`username` varchar(10) NOT NULL COMMENT 'Username',
`publicationId` int(11) NOT NULL COMMENT 'Publication ID',
`nameAppearsAsAuthor` varchar(255) DEFAULT NULL COMMENT 'The string appearing in the data for the name of the author',
`nameAppearsAsEditor` varchar(255) DEFAULT NULL COMMENT 'The string appearing in the data for the name of the editor',
`isFavourite` int(1) DEFAULT NULL COMMENT 'Favourite publication',
`savedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Automatic timestamp',
INDEX publicationId (publicationId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Table of publications for each user';
CREATE TABLE `publications` (
`id` int(11) NOT NULL COMMENT 'ID in original datasource' PRIMARY KEY,
`sourceName` varchar(255) NOT NULL COMMENT 'Source',
`type` varchar(255) DEFAULT NULL COMMENT 'Type',
`lastModifiedWhen` int(11) NOT NULL COMMENT 'Last modified when (Unixtime)',
`doi` varchar(255) DEFAULT NULL COMMENT 'DOI',
`title` text NOT NULL COMMENT 'Title',
`journal` varchar(255) DEFAULT NULL COMMENT 'Journal',
`publicationYear` varchar(255) DEFAULT NULL COMMENT 'Publication year',
`publicationMonth` varchar(255) DEFAULT NULL COMMENT 'Publication month',
`publicationDay` varchar(255) DEFAULT NULL COMMENT 'Publication day',
`dateIsAcceptance` INT(1) NULL DEFAULT NULL COMMENT 'Date is acceptance date',
`volume` varchar(255) DEFAULT NULL COMMENT 'Volume',
`issue` varchar(255) DEFAULT NULL COMMENT 'Issue',
`pagination` varchar(255) DEFAULT NULL COMMENT 'Pagination',
`publisher` varchar(255) DEFAULT NULL COMMENT 'Publisher',
`place` varchar(255) DEFAULT NULL COMMENT 'Place of publication',
`edition` varchar(255) DEFAULT NULL COMMENT 'Edition',
`editors` varchar(255) DEFAULT NULL COMMENT 'Editors',
`parentTitle` text DEFAULT NULL COMMENT 'Parent title',
`number` varchar(255) DEFAULT NULL COMMENT 'Number',
`authors` text COMMENT 'Authors',
`url` VARCHAR(255) NULL COMMENT 'URL',
`html` text NOT NULL COMMENT 'Compiled HTML representation of record',
`savedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Automatic timestamp'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Publications';
CREATE TABLE `userorganisations` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'Automatic key' PRIMARY KEY,
`userId` varchar(10) NOT NULL COMMENT 'User ID (join to users.id)',
`organisation` varchar(255) NOT NULL COMMENT 'Organisation',
INDEX userId (userId)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Table of organisations of each user';
CREATE TABLE `users` (
`id` varchar(10) NOT NULL COMMENT 'Username' PRIMARY KEY,
`forename` varchar(255) NOT NULL COMMENT 'Forename',
`surname` varchar(255) NOT NULL COMMENT 'Surname',
`savedAt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Automatic timestamp'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Table of data of users who have publications';
CREATE TABLE `instances_import` LIKE `instances`;
CREATE TABLE `publications_import` LIKE `publications`;
CREATE TABLE `userorganisations_import` LIKE `userorganisations`;
CREATE TABLE `users_import` LIKE `users`;
CREATE TABLE `exclude` (
`id` varchar(191) NOT NULL COMMENT 'Group' PRIMARY KEY,
`exclude` text COMMENT 'Publications to exclude, comma-separated',
`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='Table of publications to be excluded for a group';
";
}
# Additional initialisation, prior to actions processing phase
protected function mainPreActions ()
{
# Switch to API mode if specified
$outputFormats = array ('json', 'html');
if (isSet ($_GET['api']) && in_array ($_GET['api'], $outputFormats)) {
$this->action = 'api';
}
}
# Additional initiatialisation
protected function main ()
{
# Set the first year when publications are considered old
$this->firstOldYear = date ('Y') - $this->settings['yearsConsideredRecent'] - 1; // e.g. 2015 gives 2009 as the old year
# Define a database constraint string for types
$this->typesConstraintString = "type IN('" . implode ("','", array_keys ($this->types)) . "')";
# Determine the book covers directory; if a relative path, define it in relation to the baseUrl
if (substr ($this->settings['bookcoversLocation'], 0, 1) != '/') {
$this->settings['bookcoversLocation'] = $this->baseUrl . '/' . $this->settings['bookcoversLocation'];
}
# Ensure the book covers directory exists and is writable
if (!is_dir ($_SERVER['DOCUMENT_ROOT'] . $this->settings['bookcoversLocation'])) {
echo "\n<p class=\"warning\">The book covers directory is not present. The administrator needs to fix this problem before the system will run.</p>";
return false;
}
if (!is_writable ($_SERVER['DOCUMENT_ROOT'] . $this->settings['bookcoversLocation'])) {
echo "\n<p class=\"warning\">The book covers directory is not writable. The administrator needs to fix this problem before the system will run.</p>";
return false;
}
# Define start words to strip in comma-and listings
$this->commaAndStripStartingWords = array ('with');
}
# Show data date
public function guiSearchBox ()
{
$tableStatus = $this->databaseConnection->getTableStatus ($this->settings['database'], $this->settings['table']);
return $html = "\n<p class=\"small comment\"><!-- ignore-changes -->{$tableStatus['Comment']}<!-- /ignore-changes --></p>";
}
# API controller
public function api ()
{
# Send CORS headers
$this->corsHeaders ();
# Get the data, which may be an error
$data = $this->apiInner ($errorMessage);
# Emit 404 header if an error (e.g. method wrong, or person not present, etc.)
if (isSet ($data['json']['error'])) {
application::sendHeader (404);
}
# Select the relevant rendering
$outputFormat = $_GET['api']; // Already validated in mainPreActions
$data = $data[$outputFormat];
# Determine output
switch ($outputFormat) {
# JSON
case 'json':
$data = json_encode ($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
header ('Content-Type: application/json');
break;
# HTML
case 'html':
//
}
# Emit the data
echo $data;
}
# API controller (inner)
private function apiInner (&$errorMessage = '')
{
# Ensure an action is specified
if (!isSet ($_GET['action'])) {
return array ('json' => array ('error' => 'No method was specified.'), 'html' => '');
}
$action = $_GET['action'];
# Ensure the specified action exists
if (!isSet ($this->actions[$action])) {
return array ('error' => 'An unsupported method was specified');
}
# Determine if an item is specified
$item = (isSet ($_GET['item']) ? $_GET['item'] : false);
# Get the data
$data = $this->{$action} ($item);
# Return the data
return $data;
}
# Welcome screen
public function home ()
{
# Introduction
$html = "\n<div class=\"graybox\">";
$html .= "\n\t<p>This system contains data exported from the <a href=\"{$this->settings['website']}\" target=\"_blank\">Symplectic publications database portal</a>.</p>";
$html .= "\n</div>";
# Recent
$html .= "\n<h3>Most recent</h3>";
$html .= "\n<p><a href=\"{$this->baseUrl}/recent/\" class=\"actions\">" . '<img src="/images/icons/new.png" alt="*" class="icon" />' . " <strong>Most recent publications</strong></a></p>";
# People
$html .= "\n<h3>People</h3>";
$html .= "\n<p><a href=\"{$this->baseUrl}/people/\" class=\"actions\">" . '<img src="/images/icons/user.png" alt="*" class="icon" />' . " <strong>Publications by person</strong></a></p>";
# Research groups
$html .= "\n<h3>Research groups</h3>";
$html .= "\n<p><a href=\"{$this->baseUrl}/groups/\" class=\"actions\">" . '<img src="/images/icons/group.png" alt="*" class="icon" />' . " <strong>Publications by group</strong></a></p>";
# Statistics
if ($this->userIsAdministrator) {
$html .= "\n<h3>Statistics</h3>";
$data = $this->getStatistics ();
$html .= application::htmlTable ($data, array (), 'statistics lines compressed');
}
# Show the HTML
echo $html;
}
# Page to upload a book cover
public function bookcover ()
{
# Start the HTML
$html = '';
# Ensure the person is present, or end
if (!$this->userHasPublications ($this->user)) {
$html .= "\n<p>You do not appear to have any books in the Symplectic system.</p>";
echo $html;
return true;
}
# Get the publications for that user
if (!$data = $this->getPerson ($this->user, 'book')) {
$html .= "\n<p>You do not appear to have any books in the Symplectic system.</p>";
$html .= "\n<p>However, if you have added a book to Symplectic just now, please check back here in a few hours, as there is a slight delay for this website to pick up new publications from Symplectic.</p>";
echo $html;
return true;
}
# Arrange as key => title, and show whether there is currently a cover
$books = array ();
foreach ($data as $id => $book) {
$books[$id] = ($book['thumbnail'] ? chr(0xe2).chr(0x9c).chr(0x93) : chr(0xe2).chr(0x96).chr(0xa2)) . ' ' . $book['title'];
}
# Assemble the book covers directory
$directory = $_SERVER['DOCUMENT_ROOT'] . $this->settings['bookcoversLocation'];
# Show the upload form
$form = new form (array (
'formCompleteText' => false,
'div' => 'ultimateform',
));
$form->select (array (
'name' => 'book',
'title' => 'Book',
'values' => $books,
'required' => true,
));
$form->heading ('p', "Please select an image from your computer. It will be automatically resized to a height of {$this->settings['bookcoversHeight']}px.");
$form->upload (array (
'name' => 'image',
'title' => 'Image',
'required' => 1,
'directory' => $directory,
'allowedExtensions' => array ('jpg', 'gif', 'png', ),
'forcedFileName' => $this->user, // Avoids race condition issues
'required' => true,
'thumbnail' => true,
));
if (!$result = $form->process ()) {
echo $html;
return false;
}
# Rename the file to the ID of the book
$tmpFile = $_SERVER['DOCUMENT_ROOT'] . $this->settings['bookcoversLocation'] . $result['image'][0];
$uploadedFile = $_SERVER['DOCUMENT_ROOT'] . $this->settings['bookcoversLocation'] . $result['book'] . '-original' . '.' . pathinfo ($result['image'][0], PATHINFO_EXTENSION);
rename ($tmpFile, $uploadedFile);
# Resize
$thumbnailFile = $_SERVER['DOCUMENT_ROOT'] . $this->settings['bookcoversLocation'] . $result['book'] . '.' . $this->settings['bookcoversFormat'];
image::resize ($uploadedFile, $outputFormat = 'jpg', $newWidth = '', $this->settings['bookcoversHeight'], $thumbnailFile, false);
# Confirm success
$html = "\n<p>{$this->tick} The book cover has been successfully uploaded.</p>";
$html .= "\n<p>Please navigate to your public page on the website to see it.</p>";
$html .= "\n<p><a href=\"{$this->baseUrl}/bookcover.html\">Add another?</a></p>";
# Show the HTML
echo $html;
}
# People listing page
public function people ()
{
# Start the output HTML
$html = '';
# Provide API links
$apiLinks = $this->apiLinks ();
# Get the users from the local database
$users = $this->getPeople ();
# End if none
if (!$users) {
$html .= "\n<p>There are no users.</p>";
if ($this->action == 'api') {return array ('json' => $users, 'html' => $html);}
echo $html;
return true;
}
# Create a listing
$list = array ();
foreach ($users as $username => $user) {
$nameHtml = htmlspecialchars ($user['forename']) . ' <strong>' . htmlspecialchars ($user['surname']) . '</strong>';
$list[$username] = "<a href=\"{$this->baseUrl}/people/{$username}/\">{$nameHtml} <{$username}> ({$user['total']})" . ($user['favourites'] ? " ({$user['favourites']}<img src=\"/images/general/star.png\" class=\"icon favourite\" />)" : '') . '</a>';
}
$html = application::htmlUl ($list);
# API output
if ($this->action == 'api') {return array ('json' => $users, 'html' => $html);}
# Render the page HTML
$pageHtml = $apiLinks;
$pageHtml .= "\n<p>Please select a user:</p>";
$pageHtml .= $html;
# Show the page HTML
echo $pageHtml;
}
# Publications for a person
public function person ($username = false)
{
# Start the output HTML
$html = '';
# Ensure the person is present, or end
if (!$user = $this->userHasPublications ($username)) {
$errorMessage = 'There is no such user.';
if ($this->action == 'api') {
header ('HTTP/1.1 204 No Content'); // Zero-length content will be sent as per the HTTP specification
return array ('json' => array (), 'html' => $html);
}
$html .= "\n<p>{$errorMessage}</p>";
echo $html;
return true;
}
# Determine whether to show starred items with the star
$showStars = true;
if (isSet ($_GET['stars']) && ($_GET['stars'] == '0')) {
$showStars = false;
}
# Get the publications for that user
$publications = $this->getPerson ($username);
# Render as a list
$html = $this->publicationsList ($publications, $showFeatured = true, $showStars);
# API output
if ($this->action == 'api') {return array ('json' => $publications, 'html' => $html);}
# Show publications
$nameHtml = htmlspecialchars ($user['forename']) . ' <strong>' . htmlspecialchars ($user['surname']) . '</strong>';
$total = number_format (count ($publications));
$pageHtml = $this->apiLinks ();
$pageHtml .= "\n<p id=\"introduction\">Publications ({$total}) for {$nameHtml}:</p>";
$pageHtml .= "\n<hr />";
$pageHtml .= $html;
# Show the page HTML
echo $pageHtml;
}
# Function to provide a side-by-side comparison system for migration
public function autoreplace ($baseUrl, $username)
{
# Determine if the user is authorised for internal functions
$authorisedUser = false;
if ($_SERVER['REMOTE_USER']) {
# Determine if the user is an administrator
$currentUser = $_SERVER['REMOTE_USER'];
$userIsAdministrator = array_key_exists ($currentUser, $this->administrators);
# End if not the current user or an administrator
if (($currentUser == $username) || $userIsAdministrator) {
$authorisedUser = true;
}
}
$showToolsJs = ($authorisedUser ? 'true' : 'false');
# Define the HTML
$html = "\n\n
<!-- Load publications -->
<script src=\"{$baseUrl}/dist/symplecticPublications.js\"></script>
<script>
document.addEventListener ('DOMContentLoaded', function () {
const settings = {
baseUrl: '{$baseUrl}',
username: '{$username}',
showTools: {$showToolsJs},
website: '{$this->settings['website']}'
};
symplecticPublications.init (settings);
});
</script>
";
# Return the HTML
return $html;
}
# Function to determine if a user has publications
public function userHasPublications ($username)
{
# Get the users
$users = $this->getPeople ();
# If not present, return false
if (!isSet ($users[$username])) {return false;}
# Return the user's details
return $users[$username];
}
# Research group listings
public function groups ()
{
# Start the output HTML
$html = '';
# Provide API links
$apiLinks = $this->apiLinks ();
# Get the users and their organisations
list ($groups, $groupsBySite) = $this->getGroups ();
# End if none
if (!$groups) {
$html .= "\n<p>There are no research groups.</p>";
if ($this->action == 'api') {return array ('json' => $groups, 'html' => $html);}
echo $html;
return true;
}
# Create a listing
foreach ($groupsBySite as $organisation => $groupsThisSite) {
$list = array ();
foreach ($groupsThisSite as $id => $group) {
$nameHtml = htmlspecialchars ($group['name']);
$list[$id] = "<a href=\"{$this->baseUrl}/groups/{$id}/\">{$nameHtml}</a>";
}
if ($organisation) {
$html .= "\n<h3>" . htmlspecialchars ($organisation) . ':</h3>';
}
$html .= application::htmlUl ($list);
}
# API output
if ($this->action == 'api') {return array ('json' => $groups, 'html' => $html);}
# Render the page HTML
$pageHtml = $apiLinks;
$pageHtml .= "\n<p>Please select a research group:</p>";
$pageHtml .= $html;
# Show the page HTML
echo $pageHtml;
}
# Publications for a research group
public function group ($moniker = false)
{
# Start the output HTML
$html = '';
# Get the users and their organisations
list ($groups, $groupsBySite) = $this->getGroups ();
# Ensure the group is present, or end
if (!isSet ($groups[$moniker])) {
$errorMessage = 'There is no such group.';
if ($this->action == 'api') {return array ('json' => array ('error' => $errorMessage), 'html' => $html);}
$html .= "\n<p>{$errorMessage}</p>";
echo $html;
return true;
}
$group = $groups[$moniker];
# Determine whether to show starred items with the star
$showStars = true;
if (isSet ($_GET['stars']) && ($_GET['stars'] == '0')) {
$showStars = false;
}
# Get the members of the group
$usernames = $this->getGroupMembersUpstream ($group['url']);
# Get the publications for that user
$publications = $this->getPeoplePublications ($usernames);
# Determine publications determined already as filtered
$currentlyFiltered = $this->databaseConnection->selectOneField ($this->settings['database'], 'exclude', 'exclude', array ('id' => $moniker));
$currentlyFiltered = ($currentlyFiltered ? explode (',', $currentlyFiltered) : array ()); // Convert to array
# Determine whether to enable the filtering UI, and if so, specify the moniker of the group
$filteringUiGroup = (($this->userIsAdministrator || ($this->user && in_array ($this->user, $group['managers']))) ? ($this->action == 'group' ? $moniker : false) : false);
# If a remote user has been passed through, add an editing link
if (isSet ($_GET['REMOTE_USER'])) {
$editingPageUrl = $_SERVER['_SITE_URL'] . $this->baseUrl . '/groups/' . $moniker . '/';
$html .= "\n<p class=\"primaryaction right\"><a href=\"{$editingPageUrl}\" title=\"Edit the publications in this list, by filtering out unwanted items\"><img src=\"/images/icons/pencil.png\" class=\"icon\" /> Edit publications</a></p>";
}
# Render as a list
$html .= $this->publicationsList ($publications, false, $showStars, $currentlyFiltered, $filteringUiGroup);
# API output
if ($this->action == 'api') {return array ('json' => $publications, 'html' => $html);}
# Show publications
$nameHtml = htmlspecialchars ($group['name']);
$total = number_format (count ($publications));
$pageHtml = $this->apiLinks ();
$pageHtml .= "\n<p id=\"introduction\">Recent publications ({$total}) of members of the <strong>{$nameHtml}</strong> research group:</p>";
$pageHtml .= "\n<hr />";
$pageHtml .= $html;
# Show the page HTML
echo $pageHtml;
}
# Most recent publications
public function recent ()
{
# Start the output HTML
$html = '';
# Get the list of organisations (which will be done when multisite is disabled)
$organisations = $this->getOrganisations ();
# If an organisation has been specified, ensure that organisations are enabled and that Determine and validate the requested organisation, if any
$organisation = (isSet ($_GET['organisation']) ? $_GET['organisation'] : false);
if ($organisation) {
if (!$organisations || !in_array ($organisation, $organisations)) {
$this->page404 ();
return false;
}
}
# Determine the number of years to show
$years = $this->settings['yearsConsideredRecentMainListing'];
if (isSet ($_GET['years']) && ctype_digit ($_GET['years'])) {
$years = $_GET['years'];
}
# Determine whether to show starred items with the star
$showStars = true;
if (isSet ($_GET['stars']) && ($_GET['stars'] == '0')) {
$showStars = false;
}
# Get the most recent publications
$publications = $this->getRecent ($years, $organisation);
# Render as a list
$html = $this->publicationsList ($publications, false, $showStars);
# API output
if ($this->action == 'api') {return array ('json' => $publications, 'html' => $html);}
# Determine the organisation description
$organisationDescription = $this->settings['organisationDescription'];
if ($this->settings['multisite'] && is_array ($this->settings['organisationDescription'])) {
if ($organisation) {
$organisationDescription = $this->settings['organisationDescription'][$organisation];
} else {
$organisationDescriptionValues = array_values ($this->settings['organisationDescription']);
$firstOrganisationDescription = array_shift ($organisationDescriptionValues);
$organisationDescription = $firstOrganisationDescription;
}
}
# Show publications
$total = number_format (count ($publications));
$pageHtml = $this->organisationsTabs ($organisations);
$pageHtml .= $this->apiLinks ();
$pageHtml .= "\n<p id=\"introduction\">Most recent publications ({$total}) involving members of the {$organisationDescription} in the last {$years} " . ($years == 1 ? 'year' : 'years') . ":</p>";
$pageHtml .= "\n<hr />";
$pageHtml .= $html;
# Show the page HTML
echo $pageHtml;
}
# Function to determine the organisations present
private function getOrganisations ()
{
# End if disabled
if (!$this->settings['multisite']) {return false;}
# Get an array of distinct organisations
$query = "SELECT DISTINCT(organisation) FROM {$this->settings['database']}.userorganisations ORDER BY organisation;";
$data = $this->databaseConnection->getPairs ($query);
# Return the list
return $data;
}
# Function to create a tab set of organisations
private function organisationsTabs ($organisations)
{
# End if not multiple organisations
if (!$organisations) {return false;}
# Define a base link for all tabs
$baseLink = $this->baseUrl . '/recent/';
# Start with the default (all)
$list = array ();
$list[''] = 'View: ';
$list[$baseLink] = "<a href=\"{$baseLink}\">All</a>";
# Add a link for each organisation
foreach ($organisations as $organisation) {
$link = $baseLink . htmlspecialchars (urlencode ($organisation)) . '/';
$list[$link] = "<a href=\"{$link}\">" . htmlspecialchars ($organisation) . '</a>';
}
# Compile the HTML
$html = application::htmlUl ($list, 0, 'tabs subtabs', true, false, false, false, $selected = $_SERVER['REQUEST_URI']);
# Return the HTML
return $html;
}
# Function to provide an API link to the data equivalent of the current page
private function apiLinks ()
{
# Construct the HTML
$html = "\n" . '<p class="right faded"><a href="json"><img src="/images/icons/feed.png" alt="JSON output" border="0" /> JSON</a> | <a href="html"><img src="/images/icons/feed.png" alt="JSON output" border="0" /> HTML</a></p>';
# Return the HTML
return $html;
}
# Function to get the list of users from the database that have publications
private function getPeople ()
{
# Get the data
$query = "SELECT
users.id,
users.forename,
users.surname,
COUNT(instances.username) AS total,
COUNT(instances.isFavourite) AS favourites
FROM users
LEFT JOIN instances ON users.id = instances.username
LEFT JOIN publications ON instances.publicationId = publications.id
WHERE {$this->typesConstraintString}
GROUP BY instances.username
HAVING total > 0
ORDER BY surname, forename
;";
$data = $this->databaseConnection->getData ($query, "{$this->settings['database']}.users", true);
# Return the data
return $data;
}
# Function to get publications of a user from the database
private function getPerson ($username, $type = false)
{
# Get the data
$query = "SELECT
publications.*,
instances.isFavourite,
instances.nameAppearsAsAuthor AS highlightAuthors,
instances.nameAppearsAsEditor AS highlightEditors
FROM instances
LEFT OUTER JOIN publications ON instances.publicationId = publications.id
WHERE
username = :username
AND {$this->typesConstraintString}"
. ($type ? " AND type = '{$type}'" : '') . "
ORDER BY publicationYear DESC, authors
;";
$data = $this->databaseConnection->getData ($query, "{$this->settings['database']}.instances", true, array ('username' => $username));
# Highlight the authors
$data = $this->decoratePublicationsRuntime ($data);
# Return the data
return $data;
}
# Function to get publications of a set of users from the database
private function getPeoplePublications ($usernames)
{
# Assemble the username list into a regexp
$usernames = '^(' . implode ('|', $usernames) . ')$';
# Get the data; uses GROUP_CONCAT method as described at https://www.percona.com/blog/2013/10/22/the-power-of-mysql-group_concat/
$query = "SELECT
publications.*,
GROUP_CONCAT(DISTINCT instances.isFavourite) AS isFavourite,
GROUP_CONCAT(DISTINCT instances.nameAppearsAsAuthor ORDER BY nameAppearsAsAuthor SEPARATOR '|') AS highlightAuthors,
GROUP_CONCAT(DISTINCT instances.nameAppearsAsEditor ORDER BY nameAppearsAsEditor SEPARATOR '|') AS highlightEditors
FROM instances
LEFT OUTER JOIN publications ON instances.publicationId = publications.id
WHERE
username REGEXP :usernames
AND {$this->typesConstraintString}
AND CAST(publicationYear AS UNSIGNED INT) > '{$this->firstOldYear}'
GROUP BY publications.id
ORDER BY publicationYear DESC, authors
;";
$data = $this->databaseConnection->getData ($query, "{$this->settings['database']}.publications", true, array ('usernames' => $usernames));
# Highlight the authors and add starring
$data = $this->decoratePublicationsRuntime ($data);
# Return the data
return $data;
}
# Function to get the most recent publications
private function getRecent ($years, $organisation = false)
{
# Determine constraints
$preparedStatementValues = array ();
if ($organisation) {
$preparedStatementValues['organisation'] = $organisation;
}
# Get the data
$firstOldYearMainListing = date ('Y') - $years - 1;
$query = "SELECT
publications.*,
GROUP_CONCAT(DISTINCT instances.isFavourite) AS isFavourite,
GROUP_CONCAT(DISTINCT instances.nameAppearsAsAuthor ORDER BY nameAppearsAsAuthor SEPARATOR '|') AS highlightAuthors,
GROUP_CONCAT(DISTINCT instances.nameAppearsAsEditor ORDER BY nameAppearsAsEditor SEPARATOR '|') AS highlightEditors
FROM instances
LEFT OUTER JOIN publications ON instances.publicationId = publications.id
LEFT JOIN userorganisations ON instances.username = userorganisations.userId /* Only actually needed when organisation constraint present */
WHERE
CAST(publicationYear AS UNSIGNED INT) > '{$firstOldYearMainListing}'
AND {$this->typesConstraintString}
" . ($organisation ? ' AND organisation = :organisation' : '') . "
GROUP BY publications.id
ORDER BY publicationYear DESC, authors
;";
$data = $this->databaseConnection->getData ($query, "{$this->settings['database']}.instances", true, $preparedStatementValues);
# Highlight the authors and add starring if required
$data = $this->decoratePublicationsRuntime ($data);
# Return the data
return $data;
}
# Function to decorate publications at runtime (e.g. highlight the authors and add stars)
private function decoratePublicationsRuntime ($data)
{
# Highlight authors
foreach ($data as $id => $publication) {
$publication['html'] = $this->highlightContributors ($publication, 'authors', 'highlightAuthors');
$publication['html'] = $this->highlightContributors ($publication, 'editors', 'highlightEditors');
$data[$id]['html'] = $publication['html'];
}
# Add book covers if present
foreach ($data as $id => $publication) {
$data[$id]['thumbnail'] = false;
$data[$id]['thumbnailHtml'] = false;
$location = $this->settings['bookcoversLocation'] . $id . '.' . $this->settings['bookcoversFormat'];
if (file_exists ($_SERVER['DOCUMENT_ROOT'] . $location)) {
list ($width, $height, $type, $attributesHtml) = getimagesize ($_SERVER['DOCUMENT_ROOT'] . $location);
$altHtml = htmlspecialchars ($publication['title']);
#!# Need to add a configuration option for whether book covers (and other assets) should have $_SERVER['_SITE_URL'] prepended or not
$data[$id]['thumbnail'] = $location;
$data[$id]['thumbnailHtml'] = "<img src=\"{$data[$id]['thumbnail']}\" {$attributesHtml} alt=\"{$altHtml}\" class=\"bookcover\" />";
}
}
// application::dumpData ($data);
# Return the data
return $data;
}
# Function to perform contributor highlighting
public function highlightContributors ($publication, $field, $highlightField)