/** * Get list of user roles * * @param array $roles * * @return array * * @access protected */ protected function getUserRoles($roles) { $response = array(); $names = wp_roles()->get_names(); foreach ($roles as $role) { if (isset($names[$role])) { $response[] = translate_user_role($names[$role]); } } return $response; }
/** * Count number of users who have each of the user roles. * * Assumes there are neither duplicated nor orphaned capabilities meta_values. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query() * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257. * * @since 3.0.0 * * @global wpdb $wpdb * * @param string $strategy 'time' or 'memory' * @return array Includes a grand total and an array of counts indexed by role strings. */ function count_users($strategy = 'time') { global $wpdb; // Initialize $id = get_current_blog_id(); $blog_prefix = $wpdb->get_blog_prefix($id); $result = array(); if ('time' == $strategy) { $avail_roles = wp_roles()->get_names(); // Build a CPU-intensive query that will return concise information. $select_count = array(); foreach ($avail_roles as $this_role => $name) { $select_count[] = $wpdb->prepare("COUNT(NULLIF(`meta_value` LIKE %s, false))", '%' . $wpdb->esc_like('"' . $this_role . '"') . '%'); } $select_count = implode(', ', $select_count); // Add the meta_value index to the selection list, then run the query. $row = $wpdb->get_row("SELECT {$select_count}, COUNT(*) FROM {$wpdb->usermeta} WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N); // Run the previous loop again to associate results with role names. $col = 0; $role_counts = array(); foreach ($avail_roles as $this_role => $name) { $count = (int) $row[$col++]; if ($count > 0) { $role_counts[$this_role] = $count; } } // Get the meta_value index from the end of the result set. $total_users = (int) $row[$col]; $result['total_users'] = $total_users; $result['avail_roles'] =& $role_counts; } else { $avail_roles = array(); $users_of_blog = $wpdb->get_col("SELECT meta_value FROM {$wpdb->usermeta} WHERE meta_key = '{$blog_prefix}capabilities'"); foreach ($users_of_blog as $caps_meta) { $b_roles = maybe_unserialize($caps_meta); if (!is_array($b_roles)) { continue; } foreach ($b_roles as $b_role => $val) { if (isset($avail_roles[$b_role])) { $avail_roles[$b_role]++; } else { $avail_roles[$b_role] = 1; } } } $result['total_users'] = count($users_of_blog); $result['avail_roles'] =& $avail_roles; } return $result; }
public function get_roles() { $roles = array(); foreach (wp_roles()->roles as $k => $role) { $roles[$k] = translate_user_role($role['name']); } return $roles; }
function add_roles_on_plugin_activation() { add_role('guard_role', 'Opiekun', array('read' => false)); add_role('teacher_role', 'Nauczyciel', array('read' => true)); $roles = array('editor', 'author', 'contributor', 'subscriber'); foreach ($roles as $role) { wp_roles()->remove_role($role); } }
/** * Role comparison must be done on role name, not role display name. * * @ticket 38234 */ public function test_get_users_with_no_role_matches_on_role_name() { // Create a role with a display name which would not match the role name // in a case-insentive SQL query. wp_roles()->add_role('somerole', 'Some role display name'); $someuser = self::factory()->user->create(array('role' => 'somerole')); $users = wp_get_users_with_no_role(); wp_roles()->remove_role('somerole'); $this->assertEmpty($users); }
/** * Generate HTML for a single row on the users.php admin panel. * * @since 3.1.0 * @since 4.2.0 The `$style` argument was deprecated. * @access public * * @param object $user_object The current user object. * @param string $style Deprecated. Not used. * @param string $role Optional. Key for the $wp_roles array. Default empty. * @param int $numposts Optional. Post count to display for this user. Defaults * to zero, as in, a new user has made zero posts. * @return string Output for a single row. */ public function single_row($user_object, $style = '', $role = '', $numposts = 0) { $wp_roles = wp_roles(); if (!$user_object instanceof WP_User) { $user_object = get_userdata((int) $user_object); } $user_object->filter = 'display'; $email = $user_object->user_email; if ($this->is_site_users) { $url = "site-users.php?id={$this->site_id}&"; } else { $url = 'users.php?'; } $checkbox = ''; // Check if the user for this row is editable if (current_user_can('list_users')) { // Set up the user editing link $edit_link = esc_url(add_query_arg('wp_http_referer', urlencode(wp_unslash($_SERVER['REQUEST_URI'])), get_edit_user_link($user_object->ID))); // Set up the hover actions for this user $actions = array(); if (current_user_can('edit_user', $user_object->ID)) { $edit = "<strong><a href=\"{$edit_link}\">{$user_object->user_login}</a></strong><br />"; $actions['edit'] = '<a href="' . $edit_link . '">' . __('Edit') . '</a>'; } else { $edit = "<strong>{$user_object->user_login}</strong><br />"; } if (!is_multisite() && get_current_user_id() != $user_object->ID && current_user_can('delete_user', $user_object->ID)) { $actions['delete'] = "<a class='submitdelete' href='" . wp_nonce_url("users.php?action=delete&user={$user_object->ID}", 'bulk-users') . "'>" . __('Delete') . "</a>"; } if (is_multisite() && get_current_user_id() != $user_object->ID && current_user_can('remove_user', $user_object->ID)) { $actions['remove'] = "<a class='submitdelete' href='" . wp_nonce_url($url . "action=remove&user={$user_object->ID}", 'bulk-users') . "'>" . __('Remove') . "</a>"; } /** * Filter the action links displayed under each user in the Users list table. * * @since 2.8.0 * * @param array $actions An array of action links to be displayed. * Default 'Edit', 'Delete' for single site, and * 'Edit', 'Remove' for Multisite. * @param WP_User $user_object WP_User object for the currently-listed user. */ $actions = apply_filters('user_row_actions', $actions, $user_object); // Set up the checkbox ( because the user is editable, otherwise it's empty ) $checkbox = '<label class="screen-reader-text" for="user_' . $user_object->ID . '">' . sprintf(__('Select %s'), $user_object->user_login) . '</label>' . "<input type='checkbox' name='users[]' id='user_{$user_object->ID}' class='{$role}' value='{$user_object->ID}' />"; } else { $edit = '<strong>' . $user_object->user_login . '</strong>'; } $role_name = isset($wp_roles->role_names[$role]) ? translate_user_role($wp_roles->role_names[$role]) : __('None'); $avatar = get_avatar($user_object->ID, 32); $r = "<tr id='user-{$user_object->ID}'>"; list($columns, $hidden, $sortable, $primary) = $this->get_column_info(); foreach ($columns as $column_name => $column_display_name) { $classes = "{$column_name} column-{$column_name}"; if ($primary === $column_name) { $classes .= ' has-row-actions column-primary'; } if ('posts' === $column_name) { $classes .= ' num'; // Special case for that column } if (in_array($column_name, $hidden)) { $classes .= ' hidden'; } $data = 'data-colname="' . wp_strip_all_tags($column_display_name) . '"'; $attributes = "class='{$classes}' {$data}"; if ('cb' === $column_name) { $r .= "<th scope='row' class='check-column'>{$checkbox}</th>"; } else { $r .= "<td {$attributes}>"; switch ($column_name) { case 'username': $r .= "{$avatar} {$edit}"; break; case 'name': $r .= "{$user_object->first_name} {$user_object->last_name}"; break; case 'email': $r .= "<a href='mailto:{$email}'>{$email}</a>"; break; case 'role': $r .= $role_name; break; case 'posts': if ($numposts > 0) { $r .= "<a href='edit.php?author={$user_object->ID}' class='edit'>"; $r .= '<span aria-hidden="true">' . $numposts . '</span>'; $r .= '<span class="screen-reader-text">' . sprintf(_n('%s post by this author', '%s posts by this author', $numposts), number_format_i18n($numposts)) . '</span>'; $r .= '</a>'; } else { $r .= 0; } break; default: /** * Filter the display output of custom columns in the Users list table. * * @since 2.8.0 * * @param string $output Custom column output. Default empty. * @param string $column_name Column name. * @param int $user_id ID of the currently-listed user. */ $r .= apply_filters('manage_users_custom_column', '', $column_name, $user_object->ID); } if ($primary === $column_name) { $r .= $this->row_actions($actions); } $r .= "</td>"; } } $r .= '</tr>'; return $r; }
/** * Retrieve all of the role capabilities and merge with individual capabilities. * * All of the capabilities of the roles the user belongs to are merged with * the users individual roles. This also means that the user can be denied * specific roles that their role might have, but the specific user isn't * granted permission to. * * @since 2.0.0 * @access public * * @return array List of all capabilities for the user. */ public function get_role_caps() { $wp_roles = wp_roles(); //Filter out caps that are not role names and assign to $this->roles if (is_array($this->caps)) { $this->roles = array_filter(array_keys($this->caps), array($wp_roles, 'is_role')); } //Build $allcaps from role caps, overlay user's $caps $this->allcaps = array(); foreach ((array) $this->roles as $role) { $the_role = $wp_roles->get_role($role); $this->allcaps = array_merge((array) $this->allcaps, (array) $the_role->capabilities); } $this->allcaps = array_merge((array) $this->allcaps, (array) $this->caps); return $this->allcaps; }
/** * Restore the current blog, after calling switch_to_blog() * * @see switch_to_blog() * @since MU * * @global wpdb $wpdb * @global array $_wp_switched_stack * @global int $blog_id * @global bool $switched * @global string $table_prefix * @global WP_Object_Cache $wp_object_cache * * @return bool True on success, false if we're already on the current blog */ function restore_current_blog() { global $wpdb; if (empty($GLOBALS['_wp_switched_stack'])) { return false; } $blog = array_pop($GLOBALS['_wp_switched_stack']); if ($GLOBALS['blog_id'] == $blog) { /** This filter is documented in libs/ms-blogs.php */ do_action('switch_blog', $blog, $blog); // If we still have items in the switched stack, consider ourselves still 'switched' $GLOBALS['switched'] = !empty($GLOBALS['_wp_switched_stack']); return true; } $wpdb->set_blog_id($blog); $prev_blog_id = $GLOBALS['blog_id']; $GLOBALS['blog_id'] = $blog; $GLOBALS['table_prefix'] = $wpdb->get_blog_prefix(); if (function_exists('wp_cache_switch_to_blog')) { wp_cache_switch_to_blog($blog); } else { global $wp_object_cache; if (is_object($wp_object_cache) && isset($wp_object_cache->global_groups)) { $global_groups = $wp_object_cache->global_groups; } else { $global_groups = false; } wp_cache_init(); if (function_exists('wp_cache_add_global_groups')) { if (is_array($global_groups)) { wp_cache_add_global_groups($global_groups); } else { wp_cache_add_global_groups(array('users', 'userlogins', 'usermeta', 'user_meta', 'useremail', 'userslugs', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', 'blog-id-cache', 'networks')); } wp_cache_add_non_persistent_groups(array('comment', 'counts', 'plugins')); } } if (did_action('init')) { wp_roles()->reinit(); $current_user = wp_get_current_user(); $current_user->for_blog($blog); } /** This filter is documented in libs/ms-blogs.php */ do_action('switch_blog', $blog, $prev_blog_id); // If we still have items in the switched stack, consider ourselves still 'switched' $GLOBALS['switched'] = !empty($GLOBALS['_wp_switched_stack']); return true; }
/** * Executes changes made in WordPress 4.4.0. * * @ignore * @since 4.4.0 * * @global int $wp_current_db_version Current version. * @global wpdb $wpdb WordPress database abstraction object. */ function upgrade_440() { global $wp_current_db_version, $wpdb; if ($wp_current_db_version < 34030) { $wpdb->query("ALTER TABLE {$wpdb->options} MODIFY option_name VARCHAR(191)"); } // Remove the unused 'add_users' role. $roles = wp_roles(); foreach ($roles->role_objects as $role) { if ($role->has_cap('add_users')) { $role->remove_cap('add_users'); } } }
/** * Return an associative array listing all the views that can be used * with this table. * * Provides a list of roles and user count for that role for easy * filtering of the user table. * * @since 3.1.0 * @access protected * * @global string $role * * @return array An array of HTML links, one for each view. */ protected function get_views() { global $role; $wp_roles = wp_roles(); if ($this->is_site_users) { $url = 'site-users.php?id=' . $this->site_id; switch_to_blog($this->site_id); $users_of_blog = count_users(); restore_current_blog(); } else { $url = 'users.php'; $users_of_blog = count_users(); } $total_users = $users_of_blog['total_users']; $avail_roles =& $users_of_blog['avail_roles']; unset($users_of_blog); $class = empty($role) ? ' class="current"' : ''; $role_links = array(); $role_links['all'] = "<a href='{$url}'{$class}>" . sprintf(_nx('All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_users, 'users'), number_format_i18n($total_users)) . '</a>'; foreach ($wp_roles->get_names() as $this_role => $name) { if (!isset($avail_roles[$this_role])) { continue; } $class = ''; if ($this_role === $role) { $class = ' class="current"'; } $name = translate_user_role($name); /* translators: User role name with count */ $name = sprintf(__('%1$s <span class="count">(%2$s)</span>'), $name, number_format_i18n($avail_roles[$this_role])); $role_links[$this_role] = "<a href='" . esc_url(add_query_arg('role', $this_role, $url)) . "'{$class}>{$name}</a>"; } if (!empty($avail_roles['none'])) { $class = ''; if ('none' === $role) { $class = ' class="current"'; } $name = __('No role'); /* translators: User role name with count */ $name = sprintf(__('%1$s <span class="count">(%2$s)</span>'), $name, number_format_i18n($avail_roles['none'])); $role_links['none'] = "<a href='" . esc_url(add_query_arg('role', 'none', $url)) . "'{$class}>{$name}</a>"; } return $role_links; }
/** * Gets the friendly display name of a user role * * @param WP_Role $role * * @return array|WP_Roles */ public static function get_role_display_name(WP_Role $role) { $displayName = wp_roles(); $displayName = $displayName->get_names(); $displayName = $displayName[$role->name]; return $displayName; }
function column_post_author($item) { $a_name = get_the_author_meta('display_name', $item['post_author']); //$a_role = get_the_author_meta('roles',$item['post_author'])[0]; $a_role = wp_roles()->role_names[get_the_author_meta('roles', $item['post_author'])[0]]; $display = $a_name . '<br/>(' . $a_role . ')'; $actions = array('view' => sprintf("<a href='%s'>作者資訊</a>", get_edit_profile_url($item['post_author']))); return sprintf('%1$s %2$s', $display, $this->row_actions($actions)); }
/** * Executes changes made in WordPress 4.4.0. * * @since 4.4.0 * * @global int $wp_current_db_version Current version. * @global wpdb $wpdb WordPress database abstraction object. */ function upgrade_440() { global $wp_current_db_version, $wpdb; if ($wp_current_db_version < 34030) { $wpdb->query("DROP INDEX {$wpdb->options}" . "_UK1 ON {$wpdb->options}"); $wpdb->query("ALTER TABLE {$wpdb->options} ALTER COLUMN option_name NVARCHAR(191) NOT NULL"); $wpdb->query("CREATE UNIQUE INDEX {$wpdb->options}" . "_UK1 on {$wpdb->options} (option_name)"); $wpdb->query("CREATE TABLE {$wpdb->termmeta} (meta_id int NOT NULL identity(1,1), term_id int NOT NULL default 0, meta_key nvarchar(255) default NULL, meta_value nvarchar(max), CONSTRAINT {$wpdb->termmeta}" . "_PK PRIMARY KEY NONCLUSTERED (meta_id))"); $wpdb->query("CREATE CLUSTERED INDEX {$wpdb->termmeta}" . "_CLU1 on {$wpdb->termmeta} (term_id)"); $wpdb->query("CREATE INDEX {$wpdb->termmeta}" . "_IDX2 on {$wpdb->termmeta} (meta_key)"); } // Remove the unused 'add_users' role. $roles = wp_roles(); foreach ($roles->role_objects as $role) { if ($role->has_cap('add_users')) { $role->remove_cap('add_users'); } } }
/** * Collect caps. * * @since 160524 Cap utils. * * @param bool $no_cache Bypass cache? * * @return array All collected caps. */ public function collectAll(bool $no_cache = false) : array { if (($collection =& $this->cacheKey(__FUNCTION__)) !== null && !$no_cache) { return $collection; // Already cached this. } $collection = []; // Initialize. foreach (wp_roles()->roles as $_role_id => $_role) { foreach (array_keys($_role['capabilities'] ?? []) as $_role_cap) { $collection[$_role_cap] = $_role_cap; } } // unset($_role_id, $_role, $_role_cap); // Housekeeping. $collection = array_merge($collection, $this->forRole('super_admin', $no_cache)); foreach (get_post_types([], 'objects') as $_post_type => $_post_type_object) { foreach ($_post_type_object->cap ?? [] as $_core_cap => $_post_type_cap) { if (!in_array($_core_cap, ['read_post', 'edit_post', 'delete_post'], true)) { // ↑ Do not include post meta caps; see: <http://jas.xyz/1XN7IKd> $collection[$_core_cap] = $_core_cap; $collection[$_post_type_cap] = $_post_type_cap; } } // unset($_core_cap, $_post_type_cap); } // unset($_post_type, $_post_type_object); // Housekeeping. foreach (get_taxonomies([], 'objects') as $_taxonomy => $_taxonomy_object) { foreach ($_taxonomy_object->cap ?? [] as $_core_cap => $_taxonomy_cap) { $collection[$_core_cap] = $_core_cap; $collection[$_taxonomy_cap] = $_taxonomy_cap; } // unset($_core_cap, $_taxonomy_cap); } // unset($_taxonomy, $_taxonomy_object); // Housekeeping. asort($collection, SORT_NATURAL); return $collection; }
/** * Updates a user's role if their current one doesn't match the attributes provided by the IdP * * @return string */ private function update_role() { $attrs = $this->saml->getAttributes(); if (array_key_exists($this->settings->get_attribute('groups'), $attrs)) { foreach (wp_roles()->roles as $role_name => $role_meta) { if (!isset($role) && in_array($this->settings->get_group($role_name), $attrs[$this->settings->get_attribute('groups')])) { $role = $role_name; } } if (isset($role)) { } elseif ($this->settings->get_allow_unlisted_users()) { $role = 'subscriber'; } else { $role = false; } } else { $role = false; } $user = get_user_by('login', $attrs[$this->settings->get_attribute('username')][0]); if ($user) { $user->set_role($role); } return $role; }
/** * Add new capability * * @return string * * @access public */ public function add() { $capability = trim(AAM_Core_Request::post('capability')); if ($capability) { //add the capability to administrator's role as default behavior wp_roles()->add_cap('administrator', $capability); $response = array('status' => 'success'); } else { $response = array('status' => 'failure'); } return json_encode($response); }
/** * Get role list * * @global WP_Roles $wp_roles * * @return \WP_Roles */ public static function getRoles() { global $wp_roles; if (function_exists('wp_roles')) { $roles = wp_roles(); } elseif (isset($wp_roles)) { $roles = $wp_roles; } else { $roles = $wp_roles = new WP_Roles(); } return $roles; }
/** * Returns an array of user roles for a given user object. * * @since 4.4.0 * @access protected * * @param WP_User $user_object The WP_User object. * @return array An array of user roles. */ protected function get_role_list($user_object) { $wp_roles = wp_roles(); $role_list = array(); foreach ($user_object->roles as $role) { if (isset($wp_roles->role_names[$role])) { $role_list[$role] = translate_user_role($wp_roles->role_names[$role]); } } if (empty($role_list)) { $role_list['none'] = _x('None', 'no user roles'); } /** * Filter the returned array of roles for a user. * * @since 4.4.0 * * @param array $role_list An array of user roles. * @param WP_User $user_object A WP_User object. */ return apply_filters('get_role_list', $role_list, $user_object); }
/** * Remove capability from role. * * This is a container for {@link WP_Roles::remove_cap()} to remove the * capability from the role. That is to say, that {@link * WP_Roles::remove_cap()} implements the functionality, but it also makes * sense to use this class, because you don't need to enter the role name. * * @since 2.0.0 * @access public * * @param string $cap Capability name. */ public function remove_cap($cap) { unset($this->capabilities[$cap]); wp_roles()->remove_cap($this->name, $cap); }
$cert = file_get_contents($_FILES['certificate']['tmp_name']); $key = file_get_contents($_FILES['privatekey']['tmp_name']); if (openssl_x509_check_private_key($cert, $key)) { //keys pass openssl key pair check, //store keys in database $this->settings->set_public_key($cert); $this->settings->set_private_key($key); //write the private key on save for simple saml parsing $key_uploaded = file_put_contents($upload_dir . '/' . get_current_blog_id() . '.key', $key) ? true : false; } else { echo '<div class="error below-h2"><p>The certificate and private key you provided do not correspond to one another. They were not uploaded.</p></div>' . "\n"; } } // Update settings $this->settings->enable_cache(); $this->settings->set_attribute('username', $_POST['username_attribute']); $this->settings->set_attribute('firstname', $_POST['firstname_attribute']); $this->settings->set_attribute('lastname', $_POST['lastname_attribute']); $this->settings->set_attribute('email', $_POST['email_attribute']); $this->settings->set_attribute('groups', $_POST['groups_attribute']); foreach (wp_roles()->roles as $role_name => $role_meta) { $this->settings->set_group($role_name, $_POST[sprintf('%s_group', $role_name)]); } $this->settings->set_idp($_POST['idp']); $this->settings->set_nameidpolicy($_POST['nameidpolicy']); $this->settings->set_allow_unlisted_users($_POST['allow_unlisted_users'] == 'allow' ? true : false); $this->settings->disable_cache(); } $status = $this->get_saml_status(); include constant('SAMLAUTH_ROOT') . '/lib/views/nav_tabs.php'; include constant('SAMLAUTH_ROOT') . '/lib/views/sso_sp.php';
/** * @author Jan Pokorný * @param KT_Form_Fieldset $fieldset * @param array $roles Pole user rolí u kterých se má metabox zobrazit. Defaultně všechny role. */ public function __construct(KT_Form_Fieldset $fieldset, $roles = null) { $this->roles = $roles ?: array_keys(wp_roles()->roles); $this->fieldset = $fieldset; }
/** * Setup the user capabilities based on their roles * * This method is mostly mased on WordPress' WP_User::get_role_caps() * * @since 3.3 * @return void */ protected function setup_caps() { $wp_roles = wp_roles(); // Build $allcaps from role caps, overlay user's $caps $this->caps = array(); foreach ((array) $this->roles as $role) { $the_role = $wp_roles->get_role($role); $this->caps = array_merge((array) $this->caps, (array) $the_role->capabilities); } }
public static function all_valid_wp_capabilities() { $all_roles = wp_roles(); $all_capabilities = array(); foreach ($all_roles->roles as $key => $value) { $all_capabilities[] = array_keys($value['capabilities'], true, true); } $all_capabilities_flattened = array(); foreach ($all_capabilities as $key => $value) { foreach ($value as $key_a => $value_a) { $all_capabilities_flattened[] = $value_a; } } $all_capabilities = array_unique($all_capabilities_flattened); sort($all_capabilities); return $all_capabilities; }
/** * Sends a notification to Slack * when a user's role has changed. * * Fires after the user's role has changed. * * @access public * @since 1.1.0 * @param int - $user_id - the User ID. * @param string - $role - the new role. * @param array - $old_roles - an array of the user's previous roles. * @return bool - returns false if nothing happened */ public function user_role_notification($user_id, $role, $old_roles) { // Which event are we processing? $notification_event = 'set_user_role'; // Get the outgoing webhooks. $outgoing_webhooks = $this->get_outgoing_webhooks($notification_event); // If we have no webhooks, then there's no point. if (!$outgoing_webhooks) { return false; } // Get current user. $current_user = wp_get_current_user(); // Get site URL and name. $site_url = get_bloginfo('url'); $site_name = get_bloginfo('name'); // Get changed user data. $changed_user_data = get_userdata($user_id); $changed_user_display_name = get_the_author_meta('display_name', $user_id); // Get role info. $all_roles = wp_roles()->roles; // Create general message for the notification. $general_message = sprintf(__('%1$s changed the user role for %2$s on the %3$s website at <%4$s>.', 'rock-the-slackbot'), $current_user->display_name, $changed_user_display_name, $site_name, $site_url); // Start creating the payload. $payload = array('text' => $general_message); // Build array of current user roles. $current_user_roles = array(); // Add current user roles. if (!empty($changed_user_data->roles)) { foreach ($changed_user_data->roles as $role) { if (array_key_exists($role, $all_roles)) { $current_user_roles[] = $all_roles[$role]['name']; } else { $current_user_roles[] = $role; } } // Add to fields. $fields[] = array('title' => __('Current User Role(s)', 'rock-the-slackbot'), 'value' => implode(', ', $current_user_roles), 'short' => true); } // Build array of old user roles. $old_user_roles = array(); // Add old user roles. if (!empty($old_roles)) { foreach ($old_roles as $role) { if (array_key_exists($role, $all_roles)) { $old_user_roles[] = $all_roles[$role]['name']; } else { $old_user_roles[] = $role; } } // Add to fields. $fields[] = array('title' => __('Old User Role(s)', 'rock-the-slackbot'), 'value' => implode(', ', $old_user_roles), 'short' => true); } // Add user login. $fields[] = array('title' => __('User Login', 'rock-the-slackbot'), 'value' => get_the_author_meta('user_login', $user_id), 'short' => true); // Add user email. $fields[] = array('title' => __('User Email', 'rock-the-slackbot'), 'value' => get_the_author_meta('user_email', $user_id), 'short' => true); // Create attachment. $attachments = array(array('fallback' => $general_message, 'text' => wp_trim_words(strip_tags(get_the_author_meta('description', $user_id)), 30, '...'), 'author_name' => $changed_user_display_name, 'author_link' => get_author_posts_url($user_id), 'author_icon' => get_avatar_url($user_id, 32), 'fields' => $fields)); // Send each webhook. $this->send_outgoing_webhooks($notification_event, $outgoing_webhooks, $payload, $attachments, array('user' => $changed_user_data, 'current_user_roles' => $current_user_roles, 'old_user_roles' => $old_user_roles)); }
/** * Fetch a filtered list of user roles that the current user is * allowed to edit. * * Simple function who's main purpose is to allow filtering of the * list of roles in the $wp_roles object so that plugins can remove * inappropriate ones depending on the situation or user making edits. * Specifically because without filtering anyone with the edit_users * capability can edit others to be administrators, even if they are * only editors or authors. This filter allows admins to delegate * user management. * * @since 2.8.0 * * @return array */ function get_editable_roles() { $all_roles = wp_roles()->roles; /** * Filter the list of editable roles. * * @since 2.8.0 * * @param array $all_roles List of roles. */ $editable_roles = apply_filters('editable_roles', $all_roles); return $editable_roles; }
protected static function get_email_addresses( $contacts ) { $addresses = array(); foreach ( $contacts as $contact ) { if ( (string) $contact === (string) intval( $contact ) ) { $users = array( get_userdata( $contact ) ); } else { list( $prefix, $role ) = explode( ':', $contact, 2 ); if ( empty( $role ) ) { continue; } $users = get_users( array( 'role' => $role ) ); } foreach ( $users as $user ) { if ( is_object( $user ) && ! empty( $user->user_email ) ) { $addresses[] = $user->user_email; } } } $addresses = array_unique( $addresses ); if ( ! empty( $addresses ) ) { return $addresses; } if ( is_callable( 'wp_roles' ) ) { $roles = wp_roles(); } else { $roles = new WP_Roles(); } foreach ( $roles->roles as $role => $details ) { if ( isset( $details['capabilities']['manage_options'] ) && ( true === $details['capabilities']['manage_options'] ) ) { $users = get_users( array( 'role' => $role ) ); foreach ( $users as $user ) { if ( ! empty( $user->user_email ) ) { $addresses[] = $user->user_email; } } } } return $addresses; }
/** * Remove role, if it exists. * * @since 2.0.0 * * @param string $role Role name. */ function remove_role($role) { wp_roles()->remove_role($role); }
/** * All roles. * * @since 160524 Role utils. * * @param array $args Behavioral args. * * @return array[] Array of roles. */ public function all(array $args = []) : array { // Establish args. $default_args = ['max' => PHP_INT_MAX, 'fail_on_max' => false, 'include' => [], 'exclude' => [], 'no_cache' => false]; $args = array_merge($default_args, $args); $args = array_intersect_key($args, $default_args); // Unique. $args['max'] = max(1, (int) $args['max']); $args['fail_on_max'] = (bool) $args['fail_on_max']; // Also used by {@link total()}. $args['include'] = (array) $args['include']; $args['exclude'] = (array) $args['exclude']; $args['no_cache'] = (bool) $args['no_cache']; // Check cache; already did this query? $cache_keys = $args; // Keys to consider when checking the cache. unset($cache_keys['no_cache']); // Cache key exclusions. if (($roles =& $this->cacheKey(__FUNCTION__, $cache_keys)) !== null && !$args['no_cache']) { return $roles; // Already cached this. } // Automatically fail if there are too many; when/if desirable. if ($args['fail_on_max'] && $this->total($args) > $args['max']) { return $roles = []; // Fail; too many. } // Return the array of all roles now. $roles = wp_roles()->roles; // All possible roles. $roles = $args['include'] ? array_intersect_key($roles, array_fill_keys($args['include'], true)) : $roles; $roles = $args['exclude'] ? array_diff_key($roles, array_fill_keys($args['exclude'], true)) : $roles; return $roles; }
/** * Get the user IDs of all users with no role on this site. * * This function returns an empty array when used on Multisite. * * @since 4.4.0 * * @return array Array of user IDs. */ function wp_get_users_with_no_role() { global $wpdb; if (is_multisite()) { return array(); } $prefix = $wpdb->get_blog_prefix(); $regex = implode('|', wp_roles()->get_names()); $regex = preg_replace('/[^a-zA-Z_\\|-]/', '', $regex); $users = $wpdb->get_col($wpdb->prepare("\n\t\tSELECT user_id\n\t\tFROM {$wpdb->usermeta}\n\t\tWHERE meta_key = '{$prefix}capabilities'\n\t\tAND meta_value NOT REGEXP %s\n\t", $regex)); return $users; }
/** * Handle User Role shortcodes. * * @param string $message String that needs shortcode processing. * @param array $old_role Old User Role. * @param array $new_role New User Role. * * @return string Processed string. */ public function handle_user_role_shortcodes($message, $old_role, $new_role) { $roles = wp_roles(); $old_role_name = ''; $new_role_name = ''; if (isset($roles->role_names[$old_role])) { $old_role_name = $roles->role_names[$old_role]; } if (isset($roles->role_names[$new_role])) { $new_role_name = $roles->role_names[$new_role]; } $message = str_replace('[user_role_old]', $old_role_name, $message); $message = str_replace('[user_role_new]', $new_role_name, $message); return $message; }