094cd5c1 by Chris Boden

Initial UserSearch and User classes...needs refactoring and DI still

1 parent 81dd287b
......@@ -21,15 +21,15 @@ use Tz\WordPress\CBV\CEHours;
use Tz\WordPress\CBV\Invoice;
use Tz\WordPress\CBV\Courses;
use Tz\WordPress\CBV\CBVOptions;
use Exception, StdClass;
use Exception, StdClass, ArrayAccess, Iterator, Countable;
const OPTION_NAME = "user_options";
const CAPABILITY = "manage_cbv_users";
CBV\load('Invoice');
CBV\load('User');
Tools\import('HTML');
CBV\load('Invoice');
CBV\load('User');
Tools\import('HTML');
call_user_func(function() {
......@@ -92,81 +92,21 @@ function create_instant_invoice($id = 0) {
}
function get_users($role = null, $pagenum=1, $records_per_page=0, $return_count_only = false, $search = null) {
global $wpdb;
$users = array();
if ($search) {
$search = strip_tags($search);
$search_text = "AND (uml.meta_value LIKE '%$search%' OR umf.meta_value LIKE '%$search%' OR u.user_email LIKE '%$search%' OR u.user_login LIKE '%$search%')";
} else {
$search_text = "";
}
$blog_prefix = $wpdb->get_blog_prefix();
if ($role) {
$extra_table = "";//", {$wpdb->usermeta} as umc";
//$filter = "AND (umc.user_id=u.ID AND umc.meta_key='wp_capabilites' AND umc.meta_value LIKE '%$role%')";
$filter = "AND u.ID IN (SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key='wp_capabilities' AND meta_value LIKE '%" . $wpdb->escape($role) . "%')";
} else {
$extra_table = "";
$filter = "";
}
if ($return_count_only) {
$query = "
SELECT
COUNT(*)
FROM
{$wpdb->users} as u, {$wpdb->usermeta} as uml, {$wpdb->usermeta} as umf, {$wpdb->usermeta} as ums $extra_table
WHERE
(uml.user_id=u.ID AND uml.meta_key='last_name')
AND (umf.user_id=u.ID AND umf.meta_key='first_name')
AND (ums.user_id=u.ID AND ums.meta_key='status')
$filter
$search_text";
return $count = $wpdb->get_var($query);
}
$query = "
SELECT
u.ID, u.user_login, user_email, uml.meta_value as last_name, umf.meta_value as first_name
FROM
{$wpdb->users} as u, {$wpdb->usermeta} as uml, {$wpdb->usermeta} as umf, {$wpdb->usermeta} as ums $extra_table
WHERE
(uml.user_id=u.ID AND uml.meta_key='last_name')
AND (umf.user_id=u.ID AND umf.meta_key='first_name')
AND (ums.user_id=u.ID AND ums.meta_key='status')
$filter
$search_text
ORDER BY last_name ASC, first_name ASC
";
/*
$query = "
SELECT u.ID, u.user_login, CONCAT('{', GROUP_CONCAT(CONCAT('"', m.meta_key, '"', ':', '"', m.meta_value, '"')), '}') AS meta_data, (SELECT meta_value FROM wp_usermeta as mt where meta_key = 'last_name' and mt.user_id = u.ID) AS ln
FROM wp_users as u left join wp_usermeta as m on u.ID = m.user_id where m.meta_key IN ('first_name', 'last_name')
GROUP BY u.ID
ORDER BY ln;
");
*/
if ($records_per_page > 0) {
$limit = " LIMIT ".( ($pagenum - 1) * $records_per_page ).", $records_per_page";
} else {
$limit = "";
}
$wp_user_search = $wpdb->get_results($query . $limit);
foreach ($wp_user_search as $user ) {
$user = new User\Account((int)$user->ID);
$users[] = Array('uid' => $user->ID, 'first_name' => $user->first_name, 'last_name' => $user->last_name, 'role' => $user->getRole(), 'user_login' => $user->user_login, 'email' => $user->user_email, 'status' => $user->status, 'member_id' => $user->member_id);
}
return $users;
$fs = Array();
if (!is_null($role)) {
$len = strlen($role);
$fs = Array('wp_capabilities' => "a:1:{s:{$len}:\\\\\\\\\"{$role}\\\\\\\\\"");
}
return new Tools\UserSearch(
Array('member_id', 'first_name', 'last_name', 'home_email', 'work_email', 'email_address_preference', 'status', 'wp_capabilities')
, $records_per_page
, $pagenum
, 'last_name'
, 'ASC'
, $fs
, $search
);
}
function create_user() {
......
......@@ -12,27 +12,28 @@ use Tz\WordPress\Tools\Notifications;
use Exception, StdClass;
use WP_User;
ini_set('display_errors', 1);
$records_per_page = 20;
$filter_role = isset($_GET['role']) ? $_GET['role'] : null;
$pagenum = isset($_GET['pagenum']) ? $_GET['pagenum'] : 1;
$search = isset($_GET['search_criteria']) ? $_GET['search_criteria'] : null;
ini_set('display_errors', 1);
$rows = get_users($filter_role, 0, 0, true, $search);
$records_per_page = 20;
$last = ceil($rows/$records_per_page);
if ($last < 1) {
$last = 1;
}
$filter_role = isset($_GET['role']) ? $_GET['role'] : null;
$pagenum = isset($_GET['pagenum']) ? $_GET['pagenum'] : 1;
$search = isset($_GET['search_criteria']) ? $_GET['search_criteria'] : null;
if ($pagenum < 1) {
$pagenum = 1;
} elseif ($pagenum > $last) {
$pagenum = $last;
}
$site_users = get_users($filter_role, $pagenum, $records_per_page, false, $search);
$rows = $site_users->countTotal();
$site_users = get_users($filter_role, $pagenum, $records_per_page, false, $search);
$last = ceil($rows/$records_per_page);
if ($last < 1) {
$last = 1;
}
if ($pagenum < 1) {
$pagenum = 1;
} elseif ($pagenum > $last) {
$pagenum = $last;
}
if ($filter_role) {
$url = $_SERVER['PHP_SELF']."?page=cbv_users&role=$filter_role&pagenum=";
......@@ -171,9 +172,8 @@ if ($last > 1) {
<table cellspacing="0" class="widefat post fixed">
<thead>
<tr>
<th scope="col" class="manage-column">ID</th>
<th scope="col" class="manage-column">Name</th>
<th scope="col" width="180" class="manage-column">Username</th>
<th scope="col" width="180" class="manage-column">Member ID</th>
<th scope="col" width="250" class="manage-column">Email</th>
<th scope="col" width="200" class="manage-column">Role</th>
<th scope="col" width="100" class="manage-column">Status</th>
......@@ -184,18 +184,20 @@ if ($last > 1) {
</thead>
<tbody>
<?php
foreach($site_users as $user):
foreach ($site_users as $user):
$pref = strtolower($user['email_address_preference']);
if (!in_array($pref, Array('home', 'work'))) {
$pref = (empty($data['home_email']) ? 'work' : 'home');
}
?>
<tr>
<td><?php echo $user['member_id']?></td>
<td><a href="/wp-admin/admin.php?page=cbv_users&action=edit&uid=<?php echo $user['uid']?>"><?php echo $user['last_name'].', '.$user['first_name']?></a></td>
<td><a href="/wp-admin/admin.php?page=cbv_users&action=edit&uid=<?php echo $user['uid']?>"><?php echo $user['user_login']?></a></td>
<td><?php echo $user['email']?></td>
<td><?php echo $user['role']?></td>
<td><a href="/wp-admin/admin.php?page=cbv_users&action=edit&uid=<?php echo $user['user_id']?>"><?php echo $user['last_name'].', '.$user['first_name']?></a></td>
<td><a href="/wp-admin/admin.php?page=cbv_users&action=edit&uid=<?php echo $user['user_id']?>"><?php echo $user['member_id']?></a></td>
<td><?php echo $user[$pref . '_email']?></td>
<td><?php echo current(array_keys($user['wp_capabilities'])); ?></td>
<td><?php echo ucwords($user['status']);?></td>
<td><a href="/wp-admin/admin-ajax.php?ajax=yes&action=build_user_remove&uid=<?php echo $user['uid'];?>" class="remove-user" rel="<?php echo $user['uid'];?>">Remove User</a></td>
<td><a href="/wp-admin/admin-ajax.php?ajax=yes&action=build_user_remove&uid=<?php echo $user['user_id'];?>" class="remove-user" rel="<?php echo $user['user_id'];?>">Remove User</a></td>
</tr>
<?php endforeach; ?>
......@@ -211,4 +213,4 @@ if ($last > 1) {
<div style="clear:both;"></div>
</div>
<script src="<?php echo Tools\url('../UserManager.js', __FILE__);?>" type="text/javascript"></script>
<script src="<?php echo Tools\url('../UserManager.js', __FILE__);?>" type="text/javascript"></script>
\ No newline at end of file
......
<?php
namespace Tz\WordPress\Tools;
use WP_User;
class User {
public $ID = 0;
public $id = 0;
protected $_wpuser;
public $_metacache = Array(); // should be protected, need to figure out how invisible byte works with serialize and not using base64 encode
public function __construct($id, $name = '', $blog_id = '') {
$this->_wpuser = new WP_User($id, $name, $blog_id);
$this->id = $this->ID = $this->_wpuser->id;
}
public function __get($key) {
if (isset($this->_wpuser->{$key})) {
return $this->_wpuser->{$key};
}
return $this->getMeta($key, true);
}
public function __set($key, $val) {
$this->setMeta($key, $val);
}
public function __sleep() {
return Array('_metacache', 'id', 'ID');
}
public function __wakeup() {
$this->_wpuser = new WP_User(0);
}
public function __call($method, $params) {
if (method_exists($this->_wpuser, $method)) {
$this->setUser();
return call_user_func_array(Array($this->_wpuser, $method), $params);
}
$classname = get_class($this->_wpuser);
trigger_error("Call to undefined method {$class}::{$method}() in " . __FILE__ . " on line " . __LINE__, E_USER_ERROR);
}
protected function setUser() {
if ($this->id != $this->_wpuser->id) {
$this->_wpuser = new WP_User($this->id);
}
}
public function getMeta($key, $single = true) {
if (isset($this->_metacache[$key])) {
return $this->_metacache[$key];
}
return get_user_meta($this->ID, $key, $single);
}
public function setMeta($key, $val) {
update_user_meta($this->ID, $key, $val);
unset($this->_metacache[$key]);
}
}
\ No newline at end of file
<?php
namespace Tz\WordPress\Tools;
use ArrayAccess, Iterator, Countable;
/*
Get all active CBV users who are subscribers
$users = new UserSearch(
Array('first_name', 'last_name')
, -1
, 1
, 'last_name'
, 'ASC'
, Array('status' => 'active')
, null
, Array(16)
);
foreach ($users as $i => $data) {
echo "{$data['first_name']} {$data['last_name']}";
}
*/
class UserSearch implements ArrayAccess, Iterator, Countable {
protected $result;
protected $pos = 0;
protected $count = 0;
protected $num_rows = 0;
protected $fields = Array();
public function __construct(Array $fields, $num_results = -1, $page = 1, $sortby = null, $sortorder = 'ASC', Array $field_match = null, $text_search = null, Array $in_groups = null) {
global $wpdb;
$this->fields = $fields;
$search_clause = $limit_clause = $order_clause = $order_sort = $having_clause = $uam_join = $uam_clause = '';
// Field matches
$having = " HAVING `json` LIKE ";
if (is_array($field_match) && count($field_match) > 0) {
foreach ($field_match as $key => $val) {
if (!in_array($key, $this->fields)) {
$this->fields[] = $key;
}
$having_clause .= (empty($having_clause) ? $having : "\n AND `json` LIKE ");
$having_clause .= " '%\"{$key}\":\"{$val}%' ";
}
}
// Open ended search
if (!is_null($text_search)) {
$search_strings = explode(' ', $text_search);
foreach ($search_strings as $search) {
$having_clause .= (empty($having_clause) ? $having : "\n AND `json` LIKE ");
$having_clause .= " '%{$search}%' ";
}
}
// Order
if (!is_null($sortby)) {
$order_clause = " , GROUP_CONCAT(IF(`meta_key` = '{$sortby}', `meta_value`, '') SEPARATOR '') AS `fake_order` ";
$order_sort = " ORDER BY `fake_order` " . ($sortorder == 'DESC' ? 'DESC' : 'ASC');
}
// Pagination
if ($num_results > 0) {
$limit_clause = " LIMIT " . (($page - 1) * $num_results ) . ", {$num_results}";
}
// Groups
if (is_array($in_groups) && count($in_groups) > 0 && is_plugin_active('tz-user-access-manager/user-access-manager.php')) {
$uam_join = " LEFT JOIN `wp_uam_accessgroup_to_object` AS `uam` ON `wp_usermeta`.`user_id` = `uam`.`object_id` ";
$uam_clause = " AND `uam`.`object_type` = 'user' AND `uam`.`group_id` IN (" . implode(',', $in_groups) . ") ";
}
$query = "
SELECT SQL_CALC_FOUND_ROWS
`user_id`
, CONCAT(
'{'
, GROUP_CONCAT(
'\"'
, `meta_key`
, '\":\"'
, REPLACE(REPLACE(REPLACE(`meta_value`, '" . '"' . "', '" . '\\\"' . "'), '\\r', '\\\\r'), '\\n', '\\\\n')
, '\"'
)
, '}'
) AS `json`
{$order_clause}
FROM `wp_usermeta`
{$uam_join}
WHERE
`meta_key` IN ('" . implode("','", $this->fields) . "')
{$uam_clause}
GROUP BY `user_id`
{$having_clause}
{$order_sort}
{$limit_clause}
";
/*
?>
<textarea style="width: 95%; height: 35em; font-size: 11px;" autofocus="autofocus">
<?php
$me = new User(1);
echo serialize($me) . "\n";
echo serialize(Array('hello' => 'world'));
?>
<?php echo serialize(new User(1)); ?>
<?php echo serialize(new User(4)); ?>
<?php echo trim($query); ?>;
</textarea>
<?php
/**/
$this->result = mysql_query($query, $wpdb->dbh);
$this->num_rows = mysql_num_rows($this->result);
$count_result = mysql_query("SELECT FOUND_ROWS()", $wpdb->dbh);
list($this->count) = mysql_fetch_row($count_result);
}
public function countTotal() {
return $this->count;
}
public function count() {
return $this->num_rows;
}
public function current() {
return $this->offsetGet($this->pos);
}
public function key() {
return $this->pos;
}
public function next() {
$this->pos++;
}
public function rewind() {
$this->current = 0;
if ($this->num_rows > 0) {
mysql_data_seek($this->result, 0);
}
}
public function valid() {
return $this->offsetExists($this->pos);
}
public function offsetExists($offset) {
if ($this->num_rows == 0) {
return false;
}
return ($offset < 0 || $offset > ($this->num_rows - 1) ? false : true);
}
public function offsetGet($offset) {
if (!$this->offsetExists($offset)) {
return false;
}
if ($offset != $this->pos) {
mysql_data_seek($this->result, $offset);
}
list($user_id, $user_string) = mysql_fetch_row($this->result);
$data = array_merge(array_map(function() { return ''; }, array_flip($this->fields)), json_decode($user_string, true));
foreach ($data as $key => &$val) {
$val = maybe_unserialize($val);
}
// $sobj = unserialize(sprintf('O:23:"Tz\WordPress\Tools\User":3:{s:10:"_metacache";%3$ss:2:"id";s:%2$d:"%1$d";s:2:"ID";s:%2$d:"%1$d";}', $user_id, strlen($user_id), serialize($data)));
return $data;
}
public function offsetSet($offset, $value) {
throw new Exception("You're...you're crazy man. I like you, but you're crazy.");
}
public function offsetUnset($offset) {
throw new Exception("You're...you're crazy man. I like you, but you're crazy.");
}
}
\ No newline at end of file