forked from betterangels/better-angels
-
Notifications
You must be signed in to change notification settings - Fork 0
/
class-buoy-team.php
1003 lines (920 loc) · 32 KB
/
class-buoy-team.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
/**
* Buoy Team
*
* @package WordPress\Plugin\WP_Buoy_Plugin\Teams
*
* @copyright Copyright (c) 2015-2016 by Meitar "maymay" Moscovitz
*
* @license https://www.gnu.org/licenses/gpl-3.0.en.html
*/
if (!defined('ABSPATH')) { exit; } // Disallow direct HTTP access.
/**
* Main class for a Buoy Team.
*
* Teams are groups/lists of potential responders managed by one user
* who invites them to join said team. They are implemented as a WP
* custom post type.
*/
class WP_Buoy_Team extends WP_Buoy_Plugin {
/**
* The team post.
*
* @var WP_Post
*/
public $wp_post;
/**
* The team owner.
*
* @var WP_User
*/
private $author;
/**
* An array of WP_User objects representing the team membership.
*
* The members list include those who are not yet confirmed (pending).
*
* @var WP_User[]
*/
private $members = array();
/**
* Addresses of people without accounts who were invited to join.
*
* @var string[]
*/
private $_invitees;
/**
* Constructor.
*
* @param int $team_id The post ID of the team.
*
* @return WP_Buoy_Team
*/
public function __construct ($team_id) {
$this->wp_post = get_post($team_id);
$this->members = array_map('get_userdata', array_unique(get_post_meta($this->wp_post->ID, '_team_members')));
$this->_invitees = array_unique(get_post_meta($this->wp_post->ID, '_invitees'));
$this->author = get_userdata($this->wp_post->post_author);
}
/**
* Gets team member IDs by state.
*
* For the "invited" state, an ID is an email address.
*
* @param array $states Defaults to `array('confirmed', 'unconfirmed', 'invited')`.
*
* @return array[]|WP_Error 2D array of state => IDs
*/
public function get_members_in_states ($states = array()) {
$defaults = array('confirmed', 'unconfirmed', 'invited');
$states = wp_parse_args($states, $defaults);
$ret = array();
foreach ($states as $state) {
switch ($state) {
case 'confirmed':
case 'unconfirmed':
case 'invited':
$func = "get_{$state}_members";
$ret[$state] = $this->$func();
break;
default:
return new WP_Error(
'no-such-state',
__('Invalid state for membership.', 'buoy'),
$state
);
break;
}
}
return $ret;
}
/**
* Checks whether or not this team is the user's default team.
*
* @uses WP_Buoy_User_Settings::get()
*
* @return bool
*/
public function is_default () {
$usropt = new WP_Buoy_User_Settings($this->author->ID);
return $this->wp_post->ID == $usropt->get('default_team');
}
/**
* Makes this team the default team of the author.
*
* @uses WP_Buoy_User_Settings::set()
* @uses WP_Buoy_User_Settings::save()
*
* @return WP_Buoy_Team
*/
public function make_default () {
$usropt = new WP_Buoy_User_Settings($this->author->ID);
$usropt->set('default_team', $this->wp_post->ID)->save();
return $this;
}
/**
* Gets a list of all the user IDs associated with this team.
*
* This does not do any checking about whether the given user ID
* is "confirmed" or not.
*
* @return string[] IDs are actually returned as string values.
*/
public function get_member_ids () {
return array_unique(get_post_meta($this->wp_post->ID, '_team_members'));
}
/**
* Gets a list of all email addresses invited to join this team.
*
* @return string[]
*/
public function get_invited_members () {
return array_unique(get_post_meta($this->wp_post->ID, '_invitees'));
}
/**
* Checks whether or not the given user ID is on the team.
*
* This does not check whether the user is confirmed or not, only
* whether the user has been at least invited to be a member of a
* team.
*
* @uses WP_Buoy_Team::get_member_ids()
*
* @param int $user_id
*
* @return bool
*/
public function is_member ($user_id) {
return in_array($user_id, $this->get_member_ids());
}
/**
* Adds an invitation for this email address to this team.
*
* @param string $email
*/
public function invite_user ($email) {
add_post_meta($this->wp_post->ID, '_invitees', $email, false);
/**
* Fires when a user is added or invited to a team.
*
* @param int|string $added A user ID or the email address of the new user.
* @param WP_Buoy_Team $this
*/
do_action(self::$prefix . '_team_member_added', $email, $this);
}
/**
* Adds a user to this team (a new member).
*
* @uses add_post_meta()
* @uses do_action()
*
* @param int $user_id
* @param bool $notify Whether or not to trigger a notification when adding.
*
* @return WP_Buoy_Team
*/
public function add_member ($user_id, $notify = true) {
add_post_meta($this->wp_post->ID, '_team_members', $user_id, false);
do_action(self::$prefix . '_team_member_added', $user_id, $this, $notify);
return $this;
}
/**
* Removes a member from this team.
*
* @uses delete_post_meta()
* @uses do_action()
*
* @param int $user_id
*
* @return WP_Buoy_Team
*/
public function remove_member ($user_id) {
delete_post_meta($this->wp_post->ID, '_team_members', $user_id);
delete_post_meta($this->wp_post->ID, '_invitees', $user_id);
/**
* Fires when a user is removed from a team.
*
* @param int $user_id
* @param WP_Buoy_Team $this
*/
do_action(self::$prefix . '_team_member_removed', $user_id, $this);
return $this;
}
/**
* Sets the confirmation flag for a user on this team.
*
* @uses add_post_meta()
*
* @param int $user_id
*
* @return WP_Buoy_Team
*/
public function confirm_member ($user_id) {
add_post_meta($this->wp_post->ID, "_member_{$user_id}_is_confirmed", true, true);
return $this;
}
/**
* Unsets the confirmation flag for a user on this team.
*
* @uses delete_post_meta()
*
* @param int $user_id
*
* @return WP_Buoy_Team
*/
public function unconfirm_member ($user_id) {
delete_post_meta($this->wp_post->ID, "_member_{$user_id}_is_confirmed");
return $this;
}
/**
* Checks whether or not a user is "confirmed" to be on the team.
*
* "Confirmation" consists of a flag in the team post's metadata.
*
* @uses get_post_meta()
*
* @param int $user_id
*
* @return bool
*/
public function is_confirmed ($user_id) {
return get_post_meta($this->wp_post->ID, "_member_{$user_id}_is_confirmed", true);
}
/**
* Checks to ensure there is at least one confirmed member on the
* team.
*
* A "responder" in this context is a confirmed team member.
*
* @uses WP_Buoy_Team::is_confirmed()
*
* @return bool
*/
public function has_responder () {
foreach ($this->members as $member) {
if ($this->is_confirmed($member->ID)) {
return true;
}
}
return false;
}
/**
* Gets the confirmed members of this team.
*
* @uses WP_Buoy_Team::get_member_ids()
* @uses WP_Buoy_Team::is_confirmed()
*
* @return int[]
*/
public function get_confirmed_members () {
$responders = array();
foreach ($this->get_member_ids() as $id) {
if ($this->is_confirmed($id)) {
$responders[] = $id;
}
}
return $responders;
}
/**
* Gets the unconfirmed members of this team.
*
* @uses WP_Buoy_Team::get_member_ids()
* @uses WP_Buoy_Team::is_confirmed()
*
* @return int[]
*/
public function get_unconfirmed_members () {
$responders = array();
foreach ($this->get_member_ids() as $id) {
if (!$this->is_confirmed($id)) {
$responders[] = $id;
}
}
return $responders;
}
/**
* @return void
*/
public static function register () {
if (!class_exists('Buoy_Team_Membership_List_Table')) {
require plugin_dir_path(__FILE__) . 'class-buoy-team-membership-list-table.php';
}
if (!class_exists('WP_Posts_List_Table')) {
require_once ABSPATH . 'wp-admin/includes/class-wp-posts-list-table.php';
}
$post_type = self::$prefix . '_team';
register_post_type($post_type, array(
'labels' => array(
'name' => __('Crisis Response Teams', 'buoy'),
'singular_name' => __('Crisis Response Team', 'buoy'),
'add_new_item' => __('Add New Team', 'buoy'),
'edit_item' => __('Edit Team', 'buoy'),
'new_item' => __('New Team', 'buoy'),
'view_item' => __('View Team', 'buoy'),
'search_items' => __('Search Teams', 'Buoy'),
'not_found' => __('No teams found', 'Buoy'),
'not_found_in_trash' => __('No teams found in Trash', 'buoy'),
'all_items' => __('All Teams', 'buoy'),
'menu_name' => __('My Teams', 'buoy')
),
'description' => __('Groups of crisis responders', 'buoy'),
'public' => false,
'show_ui' => true,
'capability_type' => $post_type,
'map_meta_cap' => true,
'hierarchical' => false,
'supports' => array(
'title',
'author'
),
'register_meta_box_cb' => array(__CLASS__, 'registerMetaBoxes'),
'has_archive' => false,
'rewrite' => false,
'can_export' => false,
'menu_icon' => plugins_url('img/icon-bw-life-preserver.svg', __FILE__)
));
add_action('load-post.php', array('WP_Buoy_Plugin', 'addHelpTab'));
add_action('load-post-new.php', array('WP_Buoy_Plugin', 'addHelpTab'));
add_action('load-edit.php', array('WP_Buoy_Plugin', 'addHelpTab'));
add_filter('enter_title_here', array(__CLASS__, 'filterTitlePlaceholder'), 10, 2);
// TODO: This should probably be moved so it loads only where needed.
if (is_admin()) {
wp_enqueue_style(
__CLASS__ . '-style',
plugins_url('css/admin-teams.css', __FILE__)
);
}
add_action('current_screen', array(__CLASS__, 'processTeamTableActions'));
add_action('admin_notices', array(__CLASS__, 'renderAdminNotices'));
add_action('admin_menu', array(__CLASS__, 'registerAdminMenu'));
add_action('pre_get_posts', array(__CLASS__, 'filterTeamPostsList'));
add_action('post_updated', array(__CLASS__, 'postUpdated'), 10, 3);
add_action("save_post_{$post_type}", array(__CLASS__, 'saveTeam'), 10, 2);
add_action('deleted_post_meta', array(__CLASS__, 'deletedPostMeta'), 10, 4);
add_action("{$post_type}_member_removed", array(__CLASS__, 'checkMemberCount'), 10, 2);
add_filter('user_has_cap', array(__CLASS__, 'filterCaps'));
add_filter("manage_{$post_type}_posts_columns", array(__CLASS__, 'filterTeamPostsColumns'));
add_filter("manage_edit-{$post_type}_sortable_columns", array(__CLASS__, 'filterSortableColumns'));
add_action('wp', array(__CLASS__, 'orderTeamPosts'));
add_action("manage_{$post_type}_posts_custom_column", array(__CLASS__, 'renderTeamPostsColumn'), 10, 2);
add_action('user_register', array(__CLASS__, 'checkInvitations'));
}
/**
* @param WP_Post $post
*
* @return void
*/
public static function registerMetaBoxes ($post) {
$team = new self($post->ID);
add_meta_box(
'add-team-member',
esc_html__('Add a team member', 'buoy'),
array(__CLASS__, 'renderAddTeamMemberMetaBox'),
null,
'normal',
'high'
);
add_meta_box(
'current-team',
sprintf(
esc_html__('Current team members %s', 'buoy'),
'<span class="count">(' . count($team->get_confirmed_members()) . ')</span>'
),
array(__CLASS__, 'renderCurrentTeamMetaBox'),
null,
'normal',
'high'
);
add_meta_box(
'default-team',
esc_html__('Default Team?', 'buoy'),
array(__CLASS__, 'renderDefaultTeamMetaBox'),
null,
'side',
'low'
);
}
/**
* @param WP_Post $post
*
* @return void
*/
public static function renderAddTeamMemberMetaBox ($post) {
wp_nonce_field(self::$prefix . '_add_team_member', self::$prefix . '_add_team_member_nonce');
require 'pages/add-team-member-meta-box.php';
}
/**
* @param WP_Post $post
*
* @return void
*/
public static function renderCurrentTeamMetaBox ($post) {
wp_nonce_field(self::$prefix . '_choose_team', self::$prefix . '_choose_team_nonce');
require 'pages/current-team-meta-box.php';
}
/**
* @param WP_Post $post
*
* @return void
*/
public static function renderDefaultTeamMetaBox ($post) {
$team = new WP_Buoy_Team($post->ID);
if ($team->is_default()) {
esc_html_e('This team is your default team.', 'buoy');
} else {
print sprintf(
esc_html__('No. You can make this team your default team from your %1$sTeams%2$s page.', 'buoy'),
'<a href="' . admin_url('edit.php?post_type=' . $post->post_type) . '">', '</a>'
);
}
}
/**
* @return void
*/
public static function renderTeamMembershipPage () {
$post_type = self::$prefix . '_team';
$team_table = new Buoy_Team_Membership_List_Table($post_type);
$team_table->prepare_items();
print '<div class="wrap">';
print '<form'
. ' action="' . admin_url('edit.php?post_type=' . $post_type . '&page=' . self::$prefix . '_team_membership') . '"'
. ' method="post">';
print '<h1>' . esc_html__('Team membership', 'buoy') . '</h1>';
$team_table->display();
print '</form>';
print '</div>';
}
/**
* Sets team parameters based on actions taken in Team admin UI.
*
* @link https://developer.wordpress.org/reference/hooks/current_screen/
*
* @global $_POST
* @global $_GET
*
* @uses WP_Screen::$post_type
* @uses WP_Posts_List_Table::current_action()
* @uses WP_Buoy_User_Settings::set()
* @uses WP_Buoy_User_Settings::save()
* @uses Buoy_Team_Membership_List_Table::current_action()
* @uses wp_verify_nonce()
* @uses WP_Buoy_Team::remove_member()
* @uses WP_Buoy_Team::confirm_member()
*
* @param WP_Screen $current_screen
*
* @return void
*/
public static function processTeamTableActions ($current_screen) {
$post_type = self::$prefix . '_team';
if ($post_type !== $current_screen->post_type) {
return;
}
if ('post' === $current_screen->base) {
// The "My Teams" page.
$table = new WP_Posts_List_Table();
if ('make_default' === $table->current_action()) {
$team = new WP_Buoy_Team(absint($_GET['post']));
$team->make_default();
$msg = self::$prefix . '-default-team-updated';
wp_safe_redirect(admin_url(
"edit.php?post_type={$current_screen->post_type}&msg=$msg"
));
exit();
}
} else if ("{$post_type}_page_{$post_type}_membership") {
// The "Team Membership" page.
$table = new Buoy_Team_Membership_List_Table($post_type);
$teams = array();
if (isset($_GET['_wpnonce']) && wp_verify_nonce($_GET['_wpnonce'], 'single-' . $table->_args['plural'])) {
$teams[] = $_GET['team_id'];
} else if (isset($_POST['_wpnonce']) && wp_verify_nonce($_POST['_wpnonce'], 'bulk-' . $table->_args['plural'])) {
$teams = array_merge($teams, $_POST['teams']);
}
if (!empty($teams)) {
foreach ($teams as $team_id) {
$team = new self($team_id);
if ('leave' === $table->current_action()) {
$team->remove_member(get_current_user_id());
}
if ('join' === $table->current_action()) {
$team->confirm_member(get_current_user_id());
}
}
wp_safe_redirect(admin_url(
'edit.php?page=' . urlencode($_GET['page'])
. '&post_type=' . urlencode($_GET['post_type'])
));
exit();
}
}
}
/**
* Prints an admin notice for the given message code.
*
* @global $_GET['msg']
*
* @return void
*/
public static function renderAdminNotices () {
if (isset($_GET['msg'])) {
$notices = array(
// message-code => array('class' => 'css-class', 'message' => "Message text.")
self::$prefix . '-default-team-updated' => array(
'class' => 'notice updated is-dismissible',
'message' => esc_html__('Default team updated.', 'buoy')
)
);
if (array_key_exists($_GET['msg'], $notices)) {
?>
<div class="<?php print esc_attr($notices[$_GET['msg']]['class']);?>">
<p><?php print esc_html($notices[$_GET['msg']]['message']);?></p>
</div>
<?php
}
}
}
/**
* Checks to ensure a user doesn't leave themselves without any
* responders.
*
* Teams are only "active" is they are in the "publish" status.
* This checks a team transition and if the action leaves a user
* without any responders, it will re-set the team's status.
*
* @link https://developer.wordpress.org/reference/hooks/post_updated/
*
* @uses WP_Buoy_User::has_responder()
* @uses WP_Buoy_Team::is_default()
* @uses WP_Buoy_Team::make_default()
*
* @param int $post_id
* @param WP_Post $post_after
* @param WP_Post $post_before
*
* @return void
*/
public static function postUpdated ($post_id, $post_after, $post_before) {
if (self::$prefix . '_team' !== $post_after->post_type) {
return;
}
$buoy_user = new WP_Buoy_User($post_before->post_author);
// Prevent the user from trashing their last responder team.
if ('publish' === $post_before->post_status && 'publish' !== $post_after->post_status) {
if (!$buoy_user->has_responder()) {
wp_update_post(array(
'ID' => $post_id,
'post_status' => 'publish'
));
}
}
// Re-set the default team if the default team is trashed.
$team = new WP_Buoy_Team($post_id);
if ('trash' === $post_after->post_status && $team->is_default()) {
$teams = $buoy_user->get_teams();
$next_team = new WP_Buoy_Team(array_pop($teams));
$next_team->make_default();
}
}
/**
* Updates the team metadata (membership list).
*
* This is called by WordPress's `save_post_{$post->post_type}` hook.
*
* @link https://developer.wordpress.org/reference/hooks/save_post_post-post_type/
*
* @global $_POST
*
* @uses wp_verify_nonce()
* @uses WP_Buoy_Team::remove_member()
* @uses WP_Buoy_Team::get_member_ids()
* @uses WP_Buoy_Team::add_member()
*
* @param int $post_id
* @param WP_Post $post
*
* @return void
*/
public static function saveTeam ($post_id, $post) {
$team = new self($post_id);
// Remove any team members indicated.
if (isset($_POST[self::$prefix . '_choose_team_nonce']) && wp_verify_nonce($_POST[self::$prefix . '_choose_team_nonce'], self::$prefix . '_choose_team')) {
if (isset($_POST['remove_team_members'])) {
foreach ($_POST['remove_team_members'] as $id) {
$team->remove_member($id);
}
}
}
// Add a new team member
if (isset($_POST[self::$prefix . '_add_team_member_nonce']) && wp_verify_nonce($_POST[self::$prefix . '_add_team_member_nonce'], self::$prefix . '_add_team_member')) {
$add_team_member_input = $_POST[self::$prefix . '_add_team_member'];
$user_id = username_exists($add_team_member_input);
if (false !== $user_id) {
if (!in_array($user_id, $team->get_member_ids())) {
$team->add_member($user_id);
}
} else {
if (is_email($add_team_member_input)) {
$email = $add_team_member_input;
$user = get_user_by('email', $email);
if ($user) {
$team->add_member($user->ID);
} else {
$team->invite_user($email);
}
}
}
}
// If this is the user's only team, make this the default one.
$cnt = count(get_posts(array(
'post_type' => $post->post_type,
'author' => $post->post_author,
'fields' => 'ids'
)));
if (0 === $cnt) {
$team->make_default();
}
}
/**
* Hooks the `deleted_post_meta` action.
*
* This is used primarily to detect when a user is removed from a
* team and, when this occurrs, remove the confirmation flag, too.
*
* @link https://developer.wordpress.org/reference/hooks/deleted_meta_type_meta/
*
* @param array $meta_ids
* @param int $post_id
* @param string $meta_key
* @param mixed $meta_value
*
* @return void
*/
public static function deletedPostMeta ($meta_ids, $post_id, $meta_key, $meta_value) {
$team = new self($post_id);
if ('_team_members' === $meta_key) {
// delete confirmation when removing a team member
$team->unconfirm_member($meta_value);
}
}
/**
* Checks if a team no longer has any members.
*
* If a team is emptied for any reason, whether because the user
* has removed all their members or the members themselves decide
* to leave, this will fire a "{$post->post_type}_emptied" hook.
*
* @param int $user_id The user who was just removed.
* @param WP_Buoy_Team The team they left.
*/
public static function checkMemberCount ($user_id, $team) {
$ids = $team->get_member_ids();
if (empty($ids)) {
/**
* Fires after the last member of a team is removed (or leaves).
*
* @param WP_Buoy_Team $team
*/
do_action($team->wp_post->post_type . '_emptied', $team);
}
}
/**
* @return void
*/
public static function registerAdminMenu () {
$hooks = array();
$hooks[] = add_submenu_page(
'edit.php?post_type=' . self::$prefix . '_team',
__('Team membership', 'buoy'),
__('Team membership', 'buoy'),
'read',
self::$prefix . '_team_membership',
array(__CLASS__, 'renderTeamMembershipPage')
);
foreach ($hooks as $hook) {
add_action('load-' . $hook, array('WP_Buoy_Plugin', 'addHelpTab'));
}
}
/**
* Dynamically configures user capabilities.
* This dynamism prevents the need to write capabilities into the
* database's `options` table's `wp_user_roles` record itself.
*
* Currently simply unconditionally gives every user the required
* capabilities to manage their own crisis response teams.
*
* Called by the `user_has_cap` filter.
*
* @link https://developer.wordpress.org/reference/hooks/user_has_cap/
*
* @param array $caps The user's actual capabilities.
*
* @return array $caps
*/
public static function filterCaps ($caps) {
$caps['edit_' . self::$prefix . '_teams'] = true;
$caps['delete_' . self::$prefix . '_teams'] = true;
$caps['publish_' . self::$prefix . '_teams'] = true;
$caps['edit_published_' . self::$prefix . '_teams'] = true;
$caps['delete_published_' . self::$prefix . '_teams'] = true;
return $caps;
}
/**
* Sets the placeholder text for the "New Team" page.
*
* @link https://developer.wordpress.org/reference/hooks/enter_title_here/
*
* @param string $text
* @param WP_Post $post
*
* @return string
*/
public static function filterTitlePlaceholder ($text, $post) {
if (self::$prefix . '_team' === $post->post_type) {
$text = __('Enter team name here', 'buoy');
}
return $text;
}
/**
* Add custom columns shown in the "My Teams" admin UI.
*
* @link https://developer.wordpress.org/reference/hooks/manage_post_type_posts_columns/
*
* @param array $post_columns
*
* @return array
*/
public static function filterTeamPostsColumns ($post_columns) {
unset($post_columns['author']);
$post_columns['num_members'] = __('Members', 'buoy');
$post_columns['confirmed_members'] = __('Confirmed Members', 'buoy');
$post_columns['default_team'] = __('Default Team?', 'buoy');
return $post_columns;
}
/**
* Makes the custom columns sortable in the "My Teams" admin UI.
*
* @link https://developer.wordpress.org/reference/hooks/manage_this-screen-id_sortable_columns/
*
* @param array $sortable_columns
*
* @return array
*/
public static function filterSortableColumns ($sortable_columns) {
$sortable_columns['num_members'] = self::$prefix . '_team_member_count';
$sortable_columns['confirmed_members'] = self::$prefix . '_team_confirmed_members';
return $sortable_columns;
}
/**
* Re-orders the query results based on the team member count.
*
* This changes the global `$wp_query->posts` array directly.
*
* @todo Possibly the count should be its own meta field managed by us so this hook is more performant?
*
* @global $wp_query
*
* @uses WP_Buoy_Team::get_member_ids()
* @uses WP_Buoy_Team::get_confirmed_members()
*
* @param WP $wp
*
* @return void
*/
public static function orderTeamPosts ($wp) {
if (is_admin() && isset($wp->query_vars['orderby'])) {
if (self::$prefix . '_team_member_count' === $wp->query_vars['orderby']) {
$method = 'get_member_ids';
} else if (self::$prefix . '_team_confirmed_members' === $wp->query_vars['orderby']) {
$method = 'get_confirmed_members';
}
if (isset($method)) {
global $wp_query;
$member_counts = array();
foreach ($wp_query->posts as $post) {
$team = new WP_Buoy_Team($post->ID);
$member_counts[count($team->$method())][] = $post; // variable function
}
ksort($member_counts);
if ('desc' === $wp->query_vars['order']) {
$member_counts = array_reverse($member_counts);
}
$sorted = array();
foreach ($member_counts as $counts) {
foreach ($counts as $post) {
$sorted[] = $post;
}
}
$wp_query->posts = $sorted;
}
}
}
/**
* Add the column content for custom columns in the "My Teams" UI.
*
* @link https://developer.wordpress.org/reference/hooks/manage_post-post_type_posts_custom_column/
*
* @param string $column_name
* @param int $post_id
*
* @return void
*/
public static function renderTeamPostsColumn ($column_name, $post_id) {
$team = new WP_Buoy_Team($post_id);
switch ($column_name) {
case 'num_members':
print esc_html(count($team->get_member_ids()));
break;
case 'confirmed_members':
print esc_html(count($team->get_confirmed_members()));
break;
case 'default_team':
if ($team->is_default()) {
print '<strong>' . esc_html__('Yes', 'buoy') . '</strong>';
}
break;
}
}
/**
* Ensures that users can only see their own crisis teams in the
* WP admin view when viewing their "My Teams" dashboard page.
*
* @param WP_Query $query
*
* @return void
*/
public static function filterTeamPostsList ($query) {
if (is_admin() && $screen = get_current_screen()) {
if ('edit-' . self::$prefix .'_team' === $screen->id && current_user_can('edit_' . self::$prefix . '_teams')) {
$query->set('author', get_current_user_id());
add_filter('views_' . $screen->id, array(__CLASS__, 'filterTeamPostViews'));
add_filter('post_row_actions', array(__CLASS__, 'postRowActions'), 10, 2);
}
}
}
/**
* Removes the views links in the Team posts table.
*
* @link https://developer.wordpress.org/reference/hooks/views_this-screen-id/
*
* @param array $items
*
* @return array
*/
public static function filterTeamPostViews ($items) {
return array(); // remove all view links
}
/**
* Customizes the post row actions in the "My Teams" admin UI.
*
* @link https://developer.wordpress.org/reference/hooks/post_row_actions/
*
* @uses WP_Buoy_Team::is_default()
* @uses WP_Buoy_Team::has_responder()
*
* @param array $items
* @param WP_Post $post
*
* @return array $items
*/
public static function postRowActions ($items, $post) {
$team = new WP_Buoy_Team($post->ID);
if (!$team->is_default() && $team->has_responder() && 'publish' === $post->post_status) {
$url = admin_url('post.php?post=' . $post->ID . '&action=make_default');
$items['default'] = '<a href="' . esc_attr($url) . '">' . __('Make default', 'buoy') . '</a>';
}
unset($items['inline hide-if-no-js']); // the "Quick Edit" link
return $items;
}
/**
* Adds a user to teams they were invited to join before they had
* created an account.
*
* @param int $user_id
*
* @return void
*/
public static function checkInvitations ($user_id) {
$user = get_userdata($user_id);
$team_posts = self::getAllTeamPosts();
foreach ($team_posts as $post) {
$team = new WP_Buoy_Team($post->ID);
if (in_array($user->user_email, $team->get_invited_members())) {
$team->remove_member($user->user_email); // removes the invitation
$team->add_member($user_id, false); // then adds the user
}
}
}
/**
* Gets a list of all team posts.
*
* @return WP_Post[]
*/
public static function getAllTeamPosts () {
return get_posts(array(
'post_type' => self::$prefix . '_team',
'post_status' => array('publish', 'draft', 'trash'),
'posts_per_page' => -1
));