/
MyResearchController.php
2378 lines (2213 loc) · 84.3 KB
/
MyResearchController.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
/**
* MyResearch Controller
*
* PHP version 8
*
* Copyright (C) Villanova University 2010.
* Copyright (C) The National Library of Finland 2023.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Controller
* @author Demian Katz <demian.katz@villanova.edu>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
namespace VuFind\Controller;
use Laminas\ServiceManager\ServiceLocatorInterface;
use Laminas\Session\Container;
use Laminas\View\Model\ViewModel;
use VuFind\Controller\Feature\ListItemSelectionTrait;
use VuFind\Exception\Auth as AuthException;
use VuFind\Exception\AuthEmailNotVerified as AuthEmailNotVerifiedException;
use VuFind\Exception\AuthInProgress as AuthInProgressException;
use VuFind\Exception\BadRequest as BadRequestException;
use VuFind\Exception\Forbidden as ForbiddenException;
use VuFind\Exception\ListPermission as ListPermissionException;
use VuFind\Exception\LoginRequired as LoginRequiredException;
use VuFind\Exception\Mail as MailException;
use VuFind\Exception\MissingField as MissingFieldException;
use VuFind\ILS\PaginationHelper;
use VuFind\Mailer\Mailer;
use VuFind\Search\RecommendListener;
use VuFind\Validator\CsrfInterface;
use function count;
use function in_array;
use function intval;
use function is_array;
use function is_object;
/**
* Controller for the user account area.
*
* @category VuFind
* @package Controller
* @author Demian Katz <demian.katz@villanova.edu>
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org Main Site
*/
class MyResearchController extends AbstractBase
{
use Feature\BulkActionControllerTrait;
use Feature\CatchIlsExceptionsTrait;
use \VuFind\ILS\Logic\SummaryTrait;
use ListItemSelectionTrait;
/**
* Configuration loader
*
* @var \VuFind\Config\PluginManager
*/
protected $configLoader;
/**
* Permission that must be granted to access this module (false for no
* restriction, null to use configured default (which is usually the same
* as false)).
*
* For this controller, we default to false rather than null because
* we don't want a default setting to override the controller's accessibility
* and break the login process!
*
* @var string|bool
*/
protected $accessPermission = false;
/**
* Export support class
*
* @var \VuFind\Export
*/
protected $export;
/**
* ILS Pagination Helper
*
* @var PaginationHelper
*/
protected $paginationHelper = null;
/**
* Session container
*
* @var Container
*/
protected $session;
/**
* Constructor
*
* @param ServiceLocatorInterface $sm Service locator
* @param Container $container Session container
* @param \VuFind\Config\PluginManager $configLoader Configuration loader
* @param \VuFind\Export $export Export support class
*/
public function __construct(
ServiceLocatorInterface $sm,
Container $container,
\VuFind\Config\PluginManager $configLoader,
\VuFind\Export $export
) {
parent::__construct($sm);
$this->session = $container;
$this->configLoader = $configLoader;
$this->export = $export;
}
/**
* Process an authentication error.
*
* @param AuthException $e Exception to process.
*
* @return void
*/
protected function processAuthenticationException(AuthException $e)
{
$msg = $e->getMessage();
if ($e instanceof AuthInProgressException) {
$this->flashMessenger()->addSuccessMessage($msg);
return;
}
if ($e instanceof AuthEmailNotVerifiedException) {
$this->sendFirstVerificationEmail($e->user);
if ($msg == 'authentication_error_email_not_verified_html') {
$this->getUserVerificationContainer()->user = $e->user->username;
$url = $this->url()->fromRoute('myresearch-emailnotverified')
. '?reverify=true';
$msg = [
'html' => true,
'msg' => $msg,
'tokens' => ['%%url%%' => $url],
];
}
}
// If a Shibboleth-style login has failed and the user just logged
// out, we need to override the error message with a more relevant
// one:
if (
$msg == 'authentication_error_admin'
&& $this->getAuthManager()->userHasLoggedOut()
&& $this->getSessionInitiator()
) {
$msg = 'authentication_error_loggedout';
}
$this->flashMessenger()->addMessage($msg, 'error');
}
/**
* Maintaining this method for backwards compatibility;
* logic moved to parent and method re-named
*
* @return void
*/
protected function storeRefererForPostLoginRedirect()
{
$this->setFollowupUrlToReferer();
}
/**
* Prepare and direct the home page where it needs to go
*
* @return mixed
*/
public function homeAction()
{
// Process login request, if necessary (either because a form has been
// submitted or because we're using an external login provider):
if (
$this->params()->fromPost('processLogin')
|| $this->getSessionInitiator()
|| $this->params()->fromPost('auth_method')
|| $this->params()->fromQuery('auth_method')
) {
try {
if (!$this->getAuthManager()->getIdentity()) {
$this->getAuthManager()->login($this->getRequest());
// Return early to avoid unnecessary processing if we are being
// called from login lightbox and don't have a followup action or
// followup is set to referrer.
if (
$this->params()->fromPost('processLogin')
&& $this->inLightbox()
&& (!$this->hasFollowupUrl()
|| $this->followup()->retrieve('isReferrer') === true)
) {
$this->clearFollowupUrl();
return $this->getRefreshResponse();
}
}
} catch (AuthException $e) {
$this->processAuthenticationException($e);
}
}
// Not logged in? Force user to log in:
if (!$this->getAuthManager()->getIdentity()) {
if (
$this->followup()->retrieve('lightboxParent')
&& $url = $this->getAndClearFollowupUrl(true)
) {
return $this->redirect()->toUrl($url);
}
// Allow bypassing of post-login redirect
if ($this->params()->fromQuery('redirect', true)) {
$this->setFollowupUrlToReferer();
}
return $this->forwardTo('MyResearch', 'Login');
}
// Logged in? Forward user to followup action
// or default action (if no followup provided):
if ($url = $this->getAndClearFollowupUrl(true)) {
return $this->redirect()->toUrl($url);
}
$config = $this->getConfig();
$page = $config->Site->defaultAccountPage ?? 'Favorites';
// Default to search history if favorites are disabled:
if ($page == 'Favorites' && !$this->listsEnabled()) {
return $this->forwardTo('Search', 'History');
}
return $this->forwardTo('MyResearch', $page);
}
/**
* "Create account" action
*
* @return mixed
*/
public function accountAction()
{
// If the user is already logged in, don't let them create an account:
if ($this->getAuthManager()->getIdentity()) {
return $this->redirect()->toRoute('myresearch-home');
}
// If authentication mechanism does not support account creation, send
// the user away!
$method = trim($this->params()->fromQuery('auth_method'));
if (!$this->getAuthManager()->supportsCreation($method)) {
return $this->forwardTo('MyResearch', 'Home');
}
// If there's already a followup url, keep it; otherwise set one.
if (!$this->hasFollowupUrl()) {
$this->setFollowupUrlToReferer();
}
// Make view
$view = $this->createViewModel();
// Username policy
$view->usernamePolicy = $this->getAuthManager()->getUsernamePolicy($method);
// Password policy
$view->passwordPolicy = $this->getAuthManager()->getPasswordPolicy($method);
// Set up Captcha
$view->useCaptcha = $this->captcha()->active('newAccount');
// Pass request to view so we can repopulate user parameters in form:
$view->request = $this->getRequest()->getPost();
// Process request, if necessary:
if ($this->formWasSubmitted(useCaptcha: $view->useCaptcha)) {
try {
$this->getAuthManager()->create($this->getRequest());
return $this->forwardTo('MyResearch', 'Home');
} catch (AuthEmailNotVerifiedException $e) {
$this->sendFirstVerificationEmail($e->user);
return $this->redirect()->toRoute('myresearch-emailnotverified');
} catch (AuthException $e) {
$this->flashMessenger()->addMessage($e->getMessage(), 'error');
}
} else {
// If we are not processing a submission, we need to simply display
// an empty form. In case ChoiceAuth is being used, we may need to
// override the active authentication method based on request
// parameters to ensure display of the appropriate template.
$this->setUpAuthenticationFromRequest();
}
return $view;
}
/**
* Login Action
*
* @return mixed
*/
public function loginAction()
{
// If this authentication method doesn't use a VuFind-generated login
// form, force it through:
if ($this->getSessionInitiator()) {
// Don't get stuck in an infinite loop -- if processLogin is already
// set, it probably means Home action is forwarding back here to
// report an error!
//
// Also don't attempt to process a login that hasn't happened yet;
// if we've just been forced here from another page, we need the user
// to click the session initiator link before anything can happen.
if (
!$this->params()->fromPost('processLogin', false)
&& !$this->params()->fromPost('forcingLogin', false)
) {
$this->getRequest()->getPost()->set('processLogin', true);
return $this->forwardTo('MyResearch', 'Home');
}
}
// Make request available to view for form updating:
$view = $this->createViewModel();
$view->request = $this->getRequest()->getPost();
return $view;
}
/**
* User login action -- clear any previous follow-up information prior to
* triggering a login process. This is used for explicit login links within
* the UI to differentiate them from contextual login links that are triggered
* by attempting to access protected actions.
*
* @return mixed
*/
public function userloginAction()
{
// Don't log in if already logged in!
if ($this->getAuthManager()->getIdentity()) {
return $this->inLightbox() // different behavior for lightbox context
? $this->getRefreshResponse()
: $this->redirect()->toRoute('home');
}
$this->clearFollowupUrl();
// Set followup with the isReferrer flag so that the post-login process
// can decide whether to use it:
$this->setFollowupUrlToReferer(true, ['isReferrer' => true]);
if ($si = $this->getSessionInitiator()) {
return $this->redirect()->toUrl($si);
}
return $this->forwardTo('MyResearch', 'Login');
}
/**
* Complete login - perform a user login followed by a catalog login.
*
* @return mixed
*/
public function completeLoginAction()
{
if (!$this->getAuthManager()->getIdentity()) {
return $this->forceLogin('');
}
if (!is_array($patron = $this->catalogLogin())) {
return $patron;
}
return $this->inLightbox()
? $this->getRefreshResponse()
: $this->redirect()->toRoute('home');
}
/**
* Logout Action
*
* @return mixed
*/
public function logoutAction()
{
$config = $this->getConfig();
if (!empty($config->Site->logOutRoute)) {
$logoutTarget = $this->getServerUrl($config->Site->logOutRoute);
} else {
$logoutTarget = $this->getRequest()->getServer()->get('HTTP_REFERER');
if (empty($logoutTarget) || !$this->isLocalUrl($logoutTarget)) {
$logoutTarget = $this->getServerUrl('home');
}
// If there is an auth_method parameter in the query, we should strip
// it out. Otherwise, the user may get stuck in an infinite loop of
// logging out and getting logged back in when using environment-based
// authentication methods like Shibboleth.
$logoutTarget = preg_replace(
'/([?&])auth_method=[^&]*&?/',
'$1',
$logoutTarget
);
$logoutTarget = rtrim($logoutTarget, '?');
// Another special case: if logging out will send the user back to
// the MyResearch home action, instead send them all the way to
// VuFind home. Otherwise, they might get logged back in again,
// which is confusing. Even in the best scenario, they'll just end
// up on a login screen, which is not helpful.
if ($logoutTarget == $this->getServerUrl('myresearch-home')) {
$logoutTarget = $this->getServerUrl('home');
}
}
return $this->redirect()
->toUrl($this->getAuthManager()->logout($logoutTarget));
}
/**
* Get a search row, but throw an exception if it is not owned by the specified
* user or current active session.
*
* @param int $searchId ID of search row
* @param int $userId ID of active user
*
* @throws ForbiddenException
* @return \VuFind\Db\Row\Search
*/
protected function getSearchRowSecurely($searchId, $userId)
{
$searchTable = $this->getTable('Search');
$sessId = $this->serviceLocator
->get(\Laminas\Session\SessionManager::class)->getId();
$search = $searchTable->getOwnedRowById($searchId, $sessId, $userId);
if (empty($search)) {
throw new ForbiddenException('Access denied.');
}
return $search;
}
/**
* Support method for savesearchAction(): set the saved flag in a secure
* fashion, throwing an exception if somebody attempts something invalid.
*
* @param int $searchId The search ID to save/unsave
* @param bool $saved The new desired state of the saved flag
* @param int $userId The user ID requesting the change
*
* @throws \Exception
* @return void
*/
protected function setSavedFlagSecurely($searchId, $saved, $userId)
{
$row = $this->getSearchRowSecurely($searchId, $userId);
$row->saved = $saved ? 1 : 0;
if (!$saved) {
$row->notification_frequency = 0;
}
$row->user_id = $userId;
$row->save();
}
/**
* Return a session container for use in user email verification.
*
* @return \Laminas\Session\Container
*/
protected function getUserVerificationContainer()
{
return new \Laminas\Session\Container(
'user_verification',
$this->serviceLocator->get(\Laminas\Session\SessionManager::class)
);
}
/**
* Support method for savesearchAction() -- schedule a search.
*
* @param \VuFind\Db\Row\User $user Logged-in user object
* @param int $schedule Requested schedule setting
* @param int $sid Search ID to schedule
*
* @return mixed
*/
protected function scheduleSearch($user, $schedule, $sid)
{
// Fail if scheduled searches are disabled.
$scheduleOptions = $this->serviceLocator
->get(\VuFind\Search\History::class)
->getScheduleOptions();
if (!isset($scheduleOptions[$schedule])) {
throw new ForbiddenException('Illegal schedule option: ' . $schedule);
}
$search = $this->getTable('Search');
$baseurl = rtrim($this->getServerUrl('home'), '/');
$savedRow = $this->getSearchRowSecurely($sid, $user->id);
// In case the user has just logged in, let's deduplicate...
$sessId = $this->serviceLocator
->get(\Laminas\Session\SessionManager::class)->getId();
$duplicateId = $this->isDuplicateOfSavedSearch(
$search,
$savedRow,
$sessId,
$user->id
);
if ($duplicateId) {
$savedRow->delete();
$sid = $duplicateId;
$savedRow = $this->getSearchRowSecurely($sid, $user->id);
}
// If we didn't find an already-saved row, let's save and retry:
if (!($savedRow->saved ?? false)) {
$this->setSavedFlagSecurely($sid, true, $user->id);
$savedRow = $this->getSearchRowSecurely($sid, $user->id);
}
if (!($this->getConfig()->Account->force_first_scheduled_email ?? false)) {
// By default, a first scheduled email will be sent because the database
// last notification date will be initialized to a past date. If we don't
// want that to happen, we need to set it to a more appropriate date:
$savedRow->last_notification_sent = date('Y-m-d H:i:s');
}
$savedRow->setSchedule($schedule, $baseurl);
return $this->redirect()->toRoute('search-history');
}
/**
* Handle search subscription request
*
* @return mixed
*/
public function schedulesearchAction()
{
// Fail if saved searches or subscriptions are disabled.
$check = $this->serviceLocator
->get(\VuFind\Config\AccountCapabilities::class);
if ($check->getSavedSearchSetting() === 'disabled') {
throw new ForbiddenException('Saved searches disabled.');
}
$scheduleOptions = $this->serviceLocator
->get(\VuFind\Search\History::class)
->getScheduleOptions();
if (empty($scheduleOptions)) {
throw new ForbiddenException('Scheduled searches disabled.');
}
// Fail if search ID is missing.
$searchId = $this->params()->fromQuery('searchid', false);
if (!$searchId) {
throw new BadRequestException('searchid missing');
}
// Require login.
if (!($user = $this->getUser())) {
return $this->forceLogin();
}
// Get the row, and fail if the current user doesn't own it.
$search = $this->getSearchRowSecurely($searchId, $user->id);
// If the user has just logged in, the search might be a duplicate; if
// so, let's switch to the pre-existing version instead.
$searchTable = $this->getTable('search');
$sessId = $this->serviceLocator
->get(\Laminas\Session\SessionManager::class)->getId();
$duplicateId = $this->isDuplicateOfSavedSearch(
$searchTable,
$search,
$sessId,
$user->id
);
if ($duplicateId) {
$search->delete();
$this->redirect()->toRoute(
'myresearch-schedulesearch',
[],
['query' => ['searchid' => $duplicateId]]
);
}
// Now fetch all the results:
$resultsManager = $this->serviceLocator
->get(\VuFind\Search\Results\PluginManager::class);
$results = $search->getSearchObject()->deminify($resultsManager);
// Build the form.
return $this->createViewModel(
compact('scheduleOptions', 'search', 'results')
);
}
/**
* Is the provided search row a duplicate of a search that is already saved?
*
* @param \VuFind\Db\Table\Search $searchTable Search table
* @param ?\VuFind\Db\Row\Search $rowToCheck Search row to check (if any)
* @param string $sessId Current session ID
* @param int $userId Current user ID
*
* @return ?int
*/
protected function isDuplicateOfSavedSearch(
\VuFind\Db\Table\Search $searchTable,
?\VuFind\Db\Row\Search $rowToCheck,
string $sessId,
int $userId
): ?int {
if (!$rowToCheck) {
return null;
}
$normalizer = $this->serviceLocator
->get(\VuFind\Search\SearchNormalizer::class);
$normalized = $normalizer
->normalizeMinifiedSearch($rowToCheck->getSearchObject());
$matches = $searchTable->getSearchRowsMatchingNormalizedSearch(
$normalized,
$sessId,
$userId
);
foreach ($matches as $current) {
// $current->saved may be 1 (MySQL) or true (PostgreSQL), so we should
// avoid a strict === comparison here:
if ($current->saved == 1 && $current->id !== $rowToCheck->id) {
return $current->id;
}
}
return null;
}
/**
* Handle 'save/unsave search' request
*
* @return mixed
*/
public function savesearchAction()
{
// Fail if saved searches are disabled.
$check = $this->serviceLocator
->get(\VuFind\Config\AccountCapabilities::class);
if ($check->getSavedSearchSetting() === 'disabled') {
throw new ForbiddenException('Saved searches disabled.');
}
if (!($user = $this->getUser())) {
return $this->forceLogin();
}
// Check for schedule-related parameters and process them first:
$schedule = $this->params()->fromQuery('schedule', false);
$sid = $this->params()->fromQuery('searchid', false);
if ($schedule !== false && $sid !== false) {
return $this->scheduleSearch($user, $schedule, $sid);
}
// Check for the save / delete parameters and process them appropriately:
if (($id = $this->params()->fromQuery('save', false)) !== false) {
// If the row the user is trying to save is a duplicate of an already-
// saved row, we should just delete the duplicate. (This can happen if
// the user clicks "save" before logging in, then logs in during the
// save process, but has the same search already saved in their account).
$searchTable = $this->getTable('search');
$sessId = $this->serviceLocator
->get(\Laminas\Session\SessionManager::class)->getId();
$rowToCheck = $searchTable->getOwnedRowById($id, $sessId, $user->id);
$duplicateId = $this->isDuplicateOfSavedSearch(
$searchTable,
$rowToCheck,
$sessId,
$user->id
);
if ($duplicateId) {
$rowToCheck->delete();
$id = $duplicateId;
} else {
$this->setSavedFlagSecurely($id, true, $user->id);
}
$this->flashMessenger()->addMessage('search_save_success', 'success');
} elseif (($id = $this->params()->fromQuery('delete', false)) !== false) {
$this->setSavedFlagSecurely($id, false, $user->id);
$this->flashMessenger()->addMessage('search_unsave_success', 'success');
} else {
throw new \Exception('Missing save and delete parameters.');
}
// Forward to the appropriate place:
if ($this->params()->fromQuery('mode') == 'history') {
return $this->redirect()->toRoute('search-history');
} else {
// Forward to the Search/Results action with the "saved" parameter set;
// this will in turn redirect the user to the appropriate results screen.
$this->getRequest()->getQuery()->set('saved', $id);
return $this->forwardTo('Search', 'Results');
}
}
/**
* Gather user profile data
*
* @return mixed
*/
public function profileAction()
{
if (!($user = $this->getUser())) {
return $this->forceLogin();
}
// Begin building view object:
$view = $this->createViewModel(['user' => $user]);
$config = $this->getConfig();
$allowHomeLibrary = $config->Account->set_home_library ?? true;
$patron = $this->catalogLogin();
if (is_array($patron)) {
// Process home library parameter (if present and allowed):
$homeLibrary = $this->params()->fromPost('home_library');
if ($allowHomeLibrary && null !== $homeLibrary) {
// Note: for backward compatibility user's home library defaults to
// empty string indicating system default. We also allow null for
// "Always ask me", and the choice is encoded as ' ** ' on the form:
if (' ** ' === $homeLibrary) {
$homeLibrary = null;
}
$user->changeHomeLibrary($homeLibrary);
$this->getAuthManager()->updateSession($user);
$this->flashMessenger()->addMessage('profile_update', 'success');
}
// Obtain user information from ILS:
$catalog = $this->getILS();
$this->addAccountBlocksToFlashMessenger($catalog, $patron);
$profile = $catalog->getMyProfile($patron);
$profile['home_library'] = $allowHomeLibrary
? $user->getHomeLibrary()
: ($profile['home_library'] ?? '');
$view->profile = $profile;
$pickup = $defaultPickupLocation = null;
try {
$pickup = $catalog->getPickUpLocations($patron);
$defaultPickupLocation = $catalog->getDefaultPickUpLocation($patron);
} catch (\Exception $e) {
// Do nothing; if we're unable to load information about pickup
// locations, they are not supported and we should ignore them.
}
// Set things up differently depending on whether or not the user is
// allowed to set a home library.
if ($allowHomeLibrary) {
$view->pickup = $pickup;
$view->defaultPickupLocation = $defaultPickupLocation;
} elseif (!empty($pickup)) {
foreach ($pickup as $lib) {
if ($defaultPickupLocation == $lib['locationID']) {
$view->preferredLibraryDisplay = $lib['locationDisplay'];
break;
}
}
}
// Add proxy details if available
if ($catalog->checkCapability('getProxiedUsers', [$patron])) {
$view->proxiedUsers = $catalog->getProxiedUsers($patron);
}
if ($catalog->checkCapability('getProxyingUsers', [$patron])) {
$view->proxyingUsers = $catalog->getProxyingUsers($patron);
}
} else {
$view->patronLoginView = $patron;
// Turn off account menu in embedded login display:
$view->patronLoginView->showMenu = false;
}
$view->accountDeletion
= !empty($config->Authentication->account_deletion);
$this->addPendingEmailChangeMessage($user);
return $view;
}
/**
* Add account blocks to the flash messenger as errors.
* These messages are lightbox ignored.
*
* @param \VuFind\ILS\Connection $catalog Catalog connection
* @param array $patron Patron details
*
* @return void
*/
public function addAccountBlocksToFlashMessenger($catalog, $patron)
{
if (
$catalog->checkCapability('getAccountBlocks', compact('patron'))
&& $blocks = $catalog->getAccountBlocks($patron)
) {
foreach ($blocks as $block) {
$this->flashMessenger()->addMessage(
[ 'msg' => $block, 'dataset' => [ 'lightbox-ignore' => '1' ] ],
'error'
);
}
}
}
/**
* Catalog Login Action
*
* @return mixed
*/
public function catalogloginAction()
{
$loginSettings = $this->getILSLoginSettings();
return $this->createViewModel($loginSettings);
}
/**
* Action for sending all of a user's saved favorites to the view
*
* @return mixed
*/
public function favoritesAction()
{
// Check permission:
$response = $this->permission()->check('feature.Favorites', false);
if (is_object($response)) {
return $response;
}
// Favorites is the same as MyList, but without the list ID parameter.
return $this->forwardTo('MyResearch', 'MyList');
}
/**
* Delete group of records from favorites.
*
* @return mixed
*/
public function deleteAction()
{
// Force login:
if (!($user = $this->getUser())) {
return $this->forceLogin();
}
// Get target URL for after deletion:
$listID = $this->params()->fromPost('listID');
$newUrl = empty($listID)
? $this->url()->fromRoute('myresearch-favorites')
: $this->url()->fromRoute('userList', ['id' => $listID]);
// Fail if we have nothing to delete:
$ids = $this->getSelectedIds();
$actionLimit = $this->getBulkActionLimit('delete');
if (!is_array($ids) || empty($ids)) {
if ($redirect = $this->redirectToSource('error', 'bulk_noitems_advice')) {
return $redirect;
}
} elseif (count($ids) > $actionLimit) {
$errorMsg = $this->translate(
'bulk_limit_exceeded',
['%%count%%' => count($ids), '%%limit%%' => $actionLimit],
);
if ($redirect = $this->redirectToSource('error', $errorMsg)) {
return $redirect;
}
} elseif ($this->formWasSubmitted()) {
$this->favorites()->delete($ids, $listID, $user);
$this->flashMessenger()->addMessage('fav_delete_success', 'success');
return $this->redirect()->toUrl($newUrl);
}
// If we got this far, the operation has not been confirmed yet; show
// the necessary dialog box:
if (empty($listID)) {
$list = false;
} else {
$table = $this->getTable('UserList');
$list = $table->getExisting($listID);
}
return $this->createViewModel(
[
'list' => $list, 'deleteIDS' => $ids,
'records' => $this->getRecordLoader()->loadBatch($ids),
]
);
}
/**
* Delete record
*
* @param string $id ID of record to delete
* @param string $source Source of record to delete
*
* @return mixed True on success; otherwise returns a value that can
* be returned by the controller to forward to another action (i.e. force login)
*/
public function performDeleteFavorite($id, $source)
{
// Force login:
if (!($user = $this->getUser())) {
return $this->forceLogin();
}
// Load/check incoming parameters:
$listID = $this->params()->fromRoute('id');
$listID = empty($listID) ? null : $listID;
if (empty($id)) {
throw new \Exception('Cannot delete empty ID!');
}
// Perform delete and send appropriate flash message:
if (null !== $listID) {
// ...Specific List
$table = $this->getTable('UserList');
$list = $table->getExisting($listID);
$list->removeResourcesById($user, [$id], $source);
$this->flashMessenger()->addMessage('Item removed from list', 'success');
} else {
// ...All Saved Items
$user->removeResourcesById([$id], $source);
$this->flashMessenger()
->addMessage('Item removed from favorites', 'success');
}
// All done -- return true to indicate success.
return true;
}
/**
* Process the submission of the edit favorite form.
*
* @param \VuFind\Db\Row\User $user Logged-in user
* @param \VuFind\RecordDriver\AbstractBase $driver Record driver for favorite
* @param int $listID List being edited (null
* if editing all favorites)
*
* @return object
*/
protected function processEditSubmit($user, $driver, $listID)
{
$lists = $this->params()->fromPost('lists', []);
$tagParser = $this->serviceLocator->get(\VuFind\Tags::class);
$favorites = $this->serviceLocator
->get(\VuFind\Favorites\FavoritesService::class);
$didSomething = false;
foreach ($lists as $list) {
$tags = $this->params()->fromPost('tags' . $list);
$favorites->save(
[
'list' => $list,
'mytags' => $tagParser->parse($tags),
'notes' => $this->params()->fromPost('notes' . $list),
],
$user,
$driver
);
$didSomething = true;
}
// add to a new list?
$addToList = $this->params()->fromPost('addToList');
if ($addToList > -1) {
$didSomething = true;
$favorites->save(['list' => $addToList], $user, $driver);
}
if ($didSomething) {
$this->flashMessenger()->addMessage('edit_list_success', 'success');
}
$newUrl = null === $listID
? $this->url()->fromRoute('myresearch-favorites')
: $this->url()->fromRoute('userList', ['id' => $listID]);
return $this->redirect()->toUrl($newUrl);
}
/**
* Edit record
*
* @return mixed
*/
public function editAction()
{
// Force login:
if (!($user = $this->getUser())) {
return $this->forceLogin();
}
// Get current record (and, if applicable, selected list ID) for convenience:
$id = $this->params()->fromPost('id', $this->params()->fromQuery('id'));
$source = $this->params()->fromPost(
'source',
$this->params()->fromQuery('source', DEFAULT_SEARCH_BACKEND)
);
$driver = $this->getRecordLoader()->load($id, $source, true);
$listID = $this->params()->fromPost(