forked from sean-xiao-zhao7/pkp-orcidprofile
-
Notifications
You must be signed in to change notification settings - Fork 51
/
OrcidProfilePlugin.php
executable file
·1585 lines (1418 loc) · 60.5 KB
/
OrcidProfilePlugin.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
/**
* @file OrcidProfilePlugin.php
*
* Copyright (c) 2015-2022 University of Pittsburgh
* Copyright (c) 2014-2022 Simon Fraser University
* Copyright (c) 2003-2022 John Willinsky
* Distributed under the GNU GPL v3. For full terms see the file docs/COPYING.
*
* @class OrcidProfilePlugin
*
* @ingroup plugins_generic_orcidProfile
*
* @brief ORCID Profile plugin class
*/
namespace APP\plugins\generic\orcidProfile;
use APP\issue\Issue;
use APP\journal\Journal;
use APP\plugins\generic\citationStyleLanguage\CitationStyleLanguagePlugin;
use APP\publication\Publication;
use APP\author\Author;
use APP\controllers\grid\users\author\form\AuthorForm;
use APP\core\Application;
use APP\core\Request;
use APP\core\Services;
use APP\decision\Decision;
use APP\facades\Repo;
use APP\plugins\generic\orcidProfile\classes\form\OrcidProfileSettingsForm;
use APP\plugins\generic\orcidProfile\classes\form\OrcidProfileStatusForm;
use APP\plugins\generic\orcidProfile\classes\OrcidValidator;
use APP\plugins\generic\orcidProfile\mailables\OrcidCollectAuthorId;
use APP\plugins\generic\orcidProfile\mailables\OrcidRequestAuthorAuthorization;
use APP\submission\Submission;
use APP\template\TemplateManager;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Mail;
use PKP\components\forms\FieldOptions;
use PKP\components\forms\FieldText;
use PKP\components\forms\publication\ContributorForm;
use PKP\config\Config;
use PKP\core\Core;
use PKP\core\JSONMessage;
use PKP\core\PKPApplication;
use PKP\facades\Locale;
use PKP\form\Form;
use PKP\install\Installer;
use PKP\linkAction\LinkAction;
use PKP\linkAction\request\AjaxModal;
use PKP\plugins\GenericPlugin;
use PKP\plugins\Hook;
use PKP\plugins\PluginRegistry;
use PKP\services\PKPSchemaService;
use PKP\submission\PKPSubmission;
use PKP\submission\reviewAssignment\ReviewAssignment;
use Sokil\IsoCodes\Database\Countries\Country;
define('ORCID_URL', 'https://orcid.org/');
define('ORCID_URL_SANDBOX', 'https://sandbox.orcid.org/');
define('ORCID_API_URL_PUBLIC', 'https://orcid.org/');
define('ORCID_API_URL_PUBLIC_SANDBOX', 'https://sandbox.orcid.org/');
define('ORCID_API_URL_MEMBER', 'https://api.orcid.org/');
define('ORCID_API_URL_MEMBER_SANDBOX', 'https://api.sandbox.orcid.org/');
define('ORCID_API_VERSION_URL', 'v3.0/');
define('ORCID_API_SCOPE_PUBLIC', '/authenticate');
define('ORCID_API_SCOPE_MEMBER', '/activities/update');
define('OAUTH_TOKEN_URL', 'oauth/token');
define('ORCID_EMPLOYMENTS_URL', 'employments');
define('ORCID_PROFILE_URL', 'person');
define('ORCID_EMAIL_URL', 'email');
define('ORCID_WORK_URL', 'work');
define('ORCID_REVIEW_URL', 'peer-review');
class OrcidProfilePlugin extends GenericPlugin
{
public const PUBID_TO_ORCID_EXT_ID = ['doi' => 'doi', 'other::urn' => 'urn'];
public const USER_GROUP_TO_ORCID_ROLE = ['Author' => 'AUTHOR', 'Translator' => 'CHAIR_OR_TRANSLATOR', 'Journal manager' => 'AUTHOR'];
private $currentContextId;
/**
* @copydoc Plugin::register()
*
* @param null|mixed $mainContextId
*/
public function register($category, $path, $mainContextId = null)
{
$success = parent::register($category, $path, $mainContextId);
if (Application::isUnderMaintenance()) {
return true;
}
if (!$success || !$this->getEnabled($mainContextId)) {
return $success;
}
$contextId = $mainContextId ?? $this->getCurrentContextId();
$validator = new OrcidValidator($this);
$clientId = $this->getSetting($contextId, 'orcidClientId');
$clientSecret = $this->getSetting($contextId, 'orcidClientSecret');
if (!$validator->validateClientSecret($clientSecret) || !$validator->validateClientId($clientId)) {
error_log(new Exception('The ORCID plugin is enabled, but its settings are invalid. In order to fix, access the plugin settings and try to save the form'));
return $success;
}
Hook::add('ArticleHandler::view', $this->submissionView(...));
Hook::add('PreprintHandler::view', $this->submissionView(...));
// Insert the OrcidProfileHandler to handle ORCID redirects
Hook::add('LoadHandler', $this->setupCallbackHandler(...));
// Register callback for Smarty filters; add CSS
Hook::add('TemplateManager::display', $this->handleTemplateDisplay(...));
// Add "Connect ORCID" button to PublicProfileForm
Hook::add('User::PublicProfile::AdditionalItems', $this->handleUserPublicProfileDisplay(...));
// Display additional ORCID access information and checkbox to send e-mail to authors in the AuthorForm
Hook::add('authorform::display', $this->handleFormDisplay(...));
// Send email to author, if the added checkbox was ticked
Hook::add('authorform::execute', $this->handleAuthorFormExecute(...));
// Handle ORCID on user registration
Hook::add('registrationform::execute', $this->collectUserOrcidId(...));
// Send emails to authors without ORCID id upon submission
//TODO Hook::add('submissionsubmitstep3form::execute', $this->handleSubmissionSubmitStep3FormExecute(...));
// Send emails to authors without authorised ORCID access on promoting a submission to copy editing. Not included in OPS.
if ($this->getSetting($contextId, 'sendMailToAuthorsOnPublication')) {
Hook::add('EditorAction::recordDecision', $this->handleEditorAction(...));
}
Hook::add('Publication::publish', $this->handlePublicationStatusChange(...));
Hook::add('ThankReviewerForm::thankReviewer', $this->handleThankReviewer(...));
Hook::add('Mailer::Mailables', $this->addMailable(...));
Hook::add('Author::edit', $this->handleAuthorFormExecute(...));
Hook::add('Form::config::before', $this->addOrcidFormFields(...));
Hook::add('Installer::postInstall', $this->updateSchema(...));
Hook::add('Publication::validatePublish', $this->validate(...));
return $success;
}
/**
* Load a setting for a specific journal or load it from the config.inc.php if it is specified there.
*
* @param int $contextId The id of the journal from which the plugin settings should be loaded.
* @param string $name Name of the setting.
*
* @return mixed The setting value, either from the database for this context
* or from the global configuration file.
*/
public function getSetting($contextId, $name)
{
switch ($name) {
case 'orcidProfileAPIPath':
$config_value = Config::getVar('orcid', 'api_url');
break;
case 'orcidClientId':
$config_value = Config::getVar('orcid', 'client_id');
break;
case 'orcidClientSecret':
$config_value = Config::getVar('orcid', 'client_secret');
break;
case 'country':
$config_value = Config::getVar('orcid', 'country');
break;
case 'city':
$config_value = Config::getVar('orcid', 'city');
break;
default:
return parent::getSetting($contextId, $name);
}
return $config_value ?: parent::getSetting($contextId, $name);
}
/**
* adds orcid form fields.
*
* @param string $hookName
* @param Form $form
*/
public function addOrcidFormFields($hookName, $form): bool
{
if (!$form instanceof ContributorForm) {
return Hook::CONTINUE;
}
$form->removeField('orcid');
$form->addField(new FieldText('orcid', [
'label' => __('user.orcid'),
'optIntoEdit' => true,
'optIntoEditLabel' => __('common.override'),
'tooltip' => __('plugins.generic.orcidProfile.about.orcidExplanation'),
]), [FIELD_POSITION_AFTER, 'url']);
$form->addField(new FieldOptions('requestOrcidAuthorization', [
'label' => __('plugins.generic.orcidProfile.verify.title'),
'options' => [
[
'label' => __('plugins.generic.orcidProfile.author.requestAuthorization'),
'value' > false,
]
]
]), [FIELD_POSITION_AFTER, 'orcid']);
$form->addField(
new FieldOptions('deleteORCID', [
'label' => __('plugins.generic.orcidProfile.displayName'),
'options' => [
[
'label' => __('plugins.generic.orcidProfile.author.deleteORCID'),
'value' > false,
]
],
'showWhen' => 'orcid',
]),
[FIELD_POSITION_AFTER, 'orcid']
);
return Hook::CONTINUE;
}
/**
* @param string $hookName
* @param array $args
*/
public function handleThankReviewer($hookName, $args)
{
$request = PKPApplication::get()->getRequest();
$context = $request->getContext();
$newPublication = & $args[0];
if ($this->isMemberApiEnabled($this->currentContextId)) {
if ($this->getSetting($context->getId(), 'country') && $this->getSetting($context->getId(), 'city')) {
$this->publishReviewerWorkToOrcid($newPublication, $request);
}
}
}
/**
* @return bool True if the ORCID Member API has been selected in this context.
*/
public function isMemberApiEnabled($contextId)
{
$apiUrl = $this->getSetting($contextId, 'orcidProfileAPIPath');
if ($apiUrl === ORCID_API_URL_MEMBER || $apiUrl === ORCID_API_URL_MEMBER_SANDBOX) {
return true;
} else {
return false;
}
}
/**
* @return JSONMessage|null
*/
public function publishReviewerWorkToOrcid(Submission $submission, Request $request)
{
$context = $request->getContext();
$requestVars = $request->getUserVars();
$reviewAssignmentId = $requestVars['reviewAssignmentId'];
if (isset($reviewAssignmentId)) {
$review = Repo::reviewAssignment()->get($reviewAssignmentId, $submission->getId());
$reviewer = Repo::user()->get($review->getData('reviewerId'));
if ($reviewer->getOrcid() && $reviewer->getData('orcidAccessToken')) {
$orcidAccessExpiresOn = Carbon::parse($reviewer->getData('orcidAccessExpiresOn'));
if ($orcidAccessExpiresOn->isFuture()) {
# Extract only the ORCID from the stored ORCID uri
$orcid = basename(parse_url($reviewer->getOrcid(), PHP_URL_PATH));
$orcidReview = $this->buildOrcidReview($submission, $review, $request);
$uri = $this->getSetting($context->getId(), 'orcidProfileAPIPath') . ORCID_API_VERSION_URL . $orcid . '/' . ORCID_REVIEW_URL;
$method = 'POST';
if ($putCode = $reviewer->getData('orcidReviewPutCode')) {
$uri .= '/' . $putCode;
$method = 'PUT';
$orcidReview['put-code'] = $putCode;
}
$headers = [
'Content-Type' => ' application/vnd.orcid+json; qs=4',
'Accept' => 'application/json',
'Authorization' => 'Bearer ' . $reviewer->getData('orcidAccessToken')
];
$httpClient = Application::get()->getHttpClient();
try {
$response = $httpClient->request(
$method,
$uri,
[
'headers' => $headers,
'json' => $orcidReview,
'allow_redirects' => ['strict' => true],
]
);
} catch (ClientException $exception) {
$reason = $exception->getResponse()->getBody();
$this->logInfo("Publication fail: {$reason}");
return new JSONMessage(false);
}
$httpStatus = $response->getStatusCode();
$this->logInfo("Response status: {$httpStatus}");
$responseHeaders = $response->getHeaders();
switch ($httpStatus) {
case 200:
$this->logInfo("Review updated in profile, putCode: {$putCode}");
break;
case 201:
$location = $responseHeaders['Location'][0];
// Extract the ORCID work put code for updates/deletion.
$putCode = basename(parse_url($location, PHP_URL_PATH));
$reviewer->setData('orcidReviewPutCode', $putCode);
Repo::user()->edit($reviewer, ['orcidReviewPutCode']);
$this->logInfo("Review added to profile, putCode: {$putCode}");
break;
default:
$this->logError("Unexpected status {$httpStatus} response, body: {$responseHeaders}");
}
}
}
}
}
public function buildOrcidReview($submission, $review, $request, $issue = null)
{
$publicationUrl = $request->getDispatcher()->url($request, PKPApplication::ROUTE_PAGE, null, 'article', 'view', $submission->getId());
$context = $request->getContext();
$publicationLocale = ($submission->getData('locale')) ? $submission->getData('locale') : 'en';
$pubIdPlugins = PluginRegistry::loadCategory('pubIds', true, $context->getId()); // DO not remove
$supportedSubmissionLocales = $context->getSupportedSubmissionLocales();
if (!empty($review->getData('dateCompleted')) && $context->getData('onlineIssn')) {
$reviewCompletionDate = Carbon::parse($review->getData('dateCompleted'));
$orcidReview = [
'reviewer-role' => 'reviewer',
'review-type' => 'review',
'review-completion-date' => [
'year' => [
'value' => $reviewCompletionDate->format('Y')
],
'month' => [
'value' => $reviewCompletionDate->format('m')
],
'day' => [
'value' => $reviewCompletionDate->format('d')
]
],
'review-group-id' => 'issn:' . $context->getData('onlineIssn'),
'convening-organization' => [
'name' => $context->getData('publisherInstitution'),
'address' => [
'city' => $this->getSetting($context->getId(), 'city'),
'country' => $this->getSetting($context->getId(), 'country')
]
],
'review-identifiers' => ['external-id' => [
[
'external-id-type' => 'source-work-id',
'external-id-value' => $review->getData('reviewRoundId'),
'external-id-relationship' => 'part-of']
]]
];
if ($review->getReviewMethod() == ReviewAssignment::SUBMISSION_REVIEW_METHOD_OPEN) {
$orcidReview['subject-url'] = ['value' => $publicationUrl];
$orcidReview['review-url'] = ['value' => $publicationUrl];
$orcidReview['subject-type'] = 'journal-article';
$orcidReview['subject-name'] = [
'title' => ['value' => $submission->getCurrentPublication()->getLocalizedData('title') ?? '']
];
if (!empty($submission->getData('pub-id::doi'))) {
$externalIds = [
'external-id-type' => 'doi',
'external-id-value' => $submission->getData('pub-id::doi'),
'external-id-url' => [
'value' => 'https://doi.org/' . $submission->getData('pub-id::doi')
],
'external-id-relationship' => 'self'
];
$orcidReview['subject-external-identifier'] = $externalIds;
}
}
$translatedTitleAvailable = false;
foreach ($supportedSubmissionLocales as $defaultLanguage) {
if ($defaultLanguage !== $publicationLocale) {
$iso2LanguageCode = substr($defaultLanguage, 0, 2);
$defaultTitle = $submission->getLocalizedData($iso2LanguageCode);
if (strlen($defaultTitle) > 0 && !$translatedTitleAvailable) {
$orcidReview['subject-name']['translated-title'] = ['value' => $defaultTitle, 'language-code' => $iso2LanguageCode];
$translatedTitleAvailable = true;
}
}
}
return $orcidReview;
}
}
/**
* Write info message to log.
*
* @param string $message Message to write
*/
public function logInfo($message)
{
if ($this->getSetting($this->currentContextId, 'logLevel') === 'ERROR') {
return;
}
self::writeLog($message, 'INFO');
}
/**
* Write error message to log.
*
* @param string $message Message to write
*/
public function logError($message)
{
if ($this->getSetting($this->currentContextId, 'logLevel') === 'ERROR') {
return;
}
self::writeLog($message, 'ERROR');
}
/**
* Write a message with specified level to log
*
* @param string $message Message to write
* @param string $level Error level to add to message
*/
private static function writeLog($message, $level)
{
$fineStamp = date('Y-m-d H:i:s') . substr(microtime(), 1, 4);
error_log("{$fineStamp} {$level} {$message}\n", 3, self::logFilePath());
}
/**
* @return string Path to a custom ORCID log file.
*/
public static function logFilePath()
{
return Config::getVar('files', 'files_dir') . '/orcid.log';
}
/**
* Hook callback: register pages for each sushi-lite method
* This URL is of the form: orcidapi/{$orcidrequest}
*
* @see PKPPageRouter::route()
*/
public function setupCallbackHandler($hookName, $params)
{
$page = $params[0];
if ($this->getEnabled() && $page == 'orcidapi') {
define('HANDLER_CLASS', OrcidProfileHandler::class);
return true;
}
return false;
}
/**
* Check if there exist a valid orcid configuration section in the global config.inc.php of OJS.
*
* @return boolean True, if the config file has api_url, client_id and client_secret set in an [orcid] section
*/
public function isGloballyConfigured()
{
$apiUrl = Config::getVar('orcid', 'api_url');
$clientId = Config::getVar('orcid', 'client_id');
$clientSecret = Config::getVar('orcid', 'client_secret');
return isset($apiUrl) && trim($apiUrl) && isset($clientId) && trim($clientId) &&
isset($clientSecret) && trim($clientSecret);
}
/**
* Hook callback to handle form display.
* Registers output filter for public user profile and author form.
*
* @param string $hookName
* @param Form[] $args
*
* @return bool
*
* @see Form::display()
*
*/
public function handleFormDisplay($hookName, $args)
{
//TODO
$request = Application::get()->getRequest();
$templateMgr = TemplateManager::getManager($request);
switch ($hookName) {
case 'authorform::display':
/** @var AuthorForm */
$authorForm = &$args[0];
$author = $authorForm->getAuthor();
if ($author) {
$authenticated = !empty($author->getData('orcidAccessToken'));
$templateMgr->assign(
[
'orcidAccessToken' => $author->getData('orcidAccessToken'),
'orcidAccessScope' => $author->getData('orcidAccessScope'),
'orcidAccessExpiresOn' => $author->getData('orcidAccessExpiresOn'),
'orcidAccessDenied' => $author->getData('orcidAccessDenied'),
'orcidAuthenticated' => $authenticated
]
);
}
$templateMgr->registerFilter('output', $this->authorFormFilter(...));
break;
}
return false;
}
/**
* Hook callback: register output filter for user registration and article display.
*
* @param string $hookName
* @param array $args
*
* @return bool
*
* @see TemplateManager::display()
*
*/
public function handleTemplateDisplay($hookName, $args)
{
//TODO orcid
$templateMgr = &$args[0];
$template = &$args[1];
$request = Application::get()->getRequest();
// Assign our private stylesheet, for front and back ends.
$templateMgr->addStyleSheet(
'orcidProfile',
$request->getBaseUrl() . '/' . $this->getStyleSheet(),
[
'contexts' => ['frontend', 'backend']
]
);
switch ($template) {
case 'frontend/pages/userRegister.tpl':
$templateMgr->registerFilter('output', $this->registrationFilter(...));
break;
}
return false;
}
/**
* Return the location of the plugin's CSS file
*
* @return string
*/
public function getStyleSheet()
{
return $this->getPluginPath() . '/css/orcidProfile.css';
}
public function isSandbox()
{
$apiUrl = $this->getSetting($this->getCurrentContextId(), 'orcidProfileAPIPath');
return ($apiUrl == ORCID_API_URL_MEMBER_SANDBOX);
}
/**
* Output filter adds ORCiD interaction to registration form.
*
* @param string $output
* @param TemplateManager $templateMgr
*
* @return string
*/
public function registrationFilter($output, $templateMgr)
{
if (preg_match('/<form[^>]+id="register"[^>]+>/', $output, $matches, PREG_OFFSET_CAPTURE)) {
$match = $matches[0][0];
$offset = $matches[0][1];
$targetOp = 'register';
$templateMgr->assign([
'targetOp' => $targetOp,
'orcidUrl' => $this->getOrcidUrl(),
'orcidOAuthUrl' => $this->buildOAuthUrl('orcidAuthorize', ['targetOp' => $targetOp]),
'orcidIcon' => $this->getIcon(),
]);
$newOutput = substr($output, 0, $offset + strlen($match));
$newOutput .= $templateMgr->fetch($this->getTemplateResource('orcidProfile.tpl'));
$newOutput .= substr($output, $offset + strlen($match));
$output = $newOutput;
$templateMgr->unregisterFilter('output', $this->registrationFilter(...));
}
return $output;
}
/**
* Return the ORCID website url (prod or sandbox) based on the current API configuration
*
* @return string
*/
public function getOrcidUrl()
{
$request = Application::get()->getRequest();
$context = $request->getContext();
$contextId = ($context == null) ? 0 : $context->getId();
$apiPath = $this->getSetting($contextId, 'orcidProfileAPIPath');
return in_array($apiPath, [ORCID_API_URL_PUBLIC, ORCID_API_URL_MEMBER]) ? ORCID_URL : ORCID_URL_SANDBOX;
}
/**
* Return an ORCID OAuth authorization link with
*
* @param string $handlerMethod containting a valid method of the OrcidProfileHandler
* @param array $redirectParams associative array with additional request parameters for the redirect URL
*/
public function buildOAuthUrl($handlerMethod, $redirectParams)
{
$request = Application::get()->getRequest();
$context = $request->getContext();
// This should only ever happen within a context, never site-wide.
assert($context != null);
$contextId = $context->getId();
if ($this->isMemberApiEnabled($contextId)) {
$scope = ORCID_API_SCOPE_MEMBER;
} else {
$scope = ORCID_API_SCOPE_PUBLIC;
}
// We need to construct a page url, but the request is using the component router.
// Use the Dispatcher to construct the url and set the page router.
$redirectUrl = $request->getDispatcher()->url(
$request,
Application::ROUTE_PAGE,
null,
'orcidapi',
$handlerMethod,
null,
$redirectParams
);
return $this->getOauthPath() . 'authorize?' . http_build_query(
[
'client_id' => $this->getSetting($contextId, 'orcidClientId'),
'response_type' => 'code',
'scope' => $scope,
'redirect_uri' => $redirectUrl]
);
}
/**
* Return the OAUTH path (prod or sandbox) based on the current API configuration
*
* @return string
*/
public function getOauthPath()
{
return $this->getOrcidUrl() . 'oauth/';
}
/**
* Return a string of the ORCiD SVG icon
*
* @return string
*/
public function getIcon()
{
$path = Core::getBaseDir() . '/' . $this->getPluginPath() . '/templates/images/orcid.svg';
return file_exists($path) ? file_get_contents($path) : '';
}
/**
* Renders additional content for the PublicProfileForm.
*
* Called by @param string $output
*
*
* @return bool
*
* @see lib/pkp/templates/user/publicProfileForm.tpl
*
*/
public function handleUserPublicProfileDisplay($hookName, $params)
{
$templateMgr = &$params[1];
$output = &$params[2];
$request = Application::get()->getRequest();
$context = $request->getContext();
$userId = $request->getUser()->getId();
$user = Repo::user()->get($userId);
$contextId = ($context == null) ? 0 : $context->getId();
$targetOp = 'profile';
$templateMgr->assign(
[
'targetOp' => $targetOp,
'orcidUrl' => $this->getOrcidUrl(),
'orcidOAuthUrl' => $this->buildOAuthUrl('orcidAuthorize', ['targetOp' => $targetOp]),
'orcidClientId' => $this->getSetting($contextId, 'orcidClientId'),
'orcidIcon' => $this->getIcon(),
'orcidAuthenticated' => !empty($user->getData('orcidAccessToken')),
]
);
$output = $templateMgr->fetch($this->getTemplateResource('orcidProfile.tpl'));
return true;
}
/**
* handleAuthorFormExecute sends an e-mail to the author if a specific checkbox was ticked in the author form.
*
* @param string $hookname
* @param AuthorForm[] $args
*
* @see AuthorForm::execute() The function calling the hook.
*
*/
public function handleAuthorFormExecute($hookname, $args)
{
if (count($args) == 3) {
/** @var Author */
$author = &$args[0];
$values = $args[2];
if ($author && $values['requestOrcidAuthorization']) {
$this->sendAuthorMail($author);
}
if ($author && $values['deleteORCID']) {
$author->setOrcid(null);
$this->removeOrcidAccessToken($author, false);
}
}
}
/**
* Send mail with ORCID authorization link to the e-mail address of the supplied Author object.
*
* @param Author $author
* @param bool $updateAuthor If true update the author fields in the database.
* Use this only if not called from a function, which does this anyway.
*/
public function sendAuthorMail($author, $updateAuthor = false)
{
$request = Application::get()->getRequest();
$context = $request->getContext();
// This should only ever happen within a context, never site-wide.
if ($context != null) {
$contextId = $context->getId();
$publicationId = $author->getData('publicationId');
$publication = Repo::publication()->get($publicationId);
$submission = Repo::submission()->get($publication->getData('submissionId'));
$emailToken = md5(microtime() . $author->getEmail());
$author->setData('orcidEmailToken', $emailToken);
$oauthUrl = $this->buildOAuthUrl('orcidVerify', ['token' => $emailToken, 'state' => $publicationId]);
if ($this->isMemberApiEnabled($contextId)) {
$mailable = new OrcidRequestAuthorAuthorization($context, $submission, $oauthUrl);
} else {
$mailable = new OrcidCollectAuthorId($context, $submission, $oauthUrl);
}
// Set From to primary journal contact
$mailable->from($context->getData('contactEmail'), $context->getData('contactName'));
// Send to author
$mailable->recipients([$author]);
$emailTemplateKey = $mailable::getEmailTemplateKey();
$emailTemplate = Repo::emailTemplate()->getByKey($contextId, $emailTemplateKey);
$mailable->body($emailTemplate->getLocalizedData('body'))
->subject($emailTemplate->getLocalizedData('subject'));
Mail::send($mailable);
if ($updateAuthor) {
Repo::author()->dao->update($author);
}
}
}
/**
* Remove all data fields, which belong to an ORCID access token from the
* given Author object. Also updates fields in the db.
*
* @param Author $author object with ORCID access token
*/
public function removeOrcidAccessToken($author, $saveAuthor = true)
{
$author->setData('orcidAccessToken', null);
$author->setData('orcidAccessScope', null);
$author->setData('orcidRefreshToken', null);
$author->setData('orcidAccessExpiresOn', null);
$author->setData('orcidSandbox', null);
if ($saveAuthor) {
Repo::author()->dao->update($author);
}
}
/**
* Collect the ORCID when registering a user.
*
* @param string $hookName
* @param array $params
*
* @return bool
*/
public function collectUserOrcidId($hookName, $params)
{
$form = $params[0];
$user = $form->user;
$form->readUserVars(['orcid']);
$user->setOrcid($form->getData('orcid'));
return false;
}
/**
* Output filter adds ORCiD interaction to the 3rd step submission form.
*
*
* @return bool
*/
public function handleSubmissionSubmitStep3FormExecute($hookName, $params)
{
$form = $params[0];
// Have to use global Request access because request is not passed to hook
$publication = Repo::publication()->get($form->submission->getData('currentPublicationId'));
$authors = $publication->getData('authors');
$request = Application::get()->getRequest();
$user = $request->getUser();
$author = $authors->first();
//error_log("OrcidProfilePlugin: authors[0] = " . var_export($authors[0], true));
//error_log("OrcidProfilePlugin: user = " . var_export($user, true));
if ($author?->getOrcid() === $user->getOrcid()) {
// if the author and user share the same ORCID id
// copy the access token from the user
//error_log("OrcidProfilePlugin: user->orcidAccessToken = " . $user->getData('orcidAccessToken'));
$author->setData('orcidAccessToken', $user->getData('orcidAccessToken'));
$author->setData('orcidAccessScope', $user->getData('orcidAccessScope'));
$author->setData('orcidRefreshToken', $user->getData('orcidRefreshToken'));
$author->setData('orcidAccessExpiresOn', $user->getData('orcidAccessExpiresOn'));
$author->setData('orcidSandbox', $user->getData('orcidSandbox'));
Repo::author()->dao->update($author);
//error_log("OrcidProfilePlugin: author = " . var_export($authors[0], true));
}
return false;
}
/**
* Add additional ORCID specific fields to the Author and User objects
*
* @param string $hookName
* @param array $params
*
* @return bool
*/
public function handleAdditionalFieldNames($hookName, $params)
{
$fields = &$params[1];
$fields[] = 'orcidSandbox';
$fields[] = 'orcidAccessToken';
$fields[] = 'orcidAccessScope';
$fields[] = 'orcidRefreshToken';
$fields[] = 'orcidAccessExpiresOn';
$fields[] = 'orcidAccessDenied';
return false;
}
/**
* @copydoc Plugin::getDescription()
*/
public function getDescription()
{
return __('plugins.generic.orcidProfile.description');
}
/**
* @see PKPPlugin::getInstallEmailTemplatesFile()
*/
public function getInstallEmailTemplatesFile()
{
return ($this->getPluginPath() . '/emailTemplates.xml');
}
/**
* Extend the {url ...} smarty to support this plugin.
*/
public function smartyPluginUrl($params, $smarty)
{
$path = [$this->getCategory(), $this->getName()];
if (is_array($params['path'])) {
$params['path'] = array_merge($path, $params['path']);
} elseif (!empty($params['path'])) {
$params['path'] = array_merge($path, [$params['path']]);
} else {
$params['path'] = $path;
}
if (!empty($params['id'])) {
$params['path'] = array_merge($params['path'], [$params['id']]);
unset($params['id']);
}
return $smarty->smartyUrl($params, $smarty);
}
public function submissionView($hookName, $args)
{
$request = $args[0];
$templateMgr = TemplateManager::getManager($request);
$templateMgr->assign(['orcidIcon' => $this->getIcon()]);
}
/**
* @see Plugin::getActions()
*/
public function getActions($request, $actionArgs)
{
$router = $request->getRouter();
return array_merge(
$this->getEnabled() ? [
new LinkAction(
'settings',
new AjaxModal(
$router->url(
$request,
null,
null,
'manage',
null,
[
'verb' => 'settings',
'plugin' => $this->getName(),
'category' => 'generic'
]
),
$this->getDisplayName()
),
__('manager.plugins.settings'),
null
),
new LinkAction(
'status',
new AjaxModal($router->url($request, null, null, 'manage', null, ['verb' => 'status', 'plugin' => $this->getName(), 'category' => 'generic']), $this->getDisplayName()),
__('common.status'),
null
)
] : [],
parent::getActions($request, $actionArgs)
);
}
/**
* @see Plugin::manage()
*/
public function getDisplayName()
{
return __('plugins.generic.orcidProfile.displayName');
}
public function manage($args, $request)
{
$context = $request->getContext();
$contextId = ($context == null) ? 0 : $context->getId();
switch ($request->getUserVar('verb')) {
case 'settings':
$templateMgr = TemplateManager::getManager();
$templateMgr->registerPlugin('function', 'plugin_url', $this->smartyPluginUrl(...));
$templateMgr->assign('orcidApiUrls', [
ORCID_API_URL_PUBLIC => 'plugins.generic.orcidProfile.manager.settings.orcidProfileAPIPath.public',
ORCID_API_URL_PUBLIC_SANDBOX => 'plugins.generic.orcidProfile.manager.settings.orcidProfileAPIPath.publicSandbox',
ORCID_API_URL_MEMBER => 'plugins.generic.orcidProfile.manager.settings.orcidProfileAPIPath.member',
ORCID_API_URL_MEMBER_SANDBOX => 'plugins.generic.orcidProfile.manager.settings.orcidProfileAPIPath.memberSandbox'
]);