[wp-hackers] User Capabilities

Owen Winkler ringmaster at midnightcircus.com
Sun Jul 10 07:06:18 GMT 2005


Ryan Boren wrote:

>I'm not sure about having roles reference other roles.  If a privilege
>is removed for one role, the privilege is lost to higher roles as well.
>If manage_links is removed for the Managing Editor, the Publisher loses
>that priv as well unless it is separately added to the Publisher role.
>I think each role should be self contained.
>  
>
Hmm.  Ok.  So then does "Publisher" need not only level_10, level_9, and 
level_8, but also level_1 through level_7?

>Perhaps WP_User should have separate arrays for individual capabilities
>and roles.  Your merge code could be used to create a third array that
>would contain the full operating set of capabilities.  This array would
>be checked by has_cap() but would be not be persisted.  Any time the
>role or capability arrays change the merge would be rerun.
>  
>
Ok, except the merge code I wrote is a bit complicated if we're not 
doing recursion.  My new code is more simple.

>Adding some dedicated role management methods to WP_User might be handy.
>add_role(), remove_role(), and maybe a set_role() shortcut used by the
>default UI for changing a user's role (assuming they only have one).
>remove_role() could enforce a "you can't delete the last role" rule.
>  
>
I think those are great ideas - abstracting these functions to avoid 
messing with the database is wise.

I would also add is_role() to WP_Roles, which is just an alias for a 
single line of code, but makes the code read a lot easier.  I used it.

While trying to debug this, I noticed that my usermeta data kept being 
returned serialized, even though I added code to unserialize it.  It 
turns out that usermeta data is also loaded into $cache_userdata, which 
is updated by update_user_cache().  Now update_user_cache() isn't 
pluggable (oops!), but it is called in wp-settings.php in order to 
detect if the database is installed, presumably without wasting the 
query hit on something throwaway.  So...

My solution: I moved update_user_cache() to pluggable_functions.php.  I 
changed the wp-settings.php check to use update_category_cache() 
instead, and then updated update_category_cache() to return true on 
successful data retrieval.  I also updated update_user_cache() so that 
it unserializes, and I think that solves the matter.

Changes attached:
* Replaced role recursion with flat role cap merge.
* WP_User now has ->roles and ->allcaps.
* Added WP_Roles::is_role() for checking if a string is a valid role name.
* Added WP_User:: add_role(), remove_role(), and set_role() as per above.
* Changed WP_User::remove_cap() so that you can't remove roles with it.
* Changed add_cap() so that you can deny caps with it.
* has_cap() returns true/false based on cap true/false state - user caps 
override role caps.
* Made update_user_cache() pluggable.
* wp-settings.php now checks for db data using update_category_cache() 
instead of update_user_cache().

Has anyone else tried the patch?  If your plugin depends on user levels, 
it might be a good idea to check out these changes before they get 
committed.

What changes will there be to the user admin UI?  How extensive will it 
get?  I imagine that the only thing that *has* to be done is to use a 
dropdown of roles in place of the numeric level gadget.  Oh, how sweet 
that will be, finally!  (Sorted alphabetically?  No numbers anymore...)

Owen

-------------- next part --------------
A non-text attachment was scrubbed...
Name: capabilities.php
Type: text/x-patch
Size: 6173 bytes
Desc: not available
Url : http://comox.textdrive.com/pipermail/wp-hackers/attachments/20050710/d946af03/capabilities-0001.bin
-------------- next part --------------
Index: functions.php
===================================================================
--- functions.php	(revision 2702)
+++ functions.php	(working copy)
@@ -1218,32 +1218,11 @@
 
 function update_category_cache() {
 	global $cache_categories, $wpdb;
-	$dogs = $wpdb->get_results("SELECT * FROM $wpdb->categories");
-	foreach ($dogs as $catt)
-		$cache_categories[$catt->cat_ID] = $catt;
-}
-
-function update_user_cache() {
-	global $cache_userdata, $wpdb;
-	$level_key = $wpdb->prefix . 'user_level';
-	$user_ids = $wpdb->get_col("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$level_key'");
-	$user_ids = join(',', $user_ids);
-	$query = apply_filters('user_cache_query', "SELECT * FROM $wpdb->users WHERE ID IN ($user_ids)");
-	if ( $users = $wpdb->get_results( $query ) ) :
-		foreach ($users as $user) :
-			$metavalues = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user->ID'");
-			foreach ( $metavalues as $meta ) {
-				$user->{$meta->meta_key} = $meta->meta_value;
-				// We need to set user_level from meta, not row
-				if ( $wpdb->prefix . 'user_level' == $meta->meta_key )
-					$user->user_level = $meta->meta_value;
-			}
-
-			$cache_userdata[$user->ID] = $user;
-			$cache_userdata[$user->user_login] =& $cache_userdata[$user->ID];
-		endforeach;
+	if($dogs = $wpdb->get_results("SELECT * FROM $wpdb->categories")):
+		foreach ($dogs as $catt)
+			$cache_categories[$catt->cat_ID] = $catt;
 		return true;
-	else : 
+	else:
 		return false;
 	endif;
 }
@@ -1959,11 +1938,38 @@
 	@ header('Pragma: no-cache');
 }
 
+function get_usermeta( $user_id, $meta_key = '') {
+	global $wpdb;
+	$user_id = (int) $user_id;
+
+	if ( !empty($meta_key) ) {
+	$meta_key = preg_replace('|a-z0-9_|i', '', $meta_key);
+		$metas = $wpdb->get_results("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
+	} else {
+		$metas = $wpdb->get_results("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id'");
+	}
+
+	foreach ($metas as $index => $meta) {
+		@ $value = unserialize($meta->meta_key);
+		if ($value !== FALSE)
+			$metas[$index]->meta_key = $value;			
+	}
+
+	if ( !empty($meta_key) )
+		return $metas[0];
+	else
+		return $metas;
+}
+
 function update_usermeta( $user_id, $meta_key, $meta_value ) {
 	global $wpdb;
 	if ( !is_numeric( $user_id ) )
 		return false;
 	$meta_key = preg_replace('|a-z0-9_|i', '', $meta_key);
+
+	if ( is_array($meta_value) || is_object($meta_value) )
+		$meta_value = serialize($meta_value);
+
 	$cur = $wpdb->get_row("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'");
 	if ( !$cur ) {
 		$wpdb->query("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value )
@@ -1991,4 +1997,4 @@
 	return preg_replace('/^.*wp-content[\\\\\/]plugins[\\\\\/]/', '', $file);
 }
 
-?>
\ No newline at end of file
+?>
Index: wp-includes/pluggable-functions.php
===================================================================
--- wp-includes/pluggable-functions.php	(revision 2702)
+++ wp-includes/pluggable-functions.php	(working copy)
@@ -19,7 +19,8 @@
 	$user_url    = $userdata->user_url;
 	$user_pass_md5 = md5($userdata->user_pass);
 	$user_identity = $userdata->display_name;
-	$current_user  = $userdata;
+	if ( empty($current_user) )
+		$current_user = new WP_User($user_ID);
 }
 endif;
 
@@ -29,7 +30,7 @@
 	$user_id = (int) $user_id;
 	if ( $user_id == 0 )
 		return false;
-
+		
 	if ( isset( $cache_userdata[$user_id] ) ) 
 		return $cache_userdata[$user_id];
 
@@ -39,20 +40,53 @@
 	$metavalues = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id'");
 
 	foreach ( $metavalues as $meta ) {
-		$user->{$meta->meta_key} = $meta->meta_value;
+		@ $value = unserialize($meta->meta_value);
+		if ($value === FALSE)
+			$value = $meta->meta_value;
+		$user->{$meta->meta_key} = $value;
+
 		// We need to set user_level from meta, not row
 		if ( $wpdb->prefix . 'user_level' == $meta->meta_key )
 			$user->user_level = $meta->meta_value;
 	}
 
 	$cache_userdata[$user_id] = $user;
-
 	$cache_userdata[$cache_userdata[$userid]->user_login] =& $cache_userdata[$user_id];
 
 	return $cache_userdata[$user_id];
 }
 endif;
 
+if ( !function_exists('update_user_cache') ) :
+function update_user_cache() {
+	global $cache_userdata, $wpdb;
+	$level_key = $wpdb->prefix . 'user_level';
+	$user_ids = $wpdb->get_col("SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '$level_key'");
+	$user_ids = join(',', $user_ids);
+	$query = apply_filters('user_cache_query', "SELECT * FROM $wpdb->users WHERE ID IN ($user_ids)");
+	if ( $users = $wpdb->get_results( $query ) ) :
+		foreach ($users as $user) :
+			$metavalues = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user->ID'");
+			foreach ( $metavalues as $meta ) {
+				@ $value = unserialize($meta->meta_value);
+				if ($value === FALSE)
+					$value = $meta->meta_value;
+				$user->{$meta->meta_key} = $value;
+				// We need to set user_level from meta, not row
+				if ( $wpdb->prefix . 'user_level' == $meta->meta_key )
+					$user->user_level = $meta->meta_value;
+			}
+
+			$cache_userdata[$user->ID] = $user;
+			$cache_userdata[$user->user_login] =& $cache_userdata[$user->ID];
+		endforeach;
+		return true;
+	else : 
+		return false;
+	endif;
+}
+endif;
+
 if ( !function_exists('get_userdatabylogin') ) :
 function get_userdatabylogin($user_login) {
 	global $cache_userdata, $wpdb;
Index: wp-settings.php
===================================================================
--- wp-settings.php	(revision 2702)
+++ wp-settings.php	(working copy)
@@ -74,7 +74,7 @@
 require_once (ABSPATH . WPINC . '/wp-l10n.php');
 
 $wpdb->hide_errors();
-if ( !update_user_cache() && (!strstr($_SERVER['PHP_SELF'], 'install.php') && !defined('WP_INSTALLING')) ) {
+if ( !update_category_cache() && (!strstr($_SERVER['PHP_SELF'], 'install.php') && !defined('WP_INSTALLING')) ) {
 	if ( strstr($_SERVER['PHP_SELF'], 'wp-admin') )
 		$link = 'install.php';
 	else
@@ -85,6 +85,7 @@
 
 require (ABSPATH . WPINC . '/functions-formatting.php');
 require (ABSPATH . WPINC . '/functions-post.php');
+require (ABSPATH . WPINC . '/capabilities.php');
 require (ABSPATH . WPINC . '/classes.php');
 require (ABSPATH . WPINC . '/template-functions-general.php');
 require (ABSPATH . WPINC . '/template-functions-links.php');
@@ -160,7 +161,8 @@
 $wp_query = new WP_Query();
 $wp_rewrite = new WP_Rewrite();
 $wp = new WP();
+$wp_roles = new WP_Roles();
 
 // Everything is loaded and initialized.
 do_action('init');
-?>
\ No newline at end of file
+?>
Index: wp-admin/post.php
===================================================================
--- wp-admin/post.php	(revision 2702)
+++ wp-admin/post.php	(working copy)
@@ -66,7 +66,7 @@
 
 	$post_ID = $p = (int) $_GET['post'];
 
-	if ( !user_can_edit_post($user_ID, $post_ID) )
+	if ( !current_user_can('edit_post', $post_ID) )
 		die ( __('You are not allowed to edit this post.') );
 
 	if ( !user_can_edit_post($user_ID, $post_ID) )
@@ -322,7 +322,7 @@
 <div class="updated"><p><?php printf(__('Post saved. <a href="%s">View site &raquo;</a>'), get_bloginfo('home')); ?></p></div>
 <?php endif; ?>
 <?php
-	if ( user_can_create_draft($user_ID) ) {
+	if (user_can_create_draft($user_ID)) {
 		$action = 'post';
 		get_currentuserinfo();
 		if ( $drafts = get_users_drafts( $user_ID ) ) {
@@ -332,13 +332,13 @@
 			<?php
 			for ( $i = 0; $i < 15; $i++ ) {
 				$draft = $drafts[$i];
-				if ( 0 != $i )
+				if (0 != $i)
 					echo ', ';
 				$draft->post_title = stripslashes($draft->post_title);
 				if ( empty($draft->post_title) )
 					$draft->post_title = sprintf(__('Post # %s'), $draft->ID);
 				echo "<a href='post.php?action=edit&amp;post=$draft->ID' title='" . __('Edit this draft') . "'>$draft->post_title</a>";
-			}
+				}
 			?>
 			<?php if ( 15 < count($drafts) ) { ?>
 			, <a href="edit.php"><?php echo sprintf(__('and %s more'), (count($drafts) - 15) ); ?> &raquo;</a>
Index: wp-admin/upgrade-functions.php
===================================================================
--- wp-admin/upgrade-functions.php	(revision 2702)
+++ wp-admin/upgrade-functions.php	(working copy)
@@ -226,8 +226,11 @@
 			update_usermeta( $user->ID, 'last_name', $wpdb->escape($user->user_lastname) );
 		if ( !empty( $user->user_nickname ) )
 			update_usermeta( $user->ID, 'nickname', $wpdb->escape($user->user_nickname) );
-		if ( !empty( $user->user_level ) )
+		if ( !empty( $user->user_level ) ) {
 			update_usermeta( $user->ID, $table_prefix . 'user_level', $user->user_level );
+			$role = translate_level_to_role($user->user_level);
+			update_usermeta( $user->ID, $table_prefix . 'capabilities', array($role => true) );
+		}
 		if ( !empty( $user->user_icq ) )
 			update_usermeta( $user->ID, 'icq', $wpdb->escape($user->user_icq) );
 		if ( !empty( $user->user_aim ) )
@@ -749,4 +752,27 @@
 	}
 	return $template;
 }
-?>
\ No newline at end of file
+
+function translate_level_to_role($level) {
+	switch ($level) {
+	case 10:
+	case 9:
+	case 8:
+		return 'publisher';
+	case 7:
+	case 6:
+	case 5:
+		return 'managing_editor';
+	case 4:
+	case 3:
+		return 'copy_editor';
+	case 2:
+		return 'staff_writer';
+	case 1:
+		return 'freelancer';
+	case 0:
+		return 'visitor';
+	}
+}
+
+?>
Index: wp-admin/upgrade-schema.php
===================================================================
--- wp-admin/upgrade-schema.php	(revision 2702)
+++ wp-admin/upgrade-schema.php	(working copy)
@@ -216,6 +216,8 @@
 	// 1.5.1
 	add_option('use_trackback', 0);
 
+	populate_roles();
+
 	// Delete unused options
 	$unusedoptions = array ('blodotgsping_url', 'bodyterminator', 'emailtestonly', 'phoneemail_separator', 'smilies_directory', 'subjectprefix', 'use_bbcode', 'use_blodotgsping', 'use_phoneemail', 'use_quicktags', 'use_weblogsping', 'weblogs_cache_file', 'use_preview', 'use_htmltrans', 'smilies_directory', 'fileupload_allowedusers', 'use_phoneemail', 'default_post_status', 'default_post_category', 'archive_mode', 'time_difference', 'links_minadminlevel', 'links_use_adminlevels', 'links_rating_type', 'links_rating_char', 'links_rating_ignore_zero', 'links_rating_single_image', 'links_rating_image0', 'links_rating_image1', 'links_rating_image2', 'links_rating_image3', 'links_rating_image4', 'links_rating_image5', 'links_rating_image6', 'links_rating_image7', 'links_rating_image8', 'links_rating_image9', 'weblogs_cacheminutes', 'comment_allowed_tags', 'search_engine_friendly_urls', 'default_geourl_lat', 'default_geourl_lon', 'use_default_geourl', 'weblogs_xml_url');
 	foreach ($unusedoptions as $option) :
@@ -229,4 +231,101 @@
 	endforeach;
 }
 
+function populate_roles() {
+	global $table_prefix;
+
+	$roles = array ('publisher' =>
+									array('name' => __('Publisher'),
+											'capabilities' => array(
+												'edit_posts' => true,
+												'edit_others_posts' => true,
+												'edit_published_posts' => true,
+												'publish_posts' => true,
+												'edit_pages' => true,
+												'manage_categories' => true,
+												'manage_links' => true,
+												'upload_images' => true,
+												'manage_options' => true,
+												'switch_themes' => true,
+												'edit_themes' => true,
+												'activate_plugins' => true,
+												'edit_plugins' => true,
+												'edit_users' => true,
+												'edit_files' => true,
+												'read' => true,
+												'level_10' => true,
+												'level_9' => true,
+												'level_8' => true
+												)),
+											
+									'managing_editor' =>
+									array('name' => __('Managing Editor'),
+											'capabilities' => array(
+												'edit_posts' => true,
+												'edit_others_posts' => true,
+												'edit_published_posts' => true,
+												'publish_posts' => true,
+												'edit_pages' => true,
+												'manage_categories' => true,
+												'manage_links' => true,
+												'upload_images' => true,
+												'read' => true,
+												'level_7' => true,
+												'level_6' => true,
+												'level_5' => true
+												)),
+											
+									'copy_editor' =>
+									array('name' => __('Copy Editor'),
+											'capabilities' => array(
+												'edit_posts' => true,
+												'edit_others_posts' => true,
+												'edit_published_posts' => true,
+												'publish_posts' => true,
+												'edit_pages' => true,
+												'upload_images' => true,
+												'read' => true,
+												'level_4' => true,
+												'level_3' => true
+												)),
+											
+									'staff_writer' =>
+									array('name' => __('Staff Writer'),
+											'capabilities' => array(
+												'edit_posts' => true,
+												'publish_posts' => true,
+												'upload_images' => true,
+												'read' => true,
+												'level_2' => true
+												)),
+											
+									'freelancer' =>
+									array('name' => __('Freelancer'),
+											'capabilities' => array(
+												'edit_posts' => true,
+												'read' => true,
+												'level_1' => true
+												)),
+											
+									'designer' =>
+									array('name' => __('Designer'),
+											'capabilities' => array(
+												'edit_themes' => true,
+												'read' => true
+												)),
+											
+									'subscriber' =>
+									array('name' => __('Subscriber'),
+											'capabilities' => array(
+												'read' => true,
+												'level_0' => true
+												)),
+											
+									'inactive' =>
+									array('name' => __('Inactive'),
+												'capabilities' => array())
+									);
+
+	add_option($table_prefix . 'user_roles', $roles);
+}
 ?>


More information about the wp-hackers mailing list