-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathresolver.php
More file actions
862 lines (755 loc) · 29.5 KB
/
Copy pathresolver.php
File metadata and controls
862 lines (755 loc) · 29.5 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
<?php
/**
* @file plugins/pubIds/ark/resolver.php
*
* ARK Resolver
*
* @copyright (c) 2026 Lury Morais
* @license GNU GPL v2
*/
// Block search engines - Must be before any output
header('X-Robots-Tag: noindex, nofollow');
/**
* Get the base URL of the OJS installation
*
* @return string Base URL (e.g., https://example.com)
*/
function getSiteBaseUrl() {
$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
$baseUrl = str_replace('/plugins/pubIds/ark', '', $baseUrl);
$protocol = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https" : "http";
return $protocol . "://" . $_SERVER['HTTP_HOST'] . $baseUrl;
}
/**
* Read database configuration from config.inc.php
*
* @throws Exception If config file is not found or required fields are missing
* @return array Database configuration (driver, host, username, password, name)
*/
function getDbConfig() {
$configFile = dirname(__FILE__, 4) . '/config.inc.php';
if (!file_exists($configFile)) {
throw new Exception('Configuration file not found: ' . $configFile);
}
$configLines = file($configFile, FILE_IGNORE_NEW_LINES);
$dbConfig = [];
$inDbSection = false;
foreach ($configLines as $line) {
$line = trim($line);
// Skip empty lines and comments
if (empty($line) || $line[0] === ';' || $line[0] === '#') {
continue;
}
// Check for database section
if (strpos($line, '[database]') === 0) {
$inDbSection = true;
continue;
}
// Check for other sections
if ($inDbSection && strpos($line, '[') === 0) {
$inDbSection = false;
continue;
}
// Parse configuration values
if ($inDbSection && strpos($line, '=') !== false) {
list($key, $value) = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Remove quotes if present
$value = trim($value, " \t\n\r\0\x0B\"'");
$dbConfig[$key] = $value;
}
}
// Validate required fields
$required = ['driver', 'host', 'username', 'password', 'name'];
foreach ($required as $field) {
if (empty($dbConfig[$field])) {
throw new Exception("Missing database configuration: {$field}");
}
}
return $dbConfig;
}
/**
* Extract inflection from query string and clean the ARK value
*
* Detects '?info', '.info', '??' (full metadata) and '?' (brief metadata)
* Modifies the ARK value by reference to remove inflection characters
*
* @return string|null 'brief' for '?', 'full' for '?info'/'info'/'??', or null if no inflection
*/
function getInflection() {
$requestUri = $_SERVER['REQUEST_URI'];
// Check for '&info' parameter (works reliably)
if (isset($_GET['info'])) {
return 'full';
}
// Check for '.info' at the end of URL
if (substr($requestUri, -5) === '.info') {
return 'full';
}
// Check for '?info' in the URL (if server preserves it)
if (strpos($requestUri, '?info') !== false) {
return 'full';
}
// Check for legacy '??' inflection
if (substr($requestUri, -2) === '??') {
return 'full';
}
// Check for legacy '?' inflection (brief metadata)
if (substr($requestUri, -1) === '?' && substr($requestUri, -2) !== '??') {
return 'brief';
}
return null;
}
/**
* Get metadata for ERC response
*
* Fetches article metadata from OJS database
*
* @param PDO $pdo Database connection
* @param int $publicationId Publication ID
* @param int $contextId Journal ID
* @param string $arkSuffix ARK suffix (without prefix)
* @param string $baseUrl Site base URL
* @return array Metadata array with keys: who, what, when, ark_url, base_ark_url, who_journal, issn, support_when
*/
function getMetadataForERC($pdo, $publicationId, $contextId, $arkSuffix, $baseUrl,) {
$metadata = [];
// Get publication basic info
$stmt = $pdo->prepare("
SELECT p.*, s.locale as submission_locale
FROM publications p
JOIN submissions s ON p.submission_id = s.submission_id
WHERE p.publication_id = ?
LIMIT 1
");
$stmt->execute([$publicationId]);
$publication = $stmt->fetch(PDO::FETCH_ASSOC);
// Get authors with their names from author_settings table
$stmt = $pdo->prepare("
SELECT
a.author_id,
a.seq,
MAX(CASE WHEN as_given.setting_name = 'givenName' THEN as_given.setting_value END) as givenName,
MAX(CASE WHEN as_family.setting_name = 'familyName' THEN as_family.setting_value END) as familyName
FROM authors a
LEFT JOIN author_settings as_given ON a.author_id = as_given.author_id
AND as_given.setting_name = 'givenName'
LEFT JOIN author_settings as_family ON a.author_id = as_family.author_id
AND as_family.setting_name = 'familyName'
WHERE a.publication_id = ?
GROUP BY a.author_id, a.seq
ORDER BY a.seq
LIMIT 3
");
$stmt->execute([$publicationId]);
$authors = $stmt->fetchAll(PDO::FETCH_ASSOC);
$authorNames = [];
foreach ($authors as $author) {
$name = '';
if (!empty($author['givenName'])) $name .= $author['givenName'] . ' ';
if (!empty($author['familyName'])) $name .= $author['familyName'];
if (!empty(trim($name))) $authorNames[] = trim($name);
}
// Fallback: if no names found, try to get from email
if (empty($authorNames)) {
$stmt = $pdo->prepare("
SELECT email FROM authors WHERE publication_id = ? ORDER BY seq LIMIT 3
");
$stmt->execute([$publicationId]);
$emails = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($emails as $email) {
$authorNames[] = $email['email'];
}
}
$metadata['who'] = !empty($authorNames) ? implode('; ', $authorNames) : 'Unknown author';
// Get title from publication_settings
$stmt = $pdo->prepare("
SELECT setting_value FROM publication_settings
WHERE publication_id = ? AND setting_name = 'title'
LIMIT 1
");
$stmt->execute([$publicationId]);
$title = $stmt->fetch(PDO::FETCH_ASSOC);
$metadata['what'] = $title ? html_entity_decode($title['setting_value'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : 'Untitled';
// Get publication date
$metadata['when'] = '';
if (!empty($publication['date_published'])) {
$metadata['when'] = date('Ymd', strtotime($publication['date_published']));
} elseif (!empty($publication['last_modified'])) {
$metadata['when'] = date('Ymd', strtotime($publication['last_modified']));
} else {
$metadata['when'] = date('Ymd');
}
// Get journal title from journal_settings
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND setting_name = 'name'
LIMIT 1
");
$stmt->execute([$contextId]);
$journalName = $stmt->fetch(PDO::FETCH_ASSOC);
$metadata['who_journal'] = $journalName ? html_entity_decode($journalName['setting_value'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : 'Journal';
// Get ISSN from journal_settings
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND (setting_name = 'printIssn' OR setting_name = 'onlineIssn')
LIMIT 1
");
$stmt->execute([$contextId]);
$issn = $stmt->fetch(PDO::FETCH_ASSOC);
$metadata['issn'] = $issn ? $issn['setting_value'] : '';
// Get the full ARK identifier from database
$stmt = $pdo->prepare("
SELECT setting_value FROM publication_settings
WHERE publication_id = ? AND setting_name = 'pub-id::ark'
LIMIT 1
");
$stmt->execute([$publicationId]);
$arkFull = $stmt->fetch(PDO::FETCH_ASSOC);
// First 'where' field: Complete ARK URL with trailing slash
$fullArkId = $arkFull ? $arkFull['setting_value'] : '';
if (!empty($fullArkId)) {
if (strpos($fullArkId, 'http') !== 0) {
$metadata['ark_url'] = 'https://n2t.net/' . ltrim($fullArkId, '/') . '/';
} else {
$metadata['ark_url'] = rtrim($fullArkId, '/') . '/';
}
} else {
// Fallback
$metadata['ark_url'] = $baseUrl . "/plugins/pubIds/ark/resolver.php?ark=" . urlencode($arkSuffix) . '/';
}
// Second 'where' field (erc-support): Base ARK URL up to NAAN
$naan = '';
if (!empty($fullArkId)) {
if (preg_match('/ark:([0-9]+)\//', $fullArkId, $matches)) {
$naan = $matches[1];
}
}
$metadata['base_ark_url'] = 'https://n2t.net/ark:' . $naan . '/';
// Get ARK implementation date from journal settings (fixed date)
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND setting_name = 'arkImplementationDate' AND (locale = '' OR locale IS NULL)
LIMIT 1
");
$stmt->execute([$contextId]);
$implDate = $stmt->fetch(PDO::FETCH_ASSOC);
// Use implementation date if set and valid, otherwise fallback to article publication date
if ($implDate && !empty($implDate['setting_value']) && preg_match('/^(19|20)\d{6}$/', $implDate['setting_value'])) {
$metadata['support_when'] = $implDate['setting_value'];
} else {
$metadata['support_when'] = $metadata['when'];
}
$metadata['primary_locale'] = getPrimaryLocale($pdo, $contextId);
$metadata['site_url'] = $baseUrl;
return $metadata;
}
/**
* Output brief ERC metadata (for '?' inflection)
*
* @param array $metadata Metadata array
* @param string $arkSuffix ARK suffix
* @param string $fullArkResolverUrl Full resolver URL
*/
function outputBriefERC($metadata, $arkSuffix, $fullArkResolverUrl) {
header('Content-Type: text/plain; charset=utf-8');
echo "erc:\n";
echo "who: " . $metadata['who'] . "\n";
echo "what: " . $metadata['what'] . "\n";
echo "when: " . $metadata['when'] . "\n";
echo "where: " . $metadata['ark_url'] . "\n";
}
/**
* Output full ERC metadata with support info (for '??' inflection)
*
* @param array $metadata Metadata array
* @param string $arkSuffix ARK suffix
* @param string $fullArkResolverUrl Full resolver URL
*/
function outputFullERC($metadata, $arkSuffix, $fullArkResolverUrl) {
header('Content-Type: text/plain; charset=utf-8');
echo "erc:\n";
echo "who: " . $metadata['who'] . "\n";
echo "what: " . $metadata['what'] . "\n";
echo "when: " . $metadata['when'] . "\n";
echo "where: " . $metadata['ark_url'] . "\n";
echo "erc-support:\n";
echo "who: " . $metadata['who_journal'] . "\n";
echo "what: Permanent: Stable Content:\n";
echo "when: " . $metadata['support_when'] . "\n";
echo "where: " . $metadata['base_ark_url'] . "\n";
if (!empty($metadata['issn'])) {
echo "issn: " . $metadata['issn'] . "\n";
}
echo "\n";
// Messages in multiple languages without duplicates
$primary = $metadata['primary_locale'];
$url = $metadata['site_url'];
$messages = [];
// Add primary language message
if ($primary === 'pt_BR') {
$messages[] = "# Se você chegou a esta página por engano, por favor acesse: " . $url;
} elseif ($primary === 'en') {
$messages[] = "# If you reached this page by mistake, please visit: " . $url;
} elseif ($primary === 'es') {
$messages[] = "# Si llegaste a esta página por error, por favor visita: " . $url;
} else {
$messages[] = "# If you reached this page by mistake, please visit: " . $url;
}
// Add Portuguese if primary is not Portuguese
if ($primary !== 'pt_BR') {
$messages[] = "# Se você chegou a esta página por engano, por favor acesse: " . $url;
}
// Add English if primary is not English
if ($primary !== 'en') {
$messages[] = "# If you reached this page by mistake, please visit: " . $url;
}
// Output unique messages (remove duplicates)
$uniqueMessages = array_unique($messages);
foreach ($uniqueMessages as $msg) {
echo $msg . "\n";
}
}
/**
* Get the primary locale of the journal
*
* @param PDO $pdo Database connection
* @param int $contextId Journal ID
* @return string Locale code (e.g., 'pt_BR', 'en', 'es')
*/
function getPrimaryLocale($pdo, $contextId) {
$stmt = $pdo->prepare("
SELECT primary_locale FROM journals WHERE journal_id = ?
LIMIT 1
");
$stmt->execute([$contextId]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
return $result ? $result['primary_locale'] : 'en';
}
/**
* Display error page in both Portuguese and English
*
* @param int $statusCode HTTP status code
* @param string $titleEn English title
* @param string $titlePt Portuguese title
* @param string $messageEn English message
* @param string $messagePt Portuguese message
* @param string $detailsEn English details (optional)
* @param string $detailsPt Portuguese details (optional)
*/
function showErrorPage($statusCode, $titleEn, $titlePt, $messageEn, $messagePt, $detailsEn = '', $detailsPt = '') {
$siteUrl = getSiteBaseUrl();
$pluginUrl = 'https://github.com/lurymorais/ark-plugin';
http_response_code($statusCode);
echo '<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>' . htmlspecialchars($titleEn) . ' / ' . htmlspecialchars($titlePt) . ' - ARK Resolver</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
max-width: 900px;
margin: 40px auto;
padding: 20px;
line-height: 1.6;
background-color: #ffffff;
color: #333333;
}
h1 { font-size: 1.8rem; }
hr { margin: 30px 0; border: none; border-top: 1px solid #cccccc; }
.language-section {
margin: 20px 0;
padding: 20px;
border: 1px solid #e0e0e0;
border-radius: 8px;
}
.language-pt { background-color: #f8f9fa; }
.language-en { background-color: #ffffff; }
.language-label {
font-size: 0.8rem;
text-transform: uppercase;
letter-spacing: 1px;
opacity: 0.7;
margin-bottom: 10px;
}
a { color: #0366d6; text-decoration: none; }
a:hover { text-decoration: underline; }
.identifier {
font-family: monospace;
font-weight: bold;
}
</style>
</head>
<body>
<h1>ARK Resolver</h1>
<div class="language-section language-pt">
<div class="language-label">PORTUGUES</div>
<h2>' . htmlspecialchars($titlePt) . '</h2>
<p>' . str_replace('<strong>', '<span class="identifier">', str_replace('</strong>', '</span>', htmlspecialchars($messagePt))) . '</p>';
if ($detailsPt) {
echo '<p><strong>Detalhe:</strong> ' . htmlspecialchars($detailsPt) . '</p>';
}
echo '
<p><a href="' . htmlspecialchars($siteUrl) . '">Voltar para a pagina inicial</a></p>
</div>
<div class="language-section language-en">
<div class="language-label">ENGLISH</div>
<h2>' . htmlspecialchars($titleEn) . '</h2>
<p>' . str_replace('<strong>', '<span class="identifier">', str_replace('</strong>', '</span>', htmlspecialchars($messageEn))) . '</p>';
if ($detailsEn) {
echo '<p><strong>Details:</strong> ' . htmlspecialchars($detailsEn) . '</p>';
}
echo '
<p><a href="' . htmlspecialchars($siteUrl) . '">Back to homepage</a></p>
</div>
<hr>
<p style="text-align: center;">
<small>
<a href="' . $pluginUrl . '">ARK Plugin on GitHub</a> |
<a href="https://n2t.net/">n2t.net</a>
</small>
</p>
</body>
</html>';
exit;
}
// ============ MAIN EXECUTION ============
// Check parameter first
if (empty($_GET['ark']) && empty($_GET['id'])) {
showErrorPage(
400,
'Missing Parameter',
'Parametro Ausente',
'No ARK identifier was provided.',
'Nenhum identificador ARK foi fornecido.',
'Expected usage: resolver.php?ark=CRL1234-ABCD or resolver.php?ark=CRL1234ABCD',
'Uso esperado: resolver.php?ark=CRL1234-ABCD ou resolver.php?ark=CRL1234ABCD'
);
}
$arkSuffix = $_GET['ark'] ?? $_GET['id'];
$originalInput = $arkSuffix;
// Detect inflection (function called without arguments)
$inflection = getInflection();
// Remove inflection suffixes from ARK value
$arkSuffix = preg_replace('/\?info$/', '', $arkSuffix);
$arkSuffix = preg_replace('/\.info$/', '', $arkSuffix);
$arkSuffix = preg_replace('/\?\?$/', '', $arkSuffix);
$arkSuffix = preg_replace('/\?$/', '', $arkSuffix);
$originalInput = $arkSuffix;
// Clean ARK suffix (remove ark: prefix and shoulder)
$arkSuffix = preg_replace('/^ark:[0-9]+\//', '', $arkSuffix);
$arkSuffix = preg_replace('/^[A-Z]+\//', '', $arkSuffix);
// Length validation
if (strlen($arkSuffix) < 4) {
showErrorPage(
400,
'Invalid ARK Format',
'Formato de ARK Invalido',
'The provided identifier is too short.',
'O identificador fornecido e muito curto.',
'You tried: ' . htmlspecialchars($originalInput) . '. Minimum length is 4 characters.',
'Voce tentou: ' . htmlspecialchars($originalInput) . '. O tamanho minimo e 4 caracteres.'
);
}
if (strlen($arkSuffix) > 50) {
showErrorPage(
400,
'Invalid ARK Format',
'Formato de ARK Invalido',
'The provided identifier is too long.',
'O identificador fornecido e muito longo.',
'You tried: ' . htmlspecialchars($originalInput) . '. Maximum length is 50 characters.',
'Voce tentou: ' . htmlspecialchars($originalInput) . '. O tamanho maximo e 50 caracteres.'
);
}
try {
// Get database configuration
$dbConfig = getDbConfig();
// Build DSN based on driver
$dsn = "";
switch ($dbConfig['driver']) {
case 'mysqli':
case 'mysql':
$dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['name']};charset=utf8";
break;
case 'postgres':
case 'postgresql':
$dsn = "pgsql:host={$dbConfig['host']};dbname={$dbConfig['name']}";
break;
default:
throw new Exception("Unsupported database driver: " . $dbConfig['driver']);
}
// Connect to database
$pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Try with and without hyphen (ARK NAAN format allows both)
$attempts = [$arkSuffix];
if (strpos($arkSuffix, '-') === false && strlen($arkSuffix) >= 8) {
$attempts[] = substr($arkSuffix, 0, -4) . '-' . substr($arkSuffix, -4);
} elseif (strpos($arkSuffix, '-') !== false) {
$attempts[] = str_replace('-', '', $arkSuffix);
}
$result = null;
$objectType = null; // 'publication' or 'issue'
// First, search in publications (articles)
foreach ($attempts as $suffix) {
$stmt = $pdo->prepare("
SELECT ps.publication_id, s.context_id, 'publication' as type
FROM publication_settings ps
JOIN publications p ON ps.publication_id = p.publication_id
JOIN submissions s ON p.submission_id = s.submission_id
WHERE ps.setting_name = 'pub-id::ark'
AND (ps.setting_value = ? OR ps.setting_value LIKE CONCAT('%', ?))
LIMIT 1
");
$stmt->execute([$suffix, $suffix]);
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result = $row;
$objectType = 'publication';
break;
}
}
// If not found in publications, search in issues
if (!$result) {
foreach ($attempts as $suffix) {
$stmt = $pdo->prepare("
SELECT is2.issue_id, i.journal_id as context_id, 'issue' as type
FROM issue_settings is2
JOIN issues i ON is2.issue_id = i.issue_id
WHERE is2.setting_name = 'pub-id::ark'
AND (is2.setting_value = ? OR is2.setting_value LIKE CONCAT('%', ?))
LIMIT 1
");
$stmt->execute([$suffix, $suffix]);
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result = $row;
$objectType = 'issue';
break;
}
}
}
if (!$result) {
showErrorPage(
404,
'ARK Not Found',
'ARK Nao Encontrado',
'The identifier was not found in our database.',
'O identificador nao foi encontrado em nossa base de dados.',
'You tried: ' . htmlspecialchars($originalInput),
'Voce tentou: ' . htmlspecialchars($originalInput)
);
}
// Get journal path
$stmt2 = $pdo->prepare("SELECT path FROM journals WHERE journal_id = ?");
$stmt2->execute([$result['context_id']]);
$journal = $stmt2->fetch(PDO::FETCH_ASSOC);
if (!$journal) {
showErrorPage(
500,
'Journal Error',
'Erro no Periodico',
'Could not identify the journal associated with this ARK.',
'Nao foi possivel identificar o periodico associado a este ARK.',
'Contact the system administrator.',
'Entre em contato com o administrador do sistema.'
);
}
$baseUrl = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
$baseUrl = str_replace('/plugins/pubIds/ark', '', $baseUrl);
$siteBaseUrl = getSiteBaseUrl();
// Check if we need to return ERC metadata
if ($inflection === 'brief' || $inflection === 'full') {
$fullArkResolverUrl = $siteBaseUrl . "/plugins/pubIds/ark/resolver.php?ark=" . urlencode($originalInput);
if ($objectType === 'publication') {
$metadata = getMetadataForERC(
$pdo,
$result['publication_id'],
$result['context_id'],
$originalInput,
$siteBaseUrl,
);
} else {
// For issues, we need a different metadata function
$metadata = getMetadataForIssueERC(
$pdo,
$result['issue_id'],
$result['context_id'],
$originalInput,
$siteBaseUrl,
);
}
if ($inflection === 'brief') {
outputBriefERC($metadata, $originalInput, $fullArkResolverUrl);
} else {
outputFullERC($metadata, $originalInput, $fullArkResolverUrl);
}
exit;
}
// Redirect based on object type
if ($objectType === 'publication') {
// Get friendly URL if exists for article
$stmt3 = $pdo->prepare("
SELECT setting_value FROM publication_settings
WHERE publication_id = ? AND setting_name = 'urlPath'
LIMIT 1
");
$stmt3->execute([$result['publication_id']]);
$urlPath = $stmt3->fetch(PDO::FETCH_ASSOC);
if ($urlPath && !empty($urlPath['setting_value'])) {
$redirectUrl = $baseUrl . "/index.php/{$journal['path']}/article/view/{$urlPath['setting_value']}";
} else {
$redirectUrl = $baseUrl . "/index.php/{$journal['path']}/article/view/{$result['publication_id']}";
}
} else {
// Redirect to issue page - fix double slash issue
$baseUrlClean = rtrim($baseUrl, '/');
$redirectUrl = $baseUrlClean . "/index.php/{$journal['path']}/issue/view/{$result['issue_id']}";
}
header('HTTP/1.1 302 Found');
header('Location: ' . $redirectUrl);
exit;
} catch (PDOException $e) {
error_log("ARK Resolver PDO Error: " . $e->getMessage());
showErrorPage(
500,
'Database Error',
'Erro no Banco de Dados',
'Could not connect to the database.',
'Nao foi possivel conectar ao banco de dados.',
'Error: ' . $e->getMessage(),
'Erro: ' . $e->getMessage()
);
} catch (Exception $e) {
error_log("ARK Resolver Error: " . $e->getMessage());
showErrorPage(
500,
'Internal Error',
'Erro Interno',
'An internal error occurred.',
'Ocorreu um erro interno.',
'Error: ' . $e->getMessage(),
'Erro: ' . $e->getMessage()
);
}
/**
* Get metadata for Issue ERC response
*/
function getMetadataForIssueERC($pdo, $issueId, $contextId, $arkSuffix, $baseUrl) {
$metadata = [];
// Get issue basic info
$stmt = $pdo->prepare("
SELECT i.*, j.primary_locale, j.path as journal_path
FROM issues i
JOIN journals j ON i.journal_id = j.journal_id
WHERE i.issue_id = ?
LIMIT 1
");
$stmt->execute([$issueId]);
$issue = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$issue) {
return $metadata;
}
// Get issue title
$stmt = $pdo->prepare("
SELECT setting_value FROM issue_settings
WHERE issue_id = ? AND setting_name = 'title'
LIMIT 1
");
$stmt->execute([$issueId]);
$title = $stmt->fetch(PDO::FETCH_ASSOC);
// WHO: Use journal name as responsible entity for the issue
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND setting_name = 'name'
LIMIT 1
");
$stmt->execute([$contextId]);
$journalName = $stmt->fetch(PDO::FETCH_ASSOC);
$journalNameValue = $journalName ? html_entity_decode($journalName['setting_value'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : 'Journal';
$metadata['who'] = $journalNameValue . ' (Editorial)';
$metadata['what'] = $title ? html_entity_decode($title['setting_value'], ENT_QUOTES | ENT_HTML5, 'UTF-8') : 'Issue ' . $issueId;
// WHEN: Use issue publication date
$metadata['when'] = '';
if (!empty($issue['date_published'])) {
$metadata['when'] = date('Ymd', strtotime($issue['date_published']));
} else {
$metadata['when'] = date('Ymd');
}
// WHO_JOURNAL: Journal name
$metadata['who_journal'] = $journalNameValue;
// ISSN
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND (setting_name = 'printIssn' OR setting_name = 'onlineIssn')
LIMIT 1
");
$stmt->execute([$contextId]);
$issn = $stmt->fetch(PDO::FETCH_ASSOC);
$metadata['issn'] = $issn ? $issn['setting_value'] : '';
// Get the full ARK identifier from database
$stmt = $pdo->prepare("
SELECT setting_value FROM issue_settings
WHERE issue_id = ? AND setting_name = 'pub-id::ark'
LIMIT 1
");
$stmt->execute([$issueId]);
$arkFull = $stmt->fetch(PDO::FETCH_ASSOC);
$fullArkId = $arkFull ? $arkFull['setting_value'] : '';
// Resolver configuration
$resolverType = 'n2t';
$customResolver = null;
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND setting_name = 'resolverType'
LIMIT 1
");
$stmt->execute([$contextId]);
$resolverTypeRow = $stmt->fetch(PDO::FETCH_ASSOC);
$resolverType = $resolverTypeRow ? $resolverTypeRow['setting_value'] : 'n2t';
if ($resolverType === 'custom') {
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND setting_name = 'arkResolver'
LIMIT 1
");
$stmt->execute([$contextId]);
$customResolverRow = $stmt->fetch(PDO::FETCH_ASSOC);
$customResolver = $customResolverRow ? $customResolverRow['setting_value'] : null;
}
// First 'where' field: Complete ARK URL
if ($resolverType === 'custom' && !empty($customResolver)) {
$baseResolver = rtrim($customResolver, '/');
$metadata['ark_url'] = $baseResolver . '/' . ltrim($fullArkId, '/');
} else {
$metadata['ark_url'] = 'https://n2t.net/' . ltrim($fullArkId, '/');
}
// Second 'where' field (erc-support): Base ARK URL up to NAAN
$naan = '';
if (!empty($fullArkId)) {
if (preg_match('/ark:([0-9]+)/', $fullArkId, $matches)) {
$naan = $matches[1];
}
}
if ($resolverType === 'custom' && !empty($customResolver)) {
$baseResolver = rtrim($customResolver, '/');
$metadata['base_ark_url'] = $baseResolver . '/ark:' . $naan . '/';
} else {
$metadata['base_ark_url'] = 'https://n2t.net/ark:' . $naan . '/';
}
// SUPPORT_WHEN: Use implementation date from settings
$stmt = $pdo->prepare("
SELECT setting_value FROM journal_settings
WHERE journal_id = ? AND setting_name = 'arkImplementationDate' AND (locale = '' OR locale IS NULL)
LIMIT 1
");
$stmt->execute([$contextId]);
$implDate = $stmt->fetch(PDO::FETCH_ASSOC);
$metadata['support_when'] = ($implDate && !empty($implDate['setting_value'])) ? $implDate['setting_value'] : $metadata['when'];
$metadata['primary_locale'] = $issue['primary_locale'] ?? 'en';
$metadata['site_url'] = rtrim($baseUrl, '/');
$metadata['journal_path'] = $issue['journal_path'] ?? '';
return $metadata;
}