summaryrefslogtreecommitdiff
blob: 7bce34625b2e8ef76307f3a838f4712a1e01ab8d (plain)
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
<?php
/**
 * A user roles class for Jetpack.
 *
 * @package automattic/jetpack-roles
 */

namespace Automattic\Jetpack;

/**
 * Class Automattic\Jetpack\Roles
 *
 * Contains utilities for translating user roles to capabilities and vice versa.
 */
class Roles {
	/**
	 * Map of roles we care about, and their corresponding minimum capabilities.
	 *
	 * @access protected
	 *
	 * @var array
	 */
	protected $capability_translations = array(
		'administrator' => 'manage_options',
		'editor'        => 'edit_others_posts',
		'author'        => 'publish_posts',
		'contributor'   => 'edit_posts',
		'subscriber'    => 'read',
	);

	/**
	 * Get the role of the current user.
	 *
	 * @access public
	 *
	 * @return string|boolean Current user's role, false if not enough capabilities for any of the roles.
	 */
	public function translate_current_user_to_role() {
		foreach ( $this->capability_translations as $role => $cap ) {
			if ( current_user_can( $role ) || current_user_can( $cap ) ) {
				return $role;
			}
		}

		return false;
	}

	/**
	 * Get the role of a particular user.
	 *
	 * @access public
	 *
	 * @param \WP_User $user User object.
	 * @return string|boolean User's role, false if not enough capabilities for any of the roles.
	 */
	public function translate_user_to_role( $user ) {
		foreach ( $this->capability_translations as $role => $cap ) {
			if ( user_can( $user, $role ) || user_can( $user, $cap ) ) {
				return $role;
			}
		}

		return false;
	}

	/**
	 * Get the minimum capability for a role.
	 *
	 * @access public
	 *
	 * @param string $role Role name.
	 * @return string|boolean Capability, false if role isn't mapped to any capabilities.
	 */
	public function translate_role_to_cap( $role ) {
		if ( ! isset( $this->capability_translations[ $role ] ) ) {
			return false;
		}

		return $this->capability_translations[ $role ];
	}
}