-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclasses.groups.php
More file actions
873 lines (668 loc) · 20 KB
/
classes.groups.php
File metadata and controls
873 lines (668 loc) · 20 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
<?php
/**
* Section editor group controller
*
* @todo investigate replacing in-memory groups store with cache API
*/
class BU_Edit_Groups {
const POST_TYPE_NAME = 'buse_group';
const MEMBER_KEY = '_bu_section_group_users';
const GLOBAL_EDIT = '_bu_section_group_global_edit';
public $groups = array();
static protected $instance;
/**
* Load groups and index from db on instantiation
*
* Usage of global singleton pattern assures this method is only called once
*/
protected function __construct() {
// Load group data
$this->load();
}
/**
* Generates/fetches global singleton instance
*/
static public function get_instance() {
if ( ! isset( BU_Edit_Groups::$instance ) ) {
BU_Edit_Groups::$instance = new BU_Edit_Groups();
}
return BU_Edit_Groups::$instance;
}
static public function register_hooks() {
add_action( 'init', array( __CLASS__, 'register_post_type' ) );
}
/**
* Register hidden post type for group data storage
*/
static public function register_post_type() {
$labels = array(
'name' => _x( 'Section Groups', 'Post Type General Name', BUSE_TEXTDOMAIN ),
'singular_name' => _x( 'Section Group', 'Post Type Singular Name', BUSE_TEXTDOMAIN ),
);
$args = array(
'labels' => $labels,
'supports' => array(),
'hierarchical' => false,
'public' => false,
'show_ui' => false,
'show_in_menu' => false,
'show_in_nav_menus' => false,
'show_in_admin_bar' => false,
'menu_position' => 5,
'menu_icon' => '',
'can_export' => true,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'rewrite' => false,
'capability_type' => 'post',
);
register_post_type( self::POST_TYPE_NAME, $args );
}
// ___________________PUBLIC_INTERFACE_____________________
/**
* Returns a group by ID from internal groups array
*
* @param int $id unique ID of section group to return
* @return BU_Edit_Group|bool the requested section group object, or false on bad ID
*/
public function get( $id ) {
foreach ( $this->groups as $group ) {
if ( $group->id == $id ) {
return $group;
}
}
return false;
}
/**
* Add a group object to the internal groups array
*
* @param BU_Edit_Group $group a valid section editing group object
*/
public function add( $group ) {
if ( ! $group instanceof BU_Edit_Group ) {
return false;
}
$this->groups[] = $group;
}
/**
* Remove a group by ID from the internal groups array
*
* @param int $id unique ID of section group to delete
* @return BU_Edit_Group|bool the deleted section group object on success, otherwise false
*/
public function delete( $id ) {
foreach ( $this->groups as $i => $g ) {
if ( $g->id == $id ) {
unset( $this->groups[ $i ] );
$this->groups = array_values( $this->groups ); // reindex
return $g;
}
}
return false;
}
/**
* Return an array of all groups
*
* @todo *_groups methods usually touch the DB
* - investigate renaming to get_all()
*
* @return type
*/
public function get_groups() {
return $this->groups;
}
/**
* Remove all groups from internal array
*
* @todo *_groups methods usually touch the DB
* - investigate renaming to delete_all()
*/
public function delete_groups() {
$this->groups = array();
}
/**
* Add a new section editing group
*
* @param array $data an array of parameters for group initialization
* @return BU_Edit_Group the group that was just added
*/
public function add_group( $data ) {
// Sanitize input
$this->_clean_group_data( $data );
// Create new group from args
$group = $this->insert( $data );
if ( ! $group instanceof BU_Edit_Group ) {
return false;
}
// Set permissions
if ( isset( $data['perms'] ) ) {
BU_Group_Permissions::update_group_permissions( $group->id, $data['perms'] );
}
// Notify
add_action( 'bu_add_section_editing_group', $group );
return $group;
}
/**
* Update an existing section editing group
*
* @param int $id the id of the group to update
* @param array $data an array of parameters with group fields to update
* @return BU_Edit_Group|bool the group that was just updated or false if none existed
*/
public function update_group( $id, $data = array() ) {
if ( $this->get( $id ) === false ) {
return false;
}
// Sanitize.
$this->_clean_group_data( $data );
// Update group.
$group = $this->update( $id, $data );
if ( ! $group instanceof BU_Edit_Group ) {
return false;
}
// Update permissions.
if ( isset( $data['perms'] ) ) {
BU_Group_Permissions::update_group_permissions( $group->id, $data['perms'] );
}
return $group;
}
/**
* Delete an existing section editing group
*
* @param int $id the id of the group to delete
* @return bool true on success, false on failure
*/
public function delete_group( $id ) {
// Remove group.
$group = $this->delete( $id );
if ( ! $group ) {
error_log( 'Error deleting group: ' . $id );
return false;
}
// Delete from db
$result = wp_delete_post( $id, true );
if ( $result === false ) {
return false;
}
// Remove group permissions.
BU_Group_Permissions::delete_group_permissions( $id );
return true;
}
/**
* Returns an array of group ID's for which the specified user is a member
*
* @param int $user_id WordPress user id
* @return array array of group ids for which the specified user belongs
*/
public function find_groups_for_user( $user_id, $output = 'objects' ) {
$groups = array();
foreach ( $this->groups as $group ) {
if ( $group->has_user( $user_id ) ) {
if ( $output === 'objects' ) {
$groups[ $group->id ] = $group;
} else if ( $output === 'ids' ) {
array_push( $groups, $group->id );
}
}
}
return $groups;
}
/**
* Returns whether or not a user exists in an array of edit groups
*
* @todo remove this if it unused
*
* @param array $groups an array of BU_Edit_Group objects to check
* @param int $user_id WordPress user id to check
*/
public function has_user( $groups, $user_id ) {
if ( ! is_array( $groups ) ) {
$groups = array( $groups );
}
foreach ( $groups as $group_id ) {
$group = $this->get( $group_id );
if ( $group && $group->has_user( $user_id ) ) {
return true;
}
}
return false;
}
/**
* Get allowed post ids, optionally filtered by user ID, group or post_type
*
* @todo implement caching with md5 of args
* @todo possibly move to BU_Group_Permissions
*
* @param $args array optional args
*
* @return array post ids for the given post type, group or user
*/
public function get_allowed_posts( $args = array() ) {
global $wpdb, $bu_navigation_plugin;
$defaults = array(
'user_id' => null,
'group' => null,
'post_type' => null,
'include_unpublished' => false,
'include_links' => true,
);
extract( wp_parse_args( $args, $defaults ) );
$group_ids = array();
// If user_id is passed, populate group ID's from their memberships
if ( $user_id ) {
if ( is_null( get_userdata( $user_id ) ) ) {
error_log( 'No user found for ID: ' . $user_id );
return array();
}
// Get groups for users
$group_ids = $this->find_groups_for_user( $user_id, 'ids' );
}
// If no user ID is passed, but a group is, convert to array
if ( is_null( $user_id ) && $group ) {
if ( is_array( $group ) ) {
$group_ids = $group;
}
if ( is_numeric( $group ) && $group > 0 ) {
$group_ids = array( $group );
}
}
// Bail if we don't have any valid groups by now
if ( empty( $group_ids ) ) {
return array();
}
// Generate query
$post_type_clause = $post_status_clause = '';
// Maybe filter by post type and status
if ( ! is_null( $post_type ) && ! is_null( $pto = get_post_type_object( $post_type ) ) ) {
// Only a single post type is expected, so it should be prepared as a string.
$post_type_clause = $wpdb->prepare( "AND post_type = %s", $post_type );
if ( $include_links && $post_type == 'page' && isset( $bu_navigation_plugin ) ) {
if ( $bu_navigation_plugin->supports( 'links' ) ) {
$link_post_type = defined( 'BU_NAVIGATION_LINK_POST_TYPE' ) ? BU_NAVIGATION_LINK_POST_TYPE : 'bu_link';
// Only a single post type string is passed, so it can be prepared as normal.
$post_type_clause = $wpdb->prepare( "AND post_type IN ('page', %s) ", $link_post_type );
}
}
}
// Include unpublished should only work for hierarchical post types
if ( $include_unpublished ) {
// Flat post types are not allowed to include unpublished, as perms can be set for drafts
if ( $post_type ) {
$pto = get_post_type_object( $post_type );
if ( $pto->hierarchical ) {
// The `$post_type_clause` statement is prepared above and can be considered safe here.
$post_status_clause = "OR (post_status IN ('draft','pending') $post_type_clause)";
}
} else {
$post_status_clause = "OR post_status IN ('draft','pending')";
}
}
// Prepare the first section of the SQL statement.
$count_query = $wpdb->prepare(
"SELECT ID FROM {$wpdb->posts} WHERE ( ID IN ( SELECT post_ID FROM {$wpdb->postmeta} WHERE meta_key = %s",
BU_Group_Permissions::META_KEY
);
// Build the remaining SQL from previously prepared statements. The `group_ids` array is forced to integer values for safety.
$count_query .= " AND meta_value IN (" . implode( ',', array_map( 'intval', $group_ids ) ) . ') ) ' . $post_type_clause . ') ' . $post_status_clause;
// Execute query
$ids = $wpdb->get_col( $count_query ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
return $ids;
}
/**
* Get allowed post count, optionally filtered by user ID, group or post_type
*
* @param $args array optional args
*
* @return int allowed post count for the given post type, group or user
*/
public function get_allowed_post_count( $args = array() ) {
$ids = $this->get_allowed_posts( $args );
return count( $ids );
}
// ____________________PERSISTENCE________________________
/**
* Load all groups
*/
public function load() {
$args = array(
'post_type' => self::POST_TYPE_NAME,
'numberposts' => -1,
'order' => 'ASC',
);
$group_posts = get_posts( $args );
if ( is_array( $group_posts ) ) {
foreach ( $group_posts as $group_post ) {
$this->groups[] = $this->_post_to_group( $group_post );
}
}
}
/**
* Save all groups
*
* @todo refactor so that both insert and update groups utilize this method
* @todo test coverage
*/
public function save() {
$result = true;
foreach ( $this->groups as $group ) {
$postdata = $this->_group_to_post( $group );
// Update DB
$result = wp_insert_post( $postdata );
// Set group ID with post ID if needed
if ( $group->id < 0 ) {
$group->id = $result;
}
if ( is_wp_error( $result ) ) {
error_log( sprintf( 'Error updating group %s: %s', $group->id, $result->get_error_message() ) );
$result = false;
}
// Update meta data
update_post_meta( $group->id, self::MEMBER_KEY, $group->users );
update_post_meta( $group->id, self::GLOBAL_EDIT, $group->global_edit );
}
return $result;
}
/**
* Insert a new group
*
* @todo test coverage
*
* @param array $data a parameter list of group data for insertion
* @return bool|BU_Edit_Group False on failure. A BU_Edit_Group instance for the new group on success.
*/
protected function insert( $data ) {
// Create new group
$group = new BU_Edit_Group( $data );
// Map group data to post for insertion
$postdata = $this->_group_to_post( $group );
// Insert into DB
$result = wp_insert_post( $postdata );
if ( is_wp_error( $result ) ) {
error_log( sprintf( 'Error adding group: %s', $result->get_error_message() ) );
return false;
}
// Add auto-generated ID
$group->id = $result;
// Add meta data
add_post_meta( $group->id, self::MEMBER_KEY, $group->users );
add_post_meta( $group->id, self::GLOBAL_EDIT, $group->global_edit );
// Add group to internal groups store
$this->groups[] = $group;
return $group;
}
/**
* Update an existing group
*
* @todo test coverage
*
* @param int $id ID of group to update
* @param array $data a parameter list of group data for update
* @return bool|BU_Edit_Group False on failure. A BU_Edit_Group instance for the updated group on success.
*/
protected function update( $id, $data ) {
// Fetch existing group
$group = $this->get( $id );
if ( ! $group instanceof BU_Edit_Group ) {
return false;
}
// Update group data
$group->update( $data );
// Map group data to post for update
$postdata = $this->_group_to_post( $group );
// Update DB
$result = wp_update_post( $postdata );
if ( is_wp_error( $result ) ) {
error_log( sprintf( 'Error updating group %s: %s', $group->id, $result->get_error_message() ) );
return false;
}
// Update modified time stamp
$group->modified = get_post_modified_time( 'U',false,$result );
// Update meta data
update_post_meta( $group->id, self::MEMBER_KEY, $group->users );
update_post_meta( $group->id, self::GLOBAL_EDIT, $group->global_edit );
// Update internal groups store
foreach ( $this->groups as $i => $g ) {
if ( $g->id == $group->id ) {
$this->groups[ $i ] = $group;
}
}
return $group;
}
/**
* Sanitizes array of group data prior to group creation or updating
*/
protected function _clean_group_data( &$args ) {
// Process input
$args['name'] = sanitize_text_field( stripslashes( $args['name'] ) );
$args['description'] = isset( $args['description'] ) ? sanitize_text_field( stripslashes( $args['description'] ) ) : '';
$args['users'] = isset( $args['users'] ) ? array_map( 'absint', $args['users'] ) : array();
if ( ! isset( $args['global_edit'] ) || ! is_array( $args['global_edit'] ) ) {
$args['global_edit'] = array();
}
$sanitized_global_edit_value = array();
foreach ($args['global_edit'] as $custom_type) {
if ( post_type_exists( $custom_type ) ) {
if ( ! is_post_type_hierarchical( $custom_type ) ) {
$sanitized_global_edit_value[] = $custom_type;
}
}
}
$args['global_edit'] = $sanitized_global_edit_value;
if ( isset( $args['perms'] ) && is_array( $args['perms'] ) ) {
foreach ( $args['perms'] as $post_type => $ids_by_status ) {
if ( ! is_array( $ids_by_status ) ) {
error_log( "Unepected value for permissions data: $ids_by_status" );
unset( $args['perms'][ $post_type ] );
continue;
}
if ( ! isset( $ids_by_status['allowed'] ) ) {
$args['perms'][ $post_type ]['allowed'] = array();
}
if ( ! isset( $ids_by_status['denied'] ) ) {
$args['perms'][ $post_type ]['denied'] = array();
}
foreach ( $ids_by_status as $status => $post_ids ) {
if ( ! in_array( $status, array( 'allowed', 'denied', '' ) ) ) {
error_log( "Unexpected status: $status" );
unset( $args['perms'][ $post_type ][ $status ] );
}
}
}
}
}
/**
* Maps a group object to post object
*
* @param BU_Edit_Group $group Group object for translation
* @return StdClass $post Resulting post object
*/
protected function _group_to_post( $group ) {
$post = new stdClass();
if ( $group->id > 0 ) {
$post->ID = $group->id;
}
$post->post_type = self::POST_TYPE_NAME;
$post->post_title = $group->name;
$post->post_content = $group->description;
$post->post_status = 'publish';
return $post;
}
/**
* Maps a WP post object to group object
*
* @param StdClass $post Post object for translation
* @return BU_Edit_Group $group Resulting group object
*/
protected function _post_to_group( $post ) {
// Map post -> group fields
$data['id'] = $post->ID;
$data['name'] = $post->post_title;
$data['description'] = $post->post_content;
$data['created'] = strtotime( $post->post_date );
$data['modified'] = strtotime( $post->post_modified );
// Users and global_edit setting are stored in post meta
$users = get_post_meta( $post->ID, self::MEMBER_KEY, true );
$data['users'] = $users ? $users : array();
$global_edit = get_post_meta( $post->ID, self::GLOBAL_EDIT, true);
$data['global_edit'] = $global_edit;
// Create a new group
$group = new BU_Edit_Group( $data );
return $group;
}
/**
* Checks if the post (or post type) is marked as globally editable in this group
*
* @param int|string $post Post ID (int) or post type name (string)
* @param int $group_id Section editing group ID
* @return Boolean
*/
public function post_is_globally_editable_by_group( $post, $group_id )
{
if ($post === intval( $post )) {
$post_type = get_post_type($post);
}
else {
$post_type = $post;
}
$global_edit = get_post_meta( $group_id, BU_Edit_Groups::GLOBAL_EDIT, true);
return is_array( $global_edit ) && in_array( $post_type, $global_edit );
}
}
/**
* Class for listing groups (designed to be extended)
*
* @todo rework to use standard array traversal function and allow for keyed arrays
*/
class BU_Groups_List {
public $current_group;
public $edit_groups;
function __construct() {
$this->edit_groups = BU_Edit_Groups::get_instance();
$this->current_group = -1;
}
function have_groups() {
if ( count( $this->edit_groups->groups ) > 0 && $this->current_group < (count( $this->edit_groups->groups ) - 1) ) {
return true;
} else {
return false;
}
}
function the_group() {
$this->current_group++;
return $this->edit_groups->groups[ $this->current_group ];
}
function rewind() {
$this->current_group = -1;
}
}
/**
* A Section Editing group model
*/
class BU_Edit_Group {
private $id = null;
private $name = null;
private $description = null;
private $users = array();
private $global_edit = array();
private $created = null;
private $modified = null;
const MAX_NAME_LENGTH = 60;
/**
* Instantiate new edit group
*
* @param array $args optional parameter list to merge with defaults
*/
function __construct( $args = array() ) {
// Merge defaults
$defaults = $this->defaults();
$args = wp_parse_args( $args, $defaults );
// Update fields based on incoming parameter list
$fields = array_keys( $this->get_attributes() );
foreach ( $fields as $key ) {
$this->$key = $args[ $key ];
}
}
/**
* Returns an array with default parameter values for edit group
*
* @return array default values for edit group model
*/
private function defaults() {
$fields = array(
'id' => -1,
'name' => '',
'description' => '',
'users' => array(),
'global_edit' => array(),
'created' => time(),
'modified' => time(),
);
return $fields;
}
/**
* Does the specified user exist for this group?
*
* @todo test coverage
*
* @return bool true if user exists, false otherwise
*/
public function has_user( $user_id ) {
return in_array( $user_id, $this->users );
}
/**
* Add a new user to this group
*
* @todo test coverage
*
* @param int $user_id WordPress user ID to add for this group
*/
public function add_user( $user_id ) {
// need to make sure the user is a member of the site
if ( ! $this->has_user( $user_id ) ) {
array_push( $this->users, $user_id );
}
}
/**
* Remove a user from this group
*
* @todo test coverage
*
* @param int $user_id WordPress user ID to remove from this group
*/
public function remove_user( $user_id ) {
if ( $this->has_user( $user_id ) ) {
unset( $this->users[ array_search( $user_id, $this->users ) ] );
}
}
/**
* Update data fields for this group
*
* @param array $args an array of key => value parameters to update
*/
public function update( $args = array() ) {
$valid_fields = array_keys( $this->get_attributes() );
foreach ( $args as $key => $val ) {
if ( in_array( $key, $valid_fields ) ) {
$this->$key = $val;
}
}
}
/**
* Returns privata data field keys as an array of attribute names
*
* Used for data serialization
*/
public function get_attributes() {
return get_object_vars( $this );
}
public function __get( $key ) {
if ( isset( $this->$key ) ) {
return $this->$key;
}
return null;
}
public function __set( $key, $val ) {
$this->$key = $val;
}
}