-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathModule.php
More file actions
2755 lines (2436 loc) · 103 KB
/
Module.php
File metadata and controls
2755 lines (2436 loc) · 103 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Teams;
use Collecting\Api\Adapter\CollectingItemAdapter;
use Omeka\Api\Adapter\AssetAdapter;
use Omeka\Api\Adapter\UserAdapter;
use Omeka\Entity\Resource;
use Omeka\Mvc\Controller\Plugin\Messenger;
use Doctrine\ORM\QueryBuilder;
use Omeka\Api\Exception;
use Doctrine\ORM\Query\Expr;
use Omeka\Api\Adapter\ResourceTemplateAdapter;
use Omeka\Api\Adapter\SiteAdapter;
use Omeka\Entity\EntityInterface;
use Omeka\Permissions\Acl;
use Omeka\Permissions\Assertion\AssertionNegation;
use Omeka\Permissions\Assertion\IsSelfAssertion;
use Omeka\Permissions\Assertion\OwnsEntityAssertion;
use Teams\Acl\TeamRolePermissionAssertion;
use Teams\Entity\Team;
use Teams\Entity\TeamAsset;
use Teams\Entity\TeamResource;
use Teams\Entity\TeamResourceTemplate;
use Teams\Entity\TeamSite;
use Teams\Entity\TeamUser;
use Teams\Form\ConfigForm;
use Teams\Form\Element\AllSiteSelectOrdered;
use Teams\Form\Element\AllTeamSelect;
use Teams\Form\Element\BlankTeamSelect;
use Teams\Form\Element\RoleSelect;
use Teams\Form\Element\TeamSelect;
use Omeka\Api\Adapter\ItemAdapter;
use Omeka\Api\Adapter\ItemSetAdapter;
use Omeka\Api\Adapter\MediaAdapter;
use Omeka\Api\Representation\AbstractEntityRepresentation;
use Omeka\Module\AbstractModule;
use Laminas\EventManager\Event;
use Laminas\EventManager\SharedEventManagerInterface;
use Laminas\Mvc\Controller\AbstractController;
use Laminas\Mvc\MvcEvent;
use Laminas\ServiceManager\ServiceLocatorInterface;
use Laminas\View\Renderer\PhpRenderer;
use Teams\Mvc\Controller\Plugin\TeamAuth;
class Module extends AbstractModule
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function onBootstrap(MvcEvent $event)
{
parent::onBootstrap($event);
$this->addAclRules();
}
public function install(ServiceLocatorInterface $serviceLocator)
{
$globalSettings = $serviceLocator->get('Omeka\Settings');
$globalSettings->set('teams_filter_bypass_roles', ["global_admin"]);
$conn = $serviceLocator->get('Omeka\Connection');
$conn->exec('
CREATE TABLE team (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(240) NOT NULL, description LONGTEXT NOT NULL, UNIQUE INDEX UNIQ_C4E0A61F5E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
CREATE TABLE team_user (team_id INT NOT NULL, user_id INT NOT NULL, role_id INT DEFAULT NULL, is_current TINYINT(1) DEFAULT NULL, id INT NOT NULL AUTO_INCREMENT, UNIQUE INDEX UNIQ_5C722232BF396750 (id), INDEX IDX_5C722232296CD8AE (team_id), INDEX IDX_5C722232A76ED395 (user_id), INDEX IDX_5C722232D60322AC (role_id), UNIQUE INDEX active_team (is_current, user_id), PRIMARY KEY(team_id, user_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
CREATE TABLE team_role (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(240) NOT NULL, can_add_users TINYINT(1) DEFAULT NULL, can_add_items TINYINT(1) DEFAULT NULL, can_add_itemsets TINYINT(1) DEFAULT NULL, can_modify_resources TINYINT(1) DEFAULT NULL, can_delete_resources TINYINT(1) DEFAULT NULL, can_add_site_pages TINYINT(1) DEFAULT NULL, comment LONGTEXT DEFAULT NULL, UNIQUE INDEX UNIQ_86887E115E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
CREATE TABLE team_asset (team_id INT NOT NULL, asset_id INT NOT NULL, INDEX IDX_C5A9131C296CD8AE (team_id), INDEX IDX_C5A9131C5DA1941 (asset_id), PRIMARY KEY(team_id, asset_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
CREATE TABLE team_resource_template (team_id INT NOT NULL, resource_template_id INT NOT NULL, INDEX IDX_75325B72296CD8AE (team_id), INDEX IDX_75325B7216131EA (resource_template_id), PRIMARY KEY(team_id, resource_template_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
CREATE TABLE team_site (team_id INT NOT NULL, site_id INT NOT NULL, is_current TINYINT(1) DEFAULT NULL, INDEX IDX_B8A2FD9F296CD8AE (team_id), INDEX IDX_B8A2FD9FF6BD1646 (site_id), UNIQUE INDEX active_team (is_current, site_id), PRIMARY KEY(team_id, site_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
CREATE TABLE team_resource (team_id INT NOT NULL, resource_id INT NOT NULL, INDEX IDX_4D32868296CD8AE (team_id), INDEX IDX_4D3286889329D25 (resource_id), PRIMARY KEY(team_id, resource_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
ALTER TABLE team_user ADD CONSTRAINT FK_5C722232296CD8AE FOREIGN KEY (team_id) REFERENCES team (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_user ADD CONSTRAINT FK_5C722232A76ED395 FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_user ADD CONSTRAINT FK_5C722232D60322AC FOREIGN KEY (role_id) REFERENCES team_role (id);');
$conn->exec('
ALTER TABLE team_asset ADD CONSTRAINT FK_C5A9131C296CD8AE FOREIGN KEY (team_id) REFERENCES team (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_asset ADD CONSTRAINT FK_C5A9131C5DA1941 FOREIGN KEY (asset_id) REFERENCES asset (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_resource_template ADD CONSTRAINT FK_75325B72296CD8AE FOREIGN KEY (team_id) REFERENCES team (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_resource_template ADD CONSTRAINT FK_75325B7216131EA FOREIGN KEY (resource_template_id) REFERENCES resource_template (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_site ADD CONSTRAINT FK_B8A2FD9F296CD8AE FOREIGN KEY (team_id) REFERENCES team (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_site ADD CONSTRAINT FK_B8A2FD9FF6BD1646 FOREIGN KEY (site_id) REFERENCES site (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_resource ADD CONSTRAINT FK_4D32868296CD8AE FOREIGN KEY (team_id) REFERENCES team (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_resource ADD CONSTRAINT FK_4D3286889329D25 FOREIGN KEY (resource_id) REFERENCES resource (id) ON DELETE CASCADE;');
}
public function uninstall(ServiceLocatorInterface $serviceLocator)
{
$conn = $serviceLocator->get('Omeka\Connection');
$conn->exec('DROP TABLE IF EXISTS team_asset');
$conn->exec('DROP TABLE IF EXISTS team_user');
$conn->exec('DROP TABLE IF EXISTS team_role');
$conn->exec('DROP TABLE IF EXISTS team_resource');
$conn->exec('DROP TABLE IF EXISTS team_resource_template');
$conn->exec('DROP TABLE IF EXISTS team_site');
$conn->exec('DROP TABLE IF EXISTS team');
}
public function upgrade($oldVersion, $newVersion, ServiceLocatorInterface $serviceLocator)
{
if (version_compare($oldVersion, '1.0.0', '<')) {
$connection = $serviceLocator->get('Omeka\Connection');
/*
* use replace because it is possible for an item and a site to belong to two teams and therefore show up
* together twice in the join and result in an integrity constraint violation on duplicate primary key in
* team_site table using insert
*/
$userSettings = $serviceLocator->get('Omeka\Settings\User');
$team_users = $connection->fetchAll('select user_id, site_id from team_user tu join team_site ts on ts.team_id = tu.team_id where tu.is_current = true;');
$user_sites = [];
foreach ($team_users as $user) {
if (array_key_exists($user['user_id'], $user_sites)) {
array_push($user_sites[$user['user_id']], $user['site_id']);
} else {
$user_sites[$user['user_id']] = [$user['site_id']];
}
}
foreach ($user_sites as $user => $sites) {
$userSettings->set('default_item_sites', $sites, $user);
}
$connection->exec('replace item_site select resource_id, site_id from team_resource tr join team_site ts on tr.team_id = ts.team_id where resource_id in (select * from item)');
}
if (version_compare($oldVersion, '2.0.0', '<')) {
//add the team asset table and foriegn keys
$conn = $serviceLocator->get('Omeka\Connection');
$conn->exec('
CREATE TABLE team_asset (team_id INT NOT NULL, asset_id INT NOT NULL, INDEX IDX_C5A9131C296CD8AE (team_id), INDEX IDX_C5A9131C5DA1941 (asset_id), PRIMARY KEY(team_id, asset_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB;');
$conn->exec('
ALTER TABLE team_asset ADD CONSTRAINT FK_C5A9131C296CD8AE FOREIGN KEY (team_id) REFERENCES team (id) ON DELETE CASCADE;');
$conn->exec('
ALTER TABLE team_asset ADD CONSTRAINT FK_C5A9131C5DA1941 FOREIGN KEY (asset_id) REFERENCES asset (id) ON DELETE CASCADE;');
/*
* Create entries for existing assets:
* There are two objects that use assets as thumbnails, sites and resources. If an asset is being used as a
* thumbnail, then it needs to have at least one team in common with the site or resource
*/
$conn = $serviceLocator->get('Omeka\Connection');
$sql = <<<'SQL'
select asset_id, team_id
from (select asset.id asset_id, team_site.team_id team_id
from asset
join site
on asset.id = site.thumbnail_id
join team_site
on team_site.site_id = site.id) as site_assets
union
select asset_id, team_id
from (select asset.id asset_id, team_resource.team_id team_id
from asset
join resource
on asset.id = resource.thumbnail_id
join team_resource
on team_resource.resource_id = resource.id) as resource_assets
group by asset_id, team_id;
SQL;
$res = $conn->fetchAll($sql);
foreach ($res as $entry) {
$conn->insert('team_asset', $entry);
}
}
//version naming conventions changed to mirror release versions/core omeka versions
if (version_compare($oldVersion, '4.0.0', '<')) {
$conn = $serviceLocator->get('Omeka\Connection');
$conn->exec('ALTER TABLE team_user MODIFY id INT NOT NULL AUTO_INCREMENT');
}
if (version_compare($oldVersion, '4.1.0', '<')) {
//add global admin to the list of settings for bypass team users
$globalSettings = $serviceLocator->get('Omeka\Settings');
$globalSettings->set('teams_filter_bypass_roles', ["global_admin"]);
}
}
public function updateAllUserSites()
{
$em = $this->getServiceLocator()->get('Omeka\EntityManager');
$active_users = $em->getRepository('Teams\Entity\TeamUser')->findAllBy(['is_active' => true]);
foreach ($active_users as $user) {
$this->updateUserSites($user->getUser()->getId());
}
}
public function handleConfigForm(AbstractController $controller)
{
$globalSettings = $this->getServiceLocator()->get('Omeka\Settings');
$params = $controller->params()->fromPost();
$globalSettings->set('teams_site_admin_make_site', $params['teams_site_admin_make_site']);
$globalSettings->set('teams_editor_make_site', $params['teams_editor_make_site']);
$globalSettings->set('teams_site_admin_make_user', $params['teams_site_admin_make_user']);
$globalSettings->set('teams_filter_bypass_roles', $params['teams_filter_bypass_roles']);
}
public function getConfigForm(PhpRenderer $renderer)
{
$html = '';
$formElementManager = $this->getServiceLocator()->get('FormElementManager');
$form = $formElementManager->get(ConfigForm::class, []);
$html .= $renderer->formCollection($form, false);
return $html;
}
public function createNamedParameter(
QueryBuilder $qb,
$value,
$prefix = 'omeka_'
) {
$index = 0;
$placeholder = $prefix . $index;
$index++;
$qb->setParameter($placeholder, $value);
return ":$placeholder";
}
//TODO need to refactor to normalize and condense
protected function addAclRules()
{
$serviceLocator = $this->getServiceLocator();
$acl = $serviceLocator->get('Omeka\Acl');
// Get our new service from the service manager
$aclRuleManager = $serviceLocator->get(\Teams\Service\AclRuleManager::class);
// Delegate the complex task to our new, testable service
$aclRuleManager->applyRules($acl);
// This remaining logic can also be moved to a service in a future refactoring
$globalSettings = $this->getServiceLocator()->get('Omeka\Settings');
if (!$globalSettings->get('teams_site_admin_make_site')) {
$acl->deny('site_admin', \Omeka\Entity\Site::class, 'create');
}
if (!$globalSettings->get('teams_editor_make_site')) {
$acl->deny('editor', \Omeka\Entity\Site::class, 'create');
}
}
/**
* @param Event $event
* The default teams behavior is to filter API class, including the ones that populate the available sites in forms.
* This replaces the default site selector with one that is fully populated with all sites on the user form and adds
* an option to use teams for default sites instead of manually selecting them.
*/
public function addDefaultSitesUserForm(Event $event)
{
$form = $event->getTarget();
$settingsFieldset = $form->get('user-settings');
$userId = $form->getOption('user_id');
$userSettings = $this->getServiceLocator()->get('Omeka\Settings\User');
$informationFieldset = $form->get('user-information');
$settingsFieldset->remove('default_item_sites');
//ideally we would just swap out the 'type' from the original element, if possible.
$settingsFieldset->add([
'name' => 'default_item_sites',
'type' => AllSiteSelectOrdered::class,
'attributes' => [
'value' => $userId ? $userSettings->get('default_item_sites', null, $userId) : [],
'class' => 'chosen-select',
'data-placeholder' => 'Select sites', // @translate
'multiple' => true,
'id' => 'default_sites',
],
'options' => [
'label' => 'Default sites for items', // @translate
'empty_option' => '',
],
]);
// $informationFieldset->add([
// 'name' => 'update_default_sites',
// 'type' => 'checkbox',
// 'options' => [
// 'label' => 'Use Teams for default sites?', // @translate
// 'info' => 'Default sites for this user will be those in the selected teams(s) above.', // @translate
//
// ],
// 'attributes' => [
// 'id' => 'update_default_sites',
// 'value' => false,
//
// ],
// ]);
}
/**
* Add a tab to section navigation of a admin view.
*
* @param Event $event
*/
public function addTab(Event $event)
{
$sectionNav = $event->getParam('section_nav');
$sectionNav['teams'] = 'Teams'; // @translate
$event->setParam('section_nav', $sectionNav);
}
public function removeTab(Event $event)
{
$sectionNav = $event->getParam('section_nav');
unset($sectionNav['item-pool']);
$event->setParam('section_nav', $sectionNav);
}
/**
* Displays the teams that a resource belongs to for admin pages.
*
* @param Event $event
*/
public function adminShowTeams(Event $event)
{
$resource = $event->getTarget()->vars()->resource;
$new_item = null;
$resource_type = $resource->getControllerName();
$associated_teams = $this->listTeams($resource);
echo '<div id="teams" class="section"><p>';
//get the partial and pass it whatever variables it needs
echo $event->getTarget()->partial(
'teams/partial/resource-show-teams',
[
'teams' => $associated_teams,
'resource_type' => $resource_type,
]
);
echo '</div>';
}
/**
* Populates the list of teams users can choose from
* for the selector on top of browse/index type pages.
* The selector filters the results on the page by team.
*
* @param Event $event
*/
public function teamSelectorBrowse(Event $event)
{
$identity = $this->getUser();
$user_id = $identity->getId();
$view = $event->getTarget();
$vars = $view->vars();
if (is_array($vars->resources) && count($vars->resources) > 0) {
$resource_type = $vars->resources[0]->getControllerName() . 's';
} elseif (is_array($vars->sites) && count($vars->sites)) {
$resource_type = 'sites';
} else {
$resource_type = null;
}
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
$team_user = $entityManager->getRepository('Teams\Entity\TeamUser');
$user_teams = $team_user->findBy(['user' => $user_id]);
$current_team = $team_user->findOneBy(['user' => $user_id,'is_current' => true]);
if ($current_team) {
$current_team = $current_team->getTeam()->getName();
} elseif ($user_teams) {
$current_team = $team_user->findOneBy(['user' => $user_id]);
$current_team->setCurrent(true);
$entityManager->flush();
$current_team = $current_team->getTeam()->getName();
} else {
$current_team = null;
}
echo $event->getTarget()->partial(
'teams/partial/team-selector',
['user_teams' => $user_teams, 'current_team' => $current_team, 'resource_type' => $resource_type]
);
}
//TODO need to change language on results page so it is clear which team is being searched against
/**
* Populates a team selector on the admin advanced search page for resources
*
* @param Event $event
*/
public function teamSelectorAdvancedSearch(Event $event)
{
$identity = $this->getUser();
$user_id = $identity->getId();
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
$team_user = $entityManager->getRepository('Teams\Entity\TeamUser');
$user_teams = $team_user->findBy(['user' => $user_id]);
$current_team = $team_user->findOneBy(['user' => $user_id,'is_current' => true]);
if ($current_team) {
$current_team = $current_team->getTeam()->getName();
} else {
$current_team = null;
}
echo $event->getTarget()->partial(
'teams/partial/team-selector-adv-search',
['user_teams' => $user_teams, 'current_team' => $current_team]
);
}
/**
* Get all the teams a resource belongs to
*
* @param AbstractEntityRepresentation|null $resource
* @return array
*/
protected function listTeams(AbstractEntityRepresentation $resource = null)
{
$result = [];
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
$team_resource = $entityManager->getRepository('Teams\Entity\TeamResource')
->findBy(['resource' => $resource->id()]);
foreach ($team_resource as $tr):
$result[$tr->getTeam()->getName()] = $tr->getTeam();
endforeach;
return $result;
}
public function displayUserForm(Event $event)
{
$vars = $event->getTarget()->vars();
$vars->offsetSet('team-members', 'test');
}
public function displayTeamForm(Event $event)
{
$vars = $event->getTarget()->vars();
$view = $event->getTarget();
// Manage add/edit form.
if (isset($vars->item)) {
$vars->offsetSet('resource', $vars->item);
} elseif (isset($vars->itemSet)) {
$vars->offsetSet('resource', $vars->itemSet);
} elseif (isset($vars->media)) {
$vars->offsetSet('resource', $vars->media);
} else {
$vars->offsetSet('resource', null);
$vars->offsetSet('teams', []);
}
if ($vars->resource) {
$vars->offsetSet('teams', $this->listTeams($vars->resource, 'representation'));
}
echo $event->getTarget()->partial(
'teams/partial/team-form',
);
}
/**
* Allows users to add teams to resources on edit or create.
* Adds the right side panel selector + options and pass selections to the submission form
*
* @param Event $event
*/
public function displayTeamFormNoId(Event $event)
{
$view = $event->getTarget();
$vars = $event->getTarget()->vars();
// Manage add/edit form.
if (isset($vars->item)) {
$vars->offsetSet('resource', $vars->item);
} elseif (isset($vars->itemSet)) {
$vars->offsetSet('resource', $vars->itemSet);
} elseif (isset($vars->media)) {
$vars->offsetSet('resource', $vars->media);
} else {
$vars->offsetSet('resource', null);
$vars->offsetSet('teams', []);
}
if ($vars->resource) {
$vars->offsetSet('teams', $this->listTeams($vars->resource, 'representation'));
}
$identity = $this->getUser();
$user_id = $identity->getId();
$default_team = $this->currentTeam();
if (! $default_team) {
$messanger = new Messenger();
$messanger->addError("You can only make a new resource after you have been added to a team");
echo '<script>$(\'button:contains("Add")\').prop("disabled",true);</script>';
}
$view->headScript()->appendFile($view->assetUrl('js/add-team-to-resource.js', 'Teams'));
$view->headLink()->appendStylesheet($view->assetUrl('css/teams.css', 'Teams'));
echo $event->getTarget()->partial(
'teams/partial/team-form-no-id',
['user_id' => $user_id, 'default_team' => $default_team]
);
}
/**
* Displays a message where the site pool. Not currently used.
*
* @param Event $event
*/
public function displaySitePoolMsg(Event $event)
{
echo '
<p class="section" id="team">Site Pools superseded by the Teams Module. This site will have access to all associated Team Resources.</p>
';
}
/**
* Adds the teams partial the the list partials for the advanced search for resources form.
* Each partial is a form field
*
* @param Event $event
*/
public function advancedSearch(Event $event)
{
$partials = $event->getParams()['partials'];
$partials[] = 'teams/partial/advanced-search';
$event->setParam('partials', $partials);
}
//TODO: refactor to use the currentTeam() function
//need to use the currentTeam() function
/**
* Adds the team selector to the admin navigation
*
* @param Event $event
*/
public function teamSelectorNav(Event $event)
{
if (!$this->getServiceLocator()->get('Omeka\Status')->isSiteRequest()) {
if ($identity = $this->getUser()) {
$user_id = $identity->getId();
} else {
$user_id = null;
}
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
$tu = $entityManager->getRepository('Teams\Entity\TeamUser');
$ct = $tu->findOneBy(['is_current' => true, 'user' => $user_id]);
if ($ct) {
$ct = $ct->getTeam();
} else {
$ct = 'None';
}
echo $event->getTarget()->partial(
'teams/partial/team-nav-selector',
['current_team' => $ct]
);
}
}
public function bypassTeamsSortSelector(Event $event)
{
$globalSettings = $this->getServiceLocator()->get('Omeka\Settings');
$roles = $globalSettings->get('teams_filter_bypass_roles');
if (!is_array($roles)) {
$roles[] = $roles;
}
$user = $this->getUser();
if ($user && in_array($user->getRole(), $roles)) {
$view = $event->getTarget();
$params = $view->params();
$bypassTeams = $params->fromQuery('bypass_team_filter');
$view->headScript()->appendFile($view->assetUrl('js/append-sort-selector.js', 'Teams'));
echo $view->partial('teams/common/sort-selector-bypass-teams', ['bypassTeams' => $bypassTeams]);
}
}
//injects into AbstractEntityAdapter where queries are structured for the api
public function currentTeam()
{
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
$identity = $this->getUser();
//TODO add handeling for user not logged-in !!!this current solution would not work
if (!$identity) {
$user_id = null;
return null;
} else {
$user_id = $identity->getId();
}
//look for their current team
$team_user = $entityManager->getRepository('Teams\Entity\TeamUser')->findOneBy(['user' => $user_id, 'is_current' => 1]);
if (!$team_user) {
$team_user = $entityManager->getRepository('Teams\Entity\TeamUser')->findOneBy(['user' => $user_id]);
if ($team_user) {
$team_user->setCurrent('1');
$entityManager->merge($team_user);
$entityManager->flush();
} else {
return null;
}
}
if ($team_user) {
$current_team = $team_user->getTeam();
$team_id = $current_team->getId();
} else {
$current_team = null;
$team_id = 0;
}
return $current_team;
}
/**
* Gets team ids to use for filtering that are appropriate for the context. For users browsing resources, the
* relevant team is the user's current team. For sites, the relevant team(s) are those that the site belongs to.
*
* @param $query
* @param Event $event
* @return array
*/
public function getTeamContext($query, Event $event)
{
//if the query explicitly asks for a team, that trumps all
if (isset($query['team_id'])) {
if (!is_array($query['team_id'])) {
$team_id = [$query['team_id']];
}
foreach ($query['team_id'] as $id):
if (is_int($id)) {
$team_id[] = $id;
} else {
throw new Exception\BadRequestException(sprintf(
'team id has to be an integer',
));
}
endforeach;
} elseif ($this->getServiceLocator()->get('Omeka\Status')->isSiteRequest()) { //Logged-in or not, if it is a public site use the TeamSite
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
if (isset($query['site_id'])) {
$team = $entityManager->getRepository('Teams\Entity\TeamSite')
->findBy(['site' => $query['site_id']]);
if ($team) {
foreach ($team as $t):
$team_id[] = $t->getTeam()->getId();
endforeach;
} else {
$team_id = [0];
}
} else {
$team_id = [0];
}
} elseif ($this->getUser() != null) {
if (isset($query['all_user_teams'])) {
$userId = $this->getUser()->getId();
$api = $this->getServiceLocator()->get('Omeka\ApiManager');
$userTeams = $api->search('team-user', ['user' => $userId], ['returnScalar' => 'team'])->getContent();
$team_id = array_values($userTeams);
} elseif (($this->currentTeam())) {
$team_id[] = $this->currentTeam()->getId();
}
}
return $team_id ?? [0];
}
/**
* Adds a join to API calls for resources and sites to filter results by teams
*
* @param Event $event
*/
public function filterByTeam(Event $event)
{
$qb = $event->getParam('queryBuilder');
$query = $event->getParam('request')->getContent();
$entityClass = $event->getTarget()->getEntityClass();
$alias = 'omeka_root';
$em = $this->getServiceLocator()->get('Omeka\EntityManager');
$isSiteRequest = $this->getServiceLocator()->get('Omeka\Status')->isSiteRequest();
//fist, catch some cases where we shouldn't filter by team
//catch REST queries
if ($this->getUser() === null) {
return;
}
//most site calls are handled by the site-item relationships, but this is for the list-of-sites block.
if ($event->getParam('request')->getResource() === 'sites' &&
$event->getParam('request')->getOperation() === 'search' &&
$isSiteRequest
) {
//get the id for the current site
$siteSlug = $this->getServiceLocator()->get('Omeka\Status')->getRouteMatch()->getParam('site-slug');
$siteId = $em->getRepository('Omeka\Entity\Site')->findOneBy(['slug' => $siteSlug])->getId();
//get the teams of the current site because we only want to show sites within its teams.
$teams = $em->getRepository('Teams\Entity\TeamSite')->findBy(['site' => $siteId]);
$teamIds = [];
foreach ($teams as $team):
$teamIds[] = $team->getTeam()->getId();
endforeach;
//only get sites that share a team with the current site
$qb->join('Teams\Entity\TeamSite', 'ts', Expr\Join::WITH, $alias . '.id = ts.site')
->andWhere('ts.team IN (:team_ids)')
->setParameter('team_ids', $teamIds);
return;
}
// other site requests can be handled by site settings
if ($isSiteRequest) {
return true;
}
//catch cases where bypass_team_filter is passes, and it is a valid flag for the user's access level or the context,
// e.g. certain non-admin site requests
$globalSettings = $this->getServiceLocator()->get('Omeka\Settings');
$bypassTeamsRilterRoles = $globalSettings->get('teams_filter_bypass_roles');
if (!is_array($bypassTeamsRilterRoles)) {
$bypassTeamsRilterRoles[] = $bypassTeamsRilterRoles;
} else {
$bypassTeamsRilterRoles = ['global_admin'];
}
if (isset($query['bypass_team_filter'])
&& $query['bypass_team_filter']
&& in_array($this->getUser()->getRole(), $bypassTeamsRilterRoles)
) {
return;
}
if (isset($query['bypass_team_filter']) && $isSiteRequest) {
return;
}
if (isset($query['resource_class_id']) && $isSiteRequest) {
return;
}
if (isset($query['resource_template_id']) && $isSiteRequest) {
return;
}
//Omeka sets up a way to specifically assign item sets to sites for the Browse by Item Set block.
//for now just ignoring team filter on that
//TODO replace the site_item_set with TR join itemset
if (isset($query['site_id'])) {
if ($entityClass == 'Omeka\Entity\ItemSet') {
return;
} else {
$team_site = $em->getRepository('Teams\Entity\TeamSite')->findBy(['site' => $query['site_id']]);
foreach ($team_site as $ts):
$team_id[] = $ts->getTeam()->getId();
endforeach;
$qb->leftJoin('Teams\Entity\TeamResource', 'tr_si', Expr\Join::WITH, $alias . '.id = tr_si.resource')
->andWhere('tr_si.team = :team_id')
->setParameter('team_id', $team_id[0]);
if (count($team_id) > 1) {
$orX = $qb->expr()->orX();
$i = 0;
foreach ($team_id as $value) {
$orX->add($qb->expr()->eq('tr_si.team', ':name' . $i));
$qb->setParameter('name' . $i, $value);
$i++;
}
$qb->orWhere($orX);
}
}
return;
}
$team_id = $this->getTeamContext($query, $event);
if ($team_id === [0]) {
return;
}
if (is_array($team_id)) {
if ($entityClass == \Omeka\Entity\Site::class) {
$teamAlias = 'ts';
$joinCol = 'site';
$teamsEntityClass = \Teams\Entity\TeamSite::class;
} elseif ($entityClass == \Omeka\Entity\ResourceTemplate::class) {
$teamAlias = 'trt';
$joinCol = 'resource_template';
$teamsEntityClass = \Teams\Entity\TeamResourceTemplate::class;
} elseif ($entityClass == \Omeka\Entity\User::class) {
$teamAlias = 'tu';
$joinCol = 'user';
$teamsEntityClass = \Teams\Entity\TeamUser::class;
} elseif ($entityClass == \Omeka\Entity\Vocabulary::class) {
return;
} elseif ($entityClass == \Omeka\Entity\Asset::class) {
$teamAlias = 'ta';
$joinCol = 'asset';
$teamsEntityClass = \Teams\Entity\TeamAsset::class;
} else {
$teamAlias = 'tr';
$teamsEntityClass = \Teams\Entity\TeamResource::class;
$joinCol = 'resource';
}
$qb->leftJoin($teamsEntityClass, $teamAlias, Expr\Join::WITH, "{$alias}.id = {$teamAlias}.{$joinCol}")
->andWhere($teamAlias . '.team = :team_id')
->setParameter('team_id', $team_id[0]);
if (count($team_id) > 1) {
$orX = $qb->expr()->orX();
$i = 0;
foreach ($team_id as $value) {
$orX->add($qb->expr()->eq("{$teamAlias}.team", ':name' . $i));
$qb->setParameter('name' . $i, $value);
$i++;
}
$qb->orWhere($orX);
}
}
}
public function getOrphans(Event $event)
{
$request = $event->getParam('request')->getContent();
if(array_key_exists('orphans', $request)) {
$qb = $event->getParam('queryBuilder');
$sub = $this->getServiceLocator()->get('Omeka\EntityManager')
->createQueryBuilder()
->select('tr')
->from('Teams\Entity\TeamResource', 'tr');
$q = $sub->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR);
$resource_ids = array_column($q, 'tr_resource_id');
$qb->andWhere($qb->expr()->notIn('omeka_root.id', $resource_ids));
}
}
/**
* Adds user's teams to the user view page
*
* @param Event $event
*/
public function userTeamsView(Event $event)
{
$view = $event->getTarget();
$user_id = $view->vars()->user->id();
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
$team_users = $entityManager->getRepository('Teams\Entity\TeamUser')->findBy(['user' => $user_id]);
echo $view->partial('teams/partial/user/view', ['team_users' => $team_users]);
}
/**
* Adds user teams+roles to the user edit form
*
* @param Event $event
*/
public function userTeamsEdit(Event $event)
{
//send the form data for processing by module controller to add teamUser
$view = $event->getTarget();
$user_id = $view->vars()->user->id();
$entityManager = $this->getServiceLocator()->get('Omeka\EntityManager');
$user_teams = $entityManager->getRepository('Teams\Entity\TeamUser')->findBy(['user' => $user_id]);
$team_ids = [];
foreach ($user_teams as $user_team):
$team_ids[] = $user_team->getTeam()->getId();
endforeach;
echo $view->partial('teams/partial/user/edit', ['user_teams' => $user_teams, 'team_ids' => $team_ids]);
}
//at one point this was fixing a bug but no longer needed. Keeping for reference for now.
// /**
// * @param Event $event
// */
// public function userFormEdit(Event $event)
// {
// $view = $event->getTarget();
// echo $view->partial('teams/partial/return_url', 'Teams');
// }
//TODO: make at least one team the user's 'active' team.
/**
* When user is created, gets team+role info from the form and creates new TeamUser(s)
*
* @param Event $event
*/
public function userCreate(Event $event)
{
$request = $event->getParam('request');
$operation = $request->getOperation();
$em = $this->getServiceLocator()->get('Omeka\EntityManager');
$global = $this->getUser()->getRole() === 'global_admin';
if ($operation == 'create') {
$messanger = new Messenger();
$response = $event->getParam('response');
$resource = $response->getContent();
$user_id = $resource->getId();
$user = $em->getRepository('Omeka\Entity\User')->findOneBy(['id' => $user_id]);
$teams = $em->getRepository('Teams\Entity\Team');
$team_ids = $request->getContent()['o-module-teams:Team'];
//format is {team_id => role_id}
$team_role_ids = $request->getContent()['o-module-teams:TeamRole'];
$default_team = $request->getContent()['o-module-teams:DefaultTeam'];
foreach ($team_ids as $team_id) {
$team_id = (int) $team_id;
//handle new team added via form
if ($team_id === -1) {
if ($global) {
$u_name = $request->getContent()['o:name'];
$team_name = sprintf("%s's team", $u_name);
$team_exists = $em->getRepository('Teams\Entity\Team')->findOneBy(['name' => $team_name]);
if ($team_exists) {
$messanger->addWarning("The team you tried to add already exists. Added user to the team.");
$team = $team_exists;
} else {
$team = new Team();
$team->setName($team_name);
$team->setDescription(sprintf('A team automatically generated for new user %s', $u_name));
$em->persist($team);
$em->flush();
if ($default_team == -1) {
$default_team = $team->getId();
}
}
} else {
$messanger->addError("Only global admins can make new teams");
}
} else {
$team = $teams->findOneBy(['id' => $team_id]);
if (!$global) {
$supervisor_id = $this->getUser()->getId();
$auth = $em->getRepository('Teams\Entity\TeamUser')
->findOneBy(['user' => $supervisor_id, 'team' => $team_id])
->getRole()
->getCanAddUsers();
if (!$auth) {
$messanger->addError(sprintf("You don't have permission to add users to that team %s", $team->getName()));
continue;
}
}
}
$role_id = $team_role_ids[$team_id];
$role = $em->getRepository('Teams\Entity\TeamRole')
->findOneBy(['id' => $role_id]);
$team_user_exists = $em->getRepository('Teams\Entity\TeamUser')
->findOneBy(['team' => $team->getId(), 'user' => $user_id]);
if (!$team_user_exists) {
$team_user = new TeamUser($team, $user, $role);
$em->persist($team_user);
}
}
$em->flush();
if ($default_team) {
$em->getRepository('Teams\Entity\TeamUser')
->findOneBy(['team' => $default_team, 'user' => $user_id])
->setCurrent(true)
;
$em->flush();
}
//handle user sites
if ($request->getContent()['update_default_sites']) {
//handle user sites
$this->updateUserSites($user_id);
}
}
}
public function updateItemSites($item_id)
{
$em = $this->getServiceLocator()->get('Omeka\EntityManager');
//get current item sites
$item = $em->getRepository('Omeka\Entity\Item')
->findOneBy(['id' => $item_id]);
if ($item) {
//get all teams for the item
//get all sites associated with those teams
$item_teams = $em->getRepository('Teams\Entity\TeamResource')->findBy(['resource' => $item_id]);
$current_teams = [];
foreach ($item_teams as $team) {
$current_teams[] = $team->getTeam()->getId();
}