function fu_add_new_user($fu = false) { //echo "wtf?"; require_once '../../../wp-includes/registration.php'; global $blog_id; $email = sanitize_email($fu['email']); //$current_site = get_current_site(); $pass = $fu['password']; $user_id = email_exists($email); //echo "hi"; if (!$user_id) { $password = $pass ? $pass : generate_random_password(); $user_id = wpmu_create_user($fu['username'], $password, $email); if (false == $user_id) { //echo "uh oh"; wp_die(__('There was an error creating the user')); } else { //echo "sending mail"; wp_new_user_notification($user_id, $password); } if (get_user_option('primary_blog', $user_id) == $blog_id) { update_user_option($user_id, 'primary_blog', $blog_id, true); } } $redirect = $fu['referer'] ? $fu['referer'] : get_bloginfo('url'); wp_redirect($redirect); }
/** * @ticket 22917 */ function test_enable_live_network_user_counts_filter() { // false for large networks by default add_filter( 'enable_live_network_counts', '__return_false' ); // Refresh the cache wp_update_network_counts(); $start_count = get_user_count(); wpmu_create_user( 'user', 'pass', 'email' ); // No change, cache not refreshed $count = get_user_count(); $this->assertEquals( $start_count, $count ); wp_update_network_counts(); $start_count = get_user_count(); add_filter( 'enable_live_network_counts', '__return_true' ); wpmu_create_user( 'user2', 'pass2', 'email2' ); $count = get_user_count(); $this->assertEquals( $start_count + 1, $count ); remove_filter( 'enable_live_network_counts', '__return_false' ); remove_filter( 'enable_live_network_counts', '__return_true' ); }
/** * Creates a new blog calling wpmu_create_blog * the wpmu_create_blog parameters are: * $domain The domain of the new blog. * $path The path of the new blog. * $title The title of the new blog. * $user_id The user id of the user account who will be the blog admin. (you can use an email instead of the user_id. If so, a new user will be created) * $meta Other meta information. * $site_id The site_id of the blog to be created. * * @param array $args Array with username, password and wpmu_create_blog function parameters * @return mixed The new blog id or an error message */ function msxmlrpc_create_blog($args) { $parameters = check_arguments($args); if (!is_array($parameters)) { return $parameters; } // if the user_id is the user's e-mail if (!is_int($parameters['user_id'])) { if (!($user_id = get_user_id_from_string($parameters['user_id']))) { $error = wpmu_validate_user_signup($parameters['path'], $parameters['user_id']); if (is_wp_error($error)) { return new IXR_Error(500, $error->get_error_message()); } $user_id = wpmu_create_user($parameters['path'], wp_generate_password(), $parameters['user_id']); } $parameters['user_id'] = $user_id; } if (get_blog_id($parameters['domain'], $parameters['path']) !== false) { return new IXR_Error(500, __("Site already exists.")); } if (!isset($parameters['meta'])) { $parameters['meta'] = ""; } if (!isset($parameters['site_id'])) { $parameters['site_id'] = 1; } return wpmu_create_blog($parameters['domain'], $parameters['path'], $parameters['title'], $parameters['user_id'], $parameters['meta'], $parameters['site_id']); }
/** * Create / Add users */ function ns_wp_add_user($target_id, $useremail, $username, $userpass = '', $userrole = 'administrator', $logfile = false) { global $ns_cloner; ns_log_write("ENTER ns_wp_add_user - target_id:{$target_id}, useremail:{$useremail}, username:{$username}, userrole:{$userrole}", $logfile); $useremail = stripslashes($useremail); $username = stripslashes($username); $userpass = stripslashes($userpass); $user_by_email = get_user_by('email', $useremail); $user_by_username = get_user_by('username', $username); // check for existing user by email if (!empty($user_by_email)) { $user_id = $user_by_email->ID; ns_log_write("Found user with email '{$useremail}' (id={$user_id})", $logfile); } elseif (!empty($user_by_username)) { $user_id = $user_by_username->ID; ns_log_write("Found user with username '{$username}' (id={$user_id})", $logfile); } else { if (empty($userpass) || $userpass == strtolower('null')) { $userpass = wp_generate_password(); } $user_id = wpmu_create_user($username, $userpass, $useremail); if ($user_id != false) { ns_log_write("Created new user '{$username}' with email '{$useremail}'", $logfile); // send notification to new users if the option is set if (isset($ns_cloner->request['do_user_notify'])) { wpmu_welcome_notification($target_id, $user_id, $userpass, 'New Site with ID: ' . $target_id); ns_log_write("Sent welcome email to new user '{$username}' with email '{$useremail}'", $logfile); } } else { ns_log_write("Failed creating user '{$username}' with email '{$useremail}' - that username or email is probably already taken for a different user.", $logfile); } } // we now have a user id (or should) - give them privileges on this blog if (!empty($target_id) && !empty($user_id) && !empty($userrole)) { $result = add_user_to_blog($target_id, $user_id, $userrole); if ($result === true) { ns_log_write("Successfully added user with id {$user_id} to blog {$target_id}", $logfile); } else { $error_message = $result->get_error_message(); ns_log_write("Failed adding user to blog. WP error: {$error_message}", $logfile); } return $result; } else { $error_message = "Target id, user id, or user role were empty"; ns_log_write("Failed adding user to blog. {$error_message}", $logfile); return new WP_Error(false, $error_message); } }
/** * Add a blog to *_signups table. * * Copied from core because we need the activation key and * we need to avoid the blog activation email. This can/is done * via a hook, but the double AJAX call kills our AJAX registration * so its left out here. * * @param $domain * @param $path * @param $title * @param $user * @param $user_email * @param array $meta * * @return string $key Activation key */ public static function signup_blog($domain, $path, $title, $user, $user_email, $meta = array()) { global $wpdb; $key = substr(md5(time() . rand() . $domain), 0, 16); $meta = serialize($meta); $result = $wpdb->insert($wpdb->signups, array('domain' => $domain, 'path' => sanitize_text_field($path), 'title' => sanitize_text_field($title), 'user_login' => sanitize_text_field($user), 'user_email' => sanitize_email($user_email), 'registered' => current_time('mysql', true), 'activation_key' => $key, 'meta' => $meta)); $password = false; // Activate the user and attempt a login (because we want WP sessions) $user_id = username_exists($user); if (!$user_id) { $password = wp_generate_password(12, false); $user_id = wpmu_create_user($user, $password, $user_email); $creds = array('user_login' => $user, 'user_password' => $password, 'remember' => true); $user = wp_signon($creds); } $result = array('activation_key' => $key, 'user_pass' => $password); return $result; }
function test_with_another_site() { global $current_site, $base; $domain = 'blogoptiontest'; if (is_subdomain_install()) { $newdomain = $domain . '.' . preg_replace('|^www\\.|', '', $current_site->domain); $path = $base; } else { $newdomain = $current_site->domain; $path = $base . $domain . '/'; } $email = '*****@*****.**'; $password = wp_generate_password(12, false); $user_id = wpmu_create_user($domain, $password, $email); $this->assertInternalType('integer', $user_id); $blog_id = wpmu_create_blog($newdomain, $path, $title, $user_id, array('public' => 1), $current_site->id); $this->assertInternalType('integer', $blog_id); $key = rand_str(); $key2 = rand_str(); $value = rand_str(); $value2 = rand_str(); $this->assertFalse(get_blog_option($blog_id, 'doesnotexist')); //$this->assertFalse( get_option( 'doesnotexist' ) ); // check get_option() $this->assertTrue(add_blog_option($blog_id, $key, $value)); // Assert all values of $blog_id that means the current or main blog (the same here). $this->assertEquals($value, get_blog_option($blog_id, $key)); $this->assertEquals($value, get_blog_option("{$blog_id}", $key)); //$this->assertEquals( $value, get_option( $key ) ); // check get_option() $this->assertFalse(add_blog_option($blog_id, $key, $value)); // Already exists $this->assertFalse(update_blog_option($blog_id, $key, $value)); // Value is the same $this->assertTrue(update_blog_option($blog_id, $key, $value2)); $this->assertEquals($value2, get_blog_option($blog_id, $key)); //$this->assertEquals( $value2, get_option( $key ) ); // check get_option() $this->assertFalse(add_blog_option($blog_id, $key, $value)); $this->assertEquals($value2, get_blog_option($blog_id, $key)); //$this->assertEquals( $value2, get_option( $key ) ); // check get_option() $this->assertTrue(delete_blog_option($blog_id, $key)); $this->assertFalse(get_blog_option($blog_id, $key)); //$this->assertFalse( get_option( $key ) ); // check get_option() $this->assertFalse(delete_blog_option($blog_id, $key)); $this->assertTrue(update_blog_option($blog_id, $key2, $value2)); $this->assertEquals($value2, get_blog_option($blog_id, $key2)); //$this->assertEquals( $value2, get_option( $key2 ) ); // check get_option() $this->assertTrue(delete_blog_option($blog_id, $key2)); $this->assertFalse(get_blog_option($blog_id, $key2)); //$this->assertFalse( get_option( $key2 ) ); // check get_option() }
/** * Create / Add users */ function add_user($useremail, $username, $userpass = '', $userrole = 'administrator') { global $wpdb; $useremail = stripslashes($useremail); $username = stripslashes($username); $userpass = stripslashes($userpass); $is_new_user = 0; $user_id = ''; $user = get_user_by_email($useremail); if (!empty($user)) { // user exists $user_id = $user->ID; } else { // create user if ($userpass == '' || $userpass == strtolower('null')) { $userpass = wp_generate_password(); } $user_id = wpmu_create_user($username, $userpass, $useremail); $is_new_user = 1; } if (false == $user_id) { //die( '<p>' . __( 'There was an error creating a user', 'ns_cloner' ) . '</p> name: ' . $username . ' email: ' . $useremail . ' pass: '******'<font style="color:red;">' . "FAILED to create Username: <br>{$username}</b> with Email: <b>{$useremail}</b> - that username or email is probably already taken for a different user.</font><br />"; $is_new_user = 0; } else { // add the user add_user_to_blog($this->target_id, $user_id, $userrole); $this->status = $this->status . 'Added user: <b>' . $username . ' | ' . $useremail . '</b>'; if ($is_new_user) { $this->status = $this->status . " created with Password: {$userpass}"; $this->log('Added user: <b>' . $username . ' | ' . $useremail . " created with Password: {$userpass}"); } $this->status = $this->status . '<br />'; } }
wp_redirect(add_query_arg(array('updated' => 'true', 'action' => $userfunction), $_SERVER['HTTP_REFERER'])); } exit; break; case "adduser": check_admin_referer('add-user'); $user = $_POST['user']; if (empty($user['username']) && empty($user['email'])) { wp_die(__('Missing username and email.')); } elseif (empty($user['username'])) { wp_die(__('Missing username.')); } elseif (empty($user['email'])) { wp_die(__('Missing email.')); } $password = generate_random_password(); $user_id = wpmu_create_user(wp_specialchars(strtolower($user['username'])), $password, wp_specialchars($user['email'])); if (false == $user_id) { wp_die(__('Duplicated username or email address.')); } else { wp_new_user_notification($user_id, $password); } if (get_site_option('dashboard_blog') == false) { add_user_to_blog('1', $user_id, get_site_option('default_user_role', 'subscriber')); } else { add_user_to_blog(get_site_option('dashboard_blog'), $user_id, get_site_option('default_user_role', 'subscriber')); } wp_redirect(add_query_arg(array('updated' => 'true', 'action' => 'add'), $_SERVER['HTTP_REFERER'])); exit; break; default: wpmu_admin_do_redirect("wpmu-admin.php");
if (!current_user_can('manage_network_users')) { wp_die(__('You do not have permission to access this page.')); } if (is_array($_POST['user']) == false) { wp_die(__('Cannot create an empty user.')); } $user = $_POST['user']; if (empty($user['username']) && empty($user['email'])) { wp_die(__('Missing username and email.')); } elseif (empty($user['username'])) { wp_die(__('Missing username.')); } elseif (empty($user['email'])) { wp_die(__('Missing email.')); } $password = wp_generate_password(); $user_id = wpmu_create_user(esc_html(strtolower($user['username'])), $password, esc_html($user['email'])); if (false == $user_id) { wp_die(__('Duplicated username or email address.')); } else { wp_new_user_notification($user_id, $password); } if (get_site_option('dashboard_blog') == false) { add_user_to_blog($current_site->blog_id, $user_id, get_site_option('default_user_role', 'subscriber')); } else { add_user_to_blog(get_site_option('dashboard_blog'), $user_id, get_site_option('default_user_role', 'subscriber')); } wp_redirect(add_query_arg(array('updated' => 'true', 'action' => 'add'), wp_get_referer())); exit; break; default: wp_redirect(admin_url('ms-admin.php'));
/** * Create a site in a multisite install. * * ## OPTIONS * * --slug=<slug> * : Path for the new site. Subdomain on subdomain installs, directory on subdirectory installs. * * [--title=<title>] * : Title of the new site. Default: prettified slug. * * [--email=<email>] * : Email for Admin user. User will be created if none exists. Assignement to Super Admin if not included. * * [--network_id=<network-id>] * : Network to associate new site with. Defaults to current network (typically 1). * * [--private] * : If set, the new site will be non-public (not indexed) * * [--porcelain] * : If set, only the site id will be output on success. */ public function create($_, $assoc_args) { if (!is_multisite()) { WP_CLI::error('This is not a multisite install.'); } global $wpdb, $current_site; $base = $assoc_args['slug']; $title = \WP_CLI\Utils\get_flag_value($assoc_args, 'title', ucfirst($base)); $email = empty($assoc_args['email']) ? '' : $assoc_args['email']; // Network if (!empty($assoc_args['network_id'])) { $network = $this->_get_network($assoc_args['network_id']); if ($network === false) { WP_CLI::error(sprintf('Network with id %d does not exist.', $assoc_args['network_id'])); } } else { $network = $current_site; } $public = !\WP_CLI\Utils\get_flag_value($assoc_args, 'private'); // Sanitize if (preg_match('|^([a-zA-Z0-9-])+$|', $base)) { $base = strtolower($base); } // If not a subdomain install, make sure the domain isn't a reserved word if (!is_subdomain_install()) { $subdirectory_reserved_names = apply_filters('subdirectory_reserved_names', array('page', 'comments', 'blog', 'files', 'feed')); if (in_array($base, $subdirectory_reserved_names)) { WP_CLI::error('The following words are reserved and cannot be used as blog names: ' . implode(', ', $subdirectory_reserved_names)); } } // Check for valid email, if not, use the first Super Admin found // Probably a more efficient way to do this so we dont query for the // User twice if super admin $email = sanitize_email($email); if (empty($email) || !is_email($email)) { $super_admins = get_super_admins(); $email = ''; if (!empty($super_admins) && is_array($super_admins)) { // Just get the first one $super_login = $super_admins[0]; $super_user = get_user_by('login', $super_login); if ($super_user) { $email = $super_user->user_email; } } } if (is_subdomain_install()) { $path = '/'; $url = $newdomain = $base . '.' . preg_replace('|^www\\.|', '', $network->domain); } else { $newdomain = $network->domain; $path = '/' . trim($base, '/') . '/'; $url = $network->domain . $path; } $user_id = email_exists($email); if (!$user_id) { // Create a new user with a random password $password = wp_generate_password(12, false); $user_id = wpmu_create_user($base, $password, $email); if (false == $user_id) { WP_CLI::error("Can't create user."); } else { wp_new_user_notification($user_id, $password); } } $wpdb->hide_errors(); $id = wpmu_create_blog($newdomain, $path, $title, $user_id, array('public' => $public), $network->id); $wpdb->show_errors(); if (!is_wp_error($id)) { if (!is_super_admin($user_id) && !get_user_option('primary_blog', $user_id)) { update_user_option($user_id, 'primary_blog', $id, true); } // Prevent mailing admins of new sites // @TODO argument to pass in? // $content_mail = sprintf(__( "New site created by WP Command Line Interface\n\nAddress: %2s\nName: %3s"), get_site_url($id), stripslashes($title)); // wp_mail(get_site_option('admin_email'), sprintf(__('[%s] New Site Created'), $current_site->site_name), $content_mail, 'From: "Site Admin" <'.get_site_option( 'admin_email').'>'); } else { WP_CLI::error($id->get_error_message()); } if (\WP_CLI\Utils\get_flag_value($assoc_args, 'porcelain')) { WP_CLI::line($id); } else { WP_CLI::success("Site {$id} created: {$url}"); } }
function step3() { global $wpdb, $current_site, $dirs, $wpmu_version; $base = stripslashes(dirname($_SERVER["SCRIPT_NAME"])); if ($base != "/") { $base .= "/"; } $domain = get_clean_basedomain(); $email = $wpdb->escape($_POST['email']); if ($email == '') { die('You must enter an email address!'); } // set up site tables $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'site_name', '" . $wpdb->escape($_POST['weblog_title']) . "')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'admin_email', '" . $email . "')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'admin_user_id', '1')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'registration', 'none')"); $wpdb->query("INSERT INTO " . $wpdb->site . " ( id, domain, path ) VALUES ( NULL, '{$domain}', '{$base}' )"); $wpdb->query("INSERT INTO " . $wpdb->sitecategories . " ( cat_ID, cat_name, category_nicename, last_updated ) VALUES (1, 'Uncategorized', 'uncategorized', NOW())"); $wpdb->query("INSERT INTO " . $wpdb->sitecategories . " ( cat_ID, cat_name, category_nicename, last_updated ) VALUES (2, 'Blogroll', 'blogroll', NOW())"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'upload_filetypes', 'jpg jpeg png gif mp3 mov avi wmv midi mid pdf' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'blog_upload_space', '10' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'fileupload_maxk', '1500' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'site_admins', '" . serialize(array('admin')) . "' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'allowedthemes', '" . serialize(array('classic' => 1, 'default' => 1)) . "' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'illegal_names', '" . serialize(array("www", "web", "root", "admin", "main", "invite", "administrator")) . "' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'welcome_email', 'Dear User,\n\nYour new SITE_NAME blog has been successfully set up at:\nBLOG_URL\n\nYou can log in to the administrator account with the following information:\nUsername: USERNAME\nPassword: PASSWORD\nLogin Here: BLOG_URLwp-login.php\n\nWe hope you enjoy your new blog.\nThanks!\n\n--The Team @ SITE_NAME')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'first_post', 'Welcome to <a href=\"SITE_URL\">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' )"); $weblog_title = stripslashes($_POST['weblog_title']); $pass = substr(md5(rand()), 5, 12); $user_id = wpmu_create_user('admin', $pass, $email); $current_site->domain = $domain; $current_site->path = $base; $current_site->site_name = ucfirst($domain); wpmu_create_blog($domain, $base, $weblog_title, $user_id, array('blog_public' => 1, 'public' => 1)); update_blog_option(1, 'template', 'home'); update_blog_option(1, 'stylesheet', 'home'); if (constant('VHOST') == 'yes') { update_blog_option(1, 'permalink_structure', '/%year%/%monthnum%/%day%/%postname%/'); } else { update_blog_option(1, 'permalink_structure', '/blog/%year%/%monthnum%/%day%/%postname%/'); } $msg = "Your new WordPress MU site has been created at\nhttp://{$domain}{$base}\n\nLogin details:\nUsername: admin\nPassword: {$pass}\nLogin: http://{$domain}{$base}wp-login.php\n"; wp_mail($email, "Your new WordPress MU site is ready!", $msg, "From: wordpress@" . $_SERVER['HTTP_HOST']); ?> <h2>Installation Finished!</h2> <p>Congratulations! <br />Your <a href='http://<?php echo $domain . $base; ?> '>WordPress µ site</a> has been configured.</p> <p>You can <a class="button" href='wp-login.php'>log in</a> using the username "admin" and password <?php echo $pass; ?> </p> <?php if ($_POST['vhost'] == 'yes') { $vhost_ok = false; $hostname = substr(md5(time()), 0, 6) . '.' . $domain; // Very random hostname! if (include_once 'wp-includes/http.php') { $page = wp_remote_get('http://' . $hostname, array('timeout' => 5, 'httpversion' => '1.1')); if (is_object($page) && is_wp_error($page)) { foreach ($page->get_error_messages() as $err) { $errstr = $err; } } elseif ($page['response']['code'] == 200) { $vhost_ok = true; } } else { $fp = fsockopen($hostname, 80, $errno, $errstr, 5); // Very random hostname! if ($fp) { $vhost_ok = true; fclose($fp); } } if (!$vhost_ok) { echo "<h2>Warning! Wildcard DNS may not be configured correctly!</h2>"; echo "<p>To use the subdomain feature of WordPress MU you must have a wildcard entry in your dns. The installer attempted to contact a random hostname ({$hostname}) on your domain but failed. It returned this error message:<br /> <strong>{$errstr}</strong></p><p>From the README.txt:</p>"; echo "<p><blockquote> If you want to host blogs of the form http://blog.domain.tld/ where domain.tld is the domain name of your machine then you must add a wildcard record to your DNS records.<br />\nThis usually means adding a '*' hostname record pointing at your webserver in your DNS configuration tool. Matt has a more detailed <a href='http://ma.tt/2003/10/10/wildcard-dns-and-sub-domains/'>explanation</a> on his blog. If you still have problems, these <a href='http://mu.wordpress.org/forums/tags/wildcard'>forum messages</a> may help.</blockquote></p>"; echo "<p>You can still use your site but any subdomain you create may not be accessible. This check is not foolproof so ignore if you know your dns is correct.</p>"; } } ?> <h2>Directory Permissions</h2> <p>Please remember to reset the permissions on the following directories: <ul> <?php reset($dirs); foreach ((array) $dirs as $dir) { echo "<li>{$dir}</li>"; } ?> </ul> </p> <p>You can probably use the following command to fix the permissions but check with your host if it doubt: <br /> <code>chmod 755 <?php reset($dirs); foreach ((array) $dirs as $dir) { echo "{$dir} "; } ?> </code> </p> <h2>Further reading</h2> <p> <ul> <li>If you run into problems, please search the <a href='http://mu.wordpress.org/forums/'>WordPress µ Forums</a> where you will most likely find a solution. Please don't post there before searching. It's not polite.</li> <li>There is also the <a href='http://trac.mu.wordpress.org/'>WordPress µ Trac</a>. That's our bug tracker.</li> </ul> </p> <p>Thanks for installing WordPress µ!<br /><br />Donncha<br /><code>wpmu version: <?php echo $wpmu_version; ?> </code></p> <?php }
function ldapAddUserOptions() { global $blog_id, $current_user; if ($_POST['addUser']) { // Process the post request $user = $_POST['user']; if (empty($user['username']) && empty($user['email'])) { wp_die(__("<p>Missing username.</p>")); } $username = strtolower($user['username']); // try finding a WP account for this user name $login = get_user_by('login', $username); if (!$login) { $result = wpmuLdapSearchUser(array('username' => $username, 'blog_id' => $blog_id, 'new_role' => $user['new_role'])); if (is_wp_error($result)) { ldapAddUserResult(array('updated' => 'false', 'error' => $result, 'username' => $username)); } else { $ldapCreateLocalUser = get_site_option('ldapCreateLocalUser'); if ($result[0]) { wp_new_user_notification($result[1]); ldapAddUserResult(array('updated' => 'true', 'action' => 'add', 'username' => $username)); } elseif ($ldapCreateLocalUser || is_super_admin()) { ?> <div id='message' class='updated'> <form method='post'> <p><b><?php echo $username; ?> </b> not found in LDAP directory. To create a local user, enter the users email: <input type='text' name='user[email]' size='15' /> <input type='hidden' name='user[username]' value='<?php echo $username; ?> ' /> <input type='hidden' name='user[role]' value='<?php echo $user['new_role']; ?> ' /> <?php wp_nonce_field('add-local-user'); ?> <input type='submit' class='button' name='addLocalUser' value='Create Local User' /> </form></p> </div> <?php } else { ldapAddUserResult(array('updated' => 'false', 'action' => 'notfound', 'username' => $username)); } } } else { // Add User to Blog if (wpmuLdapAddUserToBlog($login->ID, $blog_id, $user['new_role'])) { wp_new_user_notification($login->ID); ldapAddUserResult(array('updated' => 'true', 'action' => 'add', 'username' => $username)); } else { ldapAddUserResult(array('updated' => 'false', 'action' => 'exists', 'username' => $username)); } } } elseif ($_POST['addUserBulk']) { // Check Access $ldapBulkAdd = get_site_option('ldapBulkAdd'); if (is_super_admin() || $ldapBulkAdd && is_admin()) { $user = $_POST['user']; $usernames = array(); if (!empty($user['bulk_username'])) { $usernames = explode("\n", $user['bulk_username']); $usernames = array_filter(array_map('trim', $usernames)); // trim whitespace from usernames and remove empty lines $usernames = array_map('strtolower', $usernames); } foreach ($usernames as $username) { // try finding a WP account for this user name $login = get_user_by('login', $username); if (!$login) { $result = wpmuLdapSearchUser(array('username' => $username, 'blog_id' => $blog_id, 'new_role' => $user['bulk_new_role'], 'createBlog' => false)); if (is_wp_error($result)) { ldapAddUserResult(array('updated' => 'false', 'error' => $result, 'username' => $username)); } else { if ($result[0]) { wp_new_user_notification($result[1]); ldapAddUserResult(array('updated' => 'true', 'action' => 'add', 'username' => $username)); } else { ldapAddUserResult(array('updated' => 'false', 'action' => 'notfound', 'username' => $username)); } } } else { // Add User to Blog if (wpmuLdapAddUserToBlog($login->ID, $blog_id, $user['bulk_new_role'])) { wp_new_user_notification($login->ID); ldapAddUserResult(array('updated' => 'true', 'action' => 'add', 'username' => $username)); } else { ldapAddUserResult(array('updated' => 'false', 'action' => 'exists', 'username' => $username)); } } } } else { ldapAddUserResult(array('updated' => 'false', 'action' => 'auth')); } } elseif ($_POST['addLocalUser']) { check_admin_referer('add-local-user'); $ldapCreateLocalUser = get_site_option('ldapCreateLocalUser'); if ($ldapCreateLocalUser || is_super_admin()) { $user = $_POST['user']; if (empty($user['username']) && empty($user['email'])) { wp_die(__("<p>Missing username and email.</p>")); } elseif (empty($user['username'])) { wp_die(__("<p>Missing username.</p>")); } elseif (empty($user['email'])) { wp_die(__("<p>Missing email.</p>")); } $password = generate_random_password(); $user_id = wpmu_create_user(wp_specialchars(strtolower($user['username'])), $password, wp_specialchars($user['email'])); if (false == $user_id) { wp_die(__("<p>Duplicated username or email address.</p>")); } else { wp_new_user_notification($user_id, $password); } // Update User Meta update_usermeta($user_id, 'primary_blog', $blog_id); // Configure User Role add_user_to_blog($blog_id, $user_id, $user['role']); ldapAddUserResult(array('updated' => 'true', 'action' => 'add', 'username' => $user['username'])); } else { wp_die(__("<p>Access denied.</p>")); } } ?> <div class="wrap"> <?php // Add User $ldapAddUser = get_site_option('ldapAddUser'); if (is_super_admin() || ($ldapAddUser == 'enabled' || empty($ldapAddUser))) { ?> <div id="icon-users" class="icon32"> <br /> </div> <h2><?php _e('Add User'); ?> </h2> <?php $ldapCreateLocalUser = get_site_option('ldapCreateLocalUser'); if ($ldapCreateLocalUser) { echo "<p>Local User Creation Enabled</p>"; } ?> <p> Using the following fields below to search out LDAP users and add them into the blog. <?php if ($ldapCreateLocalUser) { ?> If the user does not exist in the LDAP Directory, you will have the option to create a local account for them. <?php } ?> </p> <form method="post" id="ldap_add_user"> <?php wp_nonce_field('add-user'); ?> <fieldset class="options"> <table class="form-table" cellpadding="3" cellspacing="3"> <tr valign="top"> <th scope='row'><label for="addusername"><?php _e('Username:'******'Role:'); ?> </label></th> <td><?php wpmuLdapAddGenRoleBox('new_role'); ?> </td> </tr> </table> <p class="submit"> <input class="button" type="submit" name="addUser" value="<?php _e('Add User'); ?> " /> </p> </fieldset> </form> <?php } ?> <!-- Bulk Add User --> <?php $ldapBulkAdd = get_site_option('ldapBulkAdd'); if (is_super_admin() || $ldapBulkAdd && is_admin()) { ?> <h3><?php _e('Add Bulk Users'); ?> </h3> <p>Using the below fields, you can bulk add LDAP users. Separate multiple users by a new line. Local user creation is not available in bulk. The auto create blog for new users function will be disabled for bulk adds.</p> <form method="post" id="ldap_add_user_bulk"> <?php wp_nonce_field('add-user-bulk'); ?> <fieldset class="options"> <table class="form-table" cellpadding="3" cellspacing="3"> <tr valign="top"> <th scope='row'><label for="addbulkusername"><?php _e('Usernames:'); ?> </label></th> <td><textarea name="user[bulk_username]" id="addbulkusername" rows="15" cols="40"></textarea></td> </tr> <tr valign="top"> <th scope="row"><label for="bulk_new_role"><?php _e('Role:'); ?> </label></th> <td><?php wpmuLdapAddGenRoleBox('bulk_new_role'); ?> </td> </tr> </table> <p class="submit"> <input class="button" type="submit" name="addUserBulk" value="<?php _e('Add Bulk Users'); ?> " /> </p> </fieldset> </form> <?php } ?> </div> <?php }
function eMember_wp_create_user($user_name, $password, $email, $more = array()) { $more['role'] = isset($more['role']) ? $more['role'] : 'subscriber'; if (eMember_is_multisite_install()) { //MS install global $blog_id; if ($wp_user_id = email_exists($email)) { // if user exists then just add him to current blog. add_existing_user_to_blog(array('user_id' => $wp_user_id, 'role' => 'subscriber')); return $wp_user_id; } $wp_user_id = wpmu_create_user($user_name, $password, $email); if (is_wp_error($wp_user_id)) { eMember_log_debug("Error: " . $wp_user_id->get_error_message(), true); return $wp_user_id; } eMember_log_debug("Creating WP User using Multi site API. User ID: " . $wp_user_id . " Blog ID: " . $blog_id, true); $more['ID'] = $wp_user_id; wp_update_user($more); update_wp_user_Role($wp_user_id, $more['role']); $role = $more['role']; if (add_user_to_blog($blog_id, $wp_user_id, $role)) { //Add user to the current blog eMember_log_debug("WP MS user successfully added to blog ID: " . $blog_id, true); } else { eMember_log_debug("WP MS user addition to blog failed!", false); } return $wp_user_id; } else { //Single site install $wp_user_id = wp_create_user($user_name, $password, $email); if (is_wp_error($wp_user_id)) { eMember_log_debug("Error: " . $wp_user_id->get_error_message(), true); return $wp_user_id; } $more['ID'] = $wp_user_id; wp_update_user($more); update_wp_user_Role($wp_user_id, $more['role']); eMember_log_debug("Creating WP User using single site API. User ID: " . $wp_user_id, true); return $wp_user_id; } }
/** * Creates a WordPress user account from an LDAP response specified by * $ldapUserData. Assumes that a user account $newUserName does not already * exist. * * Code courtesy of dwang99 via post at * <code>http://patcavit.com/2005/05/11/wordpress-ldap-and-playing-nicely/</code> * * @author - dwang99 */ function wpmuLdapCreateWPUserFromLdap($opts) { global $base, $error, $wpdb, $current_site; // Extract Inputs extract($opts); if (!isset($newUserName)) { $newUserName = ''; } if (!isset($newUserPassword)) { $newUserPassword = ''; } if (!isset($ldapUserData)) { $ldapUserData = false; } if (!isset($createBlog)) { $createBlog = true; } // Check to see if email is empty if (empty($ldapUserData[LDAP_INDEX_EMAIL])) { return new WP_Error('ldapcreate_emailempty', sprintf(__('<strong>ERROR</strong>: <strong>%s</strong> does not have an email address associated with the ldap record. All wordpress accounts must have a unique email address.'), $newUserName)); } // Check to see if email already exists if (email_exists($ldapUserData[LDAP_INDEX_EMAIL])) { return new WP_Error('ldapcreate_emailconflict', sprintf(__('<strong>ERROR</strong>: <strong>%s</strong> (%s) is already associated with another account. All accounts (including the admin account) must have an unique email address.'), $ldapUserData[LDAP_INDEX_EMAIL], $newUserName)); } // we don't actually care about the WP password (since it's LDAP), but we need one for WP database $sPassword = generate_random_password(); $user_id = wpmu_create_user($newUserName, $sPassword, $ldapUserData[LDAP_INDEX_EMAIL]); if ($user_id === false) { return new WP_Error('ldapcreate_failed', __('<strong>ERROR</strong>: Account creation from LDAP failed.')); } //Update their first and last name from ldap update_usermeta($user_id, 'first_name', $ldapUserData[LDAP_INDEX_GIVEN_NAME]); update_usermeta($user_id, 'last_name', $ldapUserData[LDAP_INDEX_SURNAME]); update_usermeta($user_id, 'ldap_login', 'true'); //Set Public Display Name $displayName = get_site_option('ldapPublicDisplayName'); $display_name = ''; $ldapnick = $ldapUserData[LDAP_INDEX_NICKNAME]; if (!empty($ldapnick)) { $display_name = $ldapnick; } else { if (!empty($displayName)) { if ($displayName == 'username') { $display_name = $newUserName; } if ($displayName == 'first') { $display_name = $ldapUserData[LDAP_INDEX_GIVEN_NAME]; } if ($displayName == 'firstlast') { $display_name = $ldapUserData[LDAP_INDEX_GIVEN_NAME] . ' ' . $ldapUserData[LDAP_INDEX_SURNAME]; } if ($displayName == 'lastfirst') { $display_name = $ldapUserData[LDAP_INDEX_SURNAME] . ' ' . $ldapUserData[LDAP_INDEX_GIVEN_NAME]; } } else { $display_name = $newUserName; } } if (!empty($display_name)) { $wpdb->update($wpdb->users, compact('display_name'), array('ID' => $user_id)); } //This is for plugin events do_action('wpmu_activate_user', $user_id, $newUserPassword, false); $uname = strtolower(wp_specialchars($newUserName)); # WPMU doesnot accept non-alphanumeric characters $domain = preg_replace('/[^\\da-z]/i', '', $uname); if (constant("VHOST") == 'yes') { $newdomain = $domain . "." . $current_site->domain; $path = $base; } else { $newdomain = $current_site->domain; # prefix path with a / $path = '/' . $base . $domain . '/'; } // is it configured to create WP blogs from LDAP accounts? $ldapCreateBlog = get_site_option("ldapCreateBlog"); if ($createBlog && $ldapCreateBlog) { // Create and update the user's blog. $meta = apply_filters('signup_create_blog_meta', array('lang_id' => 'en', 'public' => 0)); $blog_id = wpmu_create_blog($newdomain, $path, $newUserName . "'s blog", $user_id, $meta); if (is_a($blog_id, "WP_Error")) { return new WP_Error('blogcreate_failed', __('<strong>ERROR</strong>: Blog creation from LDAP failed.')); } do_action('wpmu_activate_blog', $blog_id, $user_id, $newUserPassword, $newUserName . "'s blog", $meta); } // Add user as subscriber to blog #1 wpmuUpdateBlogAccess($user_id); return new WP_User($user_id); }
/** * Activate a signup. * * Hook to 'wpmu_activate_user' or 'wpmu_activate_blog' for events * that should happen only when users or sites are self-created (since * those actions are not called when users and sites are created * by a Super Admin). * * @since MU * * @global wpdb $wpdb * * @param string $key The activation key provided to the user. * @return array|WP_Error An array containing information about the activated user and/or blog */ function wpmu_activate_signup($key) { global $wpdb; $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key) ); if ( empty( $signup ) ) return new WP_Error( 'invalid_key', __( 'Invalid activation key.' ) ); if ( $signup->active ) { if ( empty( $signup->domain ) ) return new WP_Error( 'already_active', __( 'The user is already active.' ), $signup ); else return new WP_Error( 'already_active', __( 'The site is already active.' ), $signup ); } $meta = maybe_unserialize($signup->meta); $password = wp_generate_password( 12, false ); $user_id = username_exists($signup->user_login); if ( ! $user_id ) $user_id = wpmu_create_user($signup->user_login, $password, $signup->user_email); else $user_already_exists = true; if ( ! $user_id ) return new WP_Error('create_user', __('Could not create user'), $signup); $now = current_time('mysql', true); if ( empty($signup->domain) ) { $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) ); if ( isset( $user_already_exists ) ) return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup); wpmu_welcome_user_notification( $user_id, $password, $meta ); /** * Fires immediately after a new user is activated. * * @since MU * * @param int $user_id User ID. * @param int $password User password. * @param array $meta Signup meta data. */ do_action( 'wpmu_activate_user', $user_id, $password, $meta ); return array( 'user_id' => $user_id, 'password' => $password, 'meta' => $meta ); } $blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid ); // TODO: What to do if we create a user but cannot create a blog? if ( is_wp_error($blog_id) ) { // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and // setting the activation flag. Let's just set the active flag and instruct the user to reset their password. if ( 'blog_taken' == $blog_id->get_error_code() ) { $blog_id->add_data( $signup ); $wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) ); } return $blog_id; } $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) ); wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta); /** * Fires immediately after a site is activated. * * @since MU * * @param int $blog_id Blog ID. * @param int $user_id User ID. * @param int $password User password. * @param string $signup_title Site title. * @param array $meta Signup meta data. */ do_action( 'wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta ); return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta); }
function ajax_update_auth_user() { // Fail silently if current user doesn't have permissions. if (!current_user_can('edit_users')) { die(''); } // Nonce check. if (empty($_POST['nonce_save_auth_settings']) || !wp_verify_nonce($_POST['nonce_save_auth_settings'], 'save_auth_settings')) { die(''); } // Fail if requesting a change to an invalid setting. if (!in_array($_POST['setting'], array('access_users_pending', 'access_users_approved', 'access_users_blocked'))) { die(''); } // Editing a pending list entry. if ($_POST['setting'] === 'access_users_pending') { // Initialize posted data if empty. if (!(array_key_exists('access_users_pending', $_POST) && is_array($_POST['access_users_pending']))) { $_POST['access_users_pending'] = array(); } // Deal with each modified user (add or remove). foreach ($_POST['access_users_pending'] as $pending_user) { if ($pending_user['edit_action'] === 'add') { // Add new user to pending list and save (skip if it's // already there--someone else might have just done it). if (!$this->is_email_in_list($pending_user['email'], 'pending')) { $auth_settings_access_users_pending = $this->sanitize_user_list($this->get_plugin_option('access_users_pending', 'single admin')); array_push($auth_settings_access_users_pending, $pending_user); update_option('auth_settings_access_users_pending', $auth_settings_access_users_pending); } } else { if ($pending_user['edit_action'] === 'remove') { // Remove user from pending list and save if ($this->is_email_in_list($pending_user['email'], 'pending')) { $auth_settings_access_users_pending = $this->sanitize_user_list($this->get_plugin_option('access_users_pending', 'single admin')); foreach ($auth_settings_access_users_pending as $key => $existing_user) { if ($pending_user['email'] == $existing_user['email']) { unset($auth_settings_access_users_pending[$key]); break; } } update_option('auth_settings_access_users_pending', $auth_settings_access_users_pending); } } } } } // Editing an approved list entry. if ($_POST['setting'] === 'access_users_approved') { // Initialize posted data if empty. if (!(array_key_exists('access_users_approved', $_POST) && is_array($_POST['access_users_approved']))) { $_POST['access_users_approved'] = array(); } // Deal with each modified user (add, remove, or change_role). foreach ($_POST['access_users_approved'] as $approved_user) { if ($approved_user['edit_action'] === 'add') { // New user (create user, or add existing user to current site in multisite). $new_user = get_user_by('email', $approved_user['email']); if ($new_user !== false) { if (is_multisite()) { add_user_to_blog(get_current_blog_id(), $new_user->ID, $approved_user['role']); } } else { if ($approved_user['local_user'] === 'true') { // Create a WP account for this new *local* user and email the password. $plaintext_password = wp_generate_password(); // random password // If there's already a user with this username (e.g., // johndoe/johndoe@gmail.com exists, and we're trying to add // johndoe/johndoe@example.com), use the full email address // as the username. $username = explode("@", $approved_user['email']); $username = $username[0]; if (get_user_by('login', $username) !== false) { $username = $approved_user['email']; } if ($approved_user['multisite_user'] !== 'false') { $result = wpmu_create_user(strtolower($username), $plaintext_password, strtolower($approved_user['email'])); } else { $result = wp_insert_user(array('user_login' => strtolower($username), 'user_pass' => $plaintext_password, 'first_name' => '', 'last_name' => '', 'user_email' => strtolower($approved_user['email']), 'user_registered' => date('Y-m-d H:i:s'), 'role' => $approved_user['role'])); } if (!is_wp_error($result)) { // Email password to new user wp_new_user_notification($result, $plaintext_password); } } } // Email new user welcome message if plugin option is set. $this->maybe_email_welcome_message($approved_user['email']); // Add new user to approved list and save (skip if it's // already there--someone else might have just done it). if ($approved_user['multisite_user'] !== 'false') { if (!$this->is_email_in_list($approved_user['email'], 'approved', 'multisite')) { $auth_multisite_settings_access_users_approved = $this->sanitize_user_list($this->get_plugin_option('access_users_approved', 'multisite admin')); $approved_user['date_added'] = date('M Y'); array_push($auth_multisite_settings_access_users_approved, $approved_user); update_blog_option(BLOG_ID_CURRENT_SITE, 'auth_multisite_settings_access_users_approved', $auth_multisite_settings_access_users_approved); } } else { if (!$this->is_email_in_list($approved_user['email'], 'approved')) { $auth_settings_access_users_approved = $this->sanitize_user_list($this->get_plugin_option('access_users_approved', 'single admin')); $approved_user['date_added'] = date('M Y'); array_push($auth_settings_access_users_approved, $approved_user); update_option('auth_settings_access_users_approved', $auth_settings_access_users_approved); } } // If we've added a new multisite user, go through all pending/approved/blocked lists // on individual sites and remove this user from them (to prevent duplicate entries). if ($approved_user['multisite_user'] !== 'false' && is_multisite()) { $list_names = array('access_users_pending', 'access_users_approved', 'access_users_blocked'); foreach (wp_get_sites(array('limit' => 999999)) as $site) { foreach ($list_names as $list_name) { $user_list = get_blog_option($site['blog_id'], 'auth_settings_' . $list_name, array()); $list_changed = false; foreach ($user_list as $key => $user) { if ($user['email'] == $approved_user['email']) { unset($user_list[$key]); $list_changed = true; } } if ($list_changed) { update_blog_option($site['blog_id'], 'auth_settings_' . $list_name, $user_list); } } } } } else { if ($approved_user['edit_action'] === 'remove') { // Remove user from approved list and save if ($approved_user['multisite_user'] !== 'false') { if ($this->is_email_in_list($approved_user['email'], 'approved', 'multisite')) { $auth_multisite_settings_access_users_approved = $this->sanitize_user_list($this->get_plugin_option('access_users_approved', 'multisite admin')); foreach ($auth_multisite_settings_access_users_approved as $key => $existing_user) { if ($approved_user['email'] == $existing_user['email']) { unset($auth_multisite_settings_access_users_approved[$key]); break; } } update_blog_option(BLOG_ID_CURRENT_SITE, 'auth_multisite_settings_access_users_approved', $auth_multisite_settings_access_users_approved); } } else { if ($this->is_email_in_list($approved_user['email'], 'approved')) { $auth_settings_access_users_approved = $this->sanitize_user_list($this->get_plugin_option('access_users_approved', 'single admin')); foreach ($auth_settings_access_users_approved as $key => $existing_user) { if ($approved_user['email'] == $existing_user['email']) { unset($auth_settings_access_users_approved[$key]); break; } } update_option('auth_settings_access_users_approved', $auth_settings_access_users_approved); } } } else { if ($approved_user['edit_action'] === 'change_role') { // Update user's role in WordPress $changed_user = get_user_by('email', $approved_user['email']); if ($changed_user) { if (is_multisite() && $approved_user['multisite_user'] !== 'false') { foreach (get_blogs_of_user($changed_user->ID) as $blog) { add_user_to_blog($blog->userblog_id, $changed_user->ID, $approved_user['role']); } } else { $changed_user->set_role($approved_user['role']); } } if ($approved_user['multisite_user'] !== 'false') { if ($this->is_email_in_list($approved_user['email'], 'approved', 'multisite')) { $auth_multisite_settings_access_users_approved = $this->sanitize_user_list($this->get_plugin_option('access_users_approved', 'multisite admin')); foreach ($auth_multisite_settings_access_users_approved as $key => $existing_user) { if ($approved_user['email'] == $existing_user['email']) { $auth_multisite_settings_access_users_approved[$key]['role'] = $approved_user['role']; break; } } update_blog_option(BLOG_ID_CURRENT_SITE, 'auth_multisite_settings_access_users_approved', $auth_multisite_settings_access_users_approved); } } else { // Update user's role in approved list and save. if ($this->is_email_in_list($approved_user['email'], 'approved')) { $auth_settings_access_users_approved = $this->sanitize_user_list($this->get_plugin_option('access_users_approved', 'single admin')); foreach ($auth_settings_access_users_approved as $key => $existing_user) { if ($approved_user['email'] == $existing_user['email']) { $auth_settings_access_users_approved[$key]['role'] = $approved_user['role']; break; } } update_option('auth_settings_access_users_approved', $auth_settings_access_users_approved); } } } } } } } // Editing a blocked list entry. if ($_POST['setting'] === 'access_users_blocked') { // Initialize posted data if empty. if (!(array_key_exists('access_users_blocked', $_POST) && is_array($_POST['access_users_blocked']))) { $_POST['access_users_blocked'] = array(); } // Deal with each modified user (add or remove). foreach ($_POST['access_users_blocked'] as $blocked_user) { if ($blocked_user['edit_action'] === 'add') { // Add new user to blocked list and save (skip if it's // already there--someone else might have just done it). if (!$this->is_email_in_list($blocked_user['email'], 'blocked')) { $auth_settings_access_users_blocked = $this->sanitize_user_list($this->get_plugin_option('access_users_blocked', 'single admin')); $blocked_user['date_added'] = date('M Y'); array_push($auth_settings_access_users_blocked, $blocked_user); update_option('auth_settings_access_users_blocked', $auth_settings_access_users_blocked); } } else { if ($blocked_user['edit_action'] === 'remove') { // Remove auth_blocked usermeta for the user. $unblocked_user = get_user_by('email', $blocked_user['email']); if ($unblocked_user !== false) { delete_user_meta($unblocked_user->ID, 'auth_blocked', 'yes'); } // Remove user from blocked list and save if ($this->is_email_in_list($blocked_user['email'], 'blocked')) { $auth_settings_access_users_blocked = $this->sanitize_user_list($this->get_plugin_option('access_users_blocked', 'single admin')); foreach ($auth_settings_access_users_blocked as $key => $existing_user) { if ($blocked_user['email'] == $existing_user['email']) { unset($auth_settings_access_users_blocked[$key]); break; } } update_option('auth_settings_access_users_blocked', $auth_settings_access_users_blocked); } } } } } // Return 'success' value to AJAX call. die('success'); }
function bapi_create_site() { if (!preg_match('/bapi-signup\\.php$/', $_SERVER['REQUEST_URI'])) { return; } if (extension_loaded('newrelic')) { newrelic_start_transaction('WP InstaSites'); newrelic_name_transaction('create-instasite'); } if (isset($_POST['blogid']) && $_POST['blogid'] != 0) { header('Content-Type: application/javascript'); $d = get_blog_details($_POST['blogid']); if ($d === false) { $new_site = array("status" => "error", "data" => array("errors" => array("blogid_invalid" => "Unable to locate blog with ID: " . $_POST['blogid']), "error_data" => "")); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } switch_to_blog($_POST['blogid']); $blogid = get_current_blog_id(); if ($blogid != $_POST['blogid']) { $new_site = array("status" => "error", "data" => array("errors" => array("blogid_switch_fail" => "Unable to switch to BlogID: " . $_POST['blogid']), "error_data" => "")); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } //Do Update Stuff Here $prefix = $_POST['siteprefix']; $sname = $_POST['sitename']; $tagline = ''; if (isset($_POST['tagline']) && !empty($_POST['tagline'])) { $tagline = $_POST['tagline']; } $apikey = ""; if (isset($_POST['apikey']) && !empty($_POST['apikey'])) { $apikey = $_POST['apikey']; } $username = $_POST['username']; $password = $_POST['password']; $domain = $_SERVER['SERVER_NAME']; $siteurl = $prefix . '.' . $domain; //How to check which domain is used for current service $liveurl = 'http://' . $siteurl; if (isset($_POST['domain']) && !empty($_POST['domain'])) { $liveurl = $_POST['domain']; //bapi_site_cdn_domain } $cf_url = str_replace('http://', '', $liveurl); $cf_origin = str_replace('http://', '', $siteurl); $cf = modify_cf_distro($cf_origin, $cf_url); if ($cf['CreatingDistrib'] === false) { header('Content-Type: application/javascript'); $new_site = array("status" => "error", "data" => array("errors" => array("cloudfront_distrib" => 'Error Creating CloudFront Distribution'), "message" => $cf['Message'], "error_data" => "")); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } $liveurl = get_site_url(); if (isset($_POST['domain']) && !empty($_POST['domain'])) { $liveurl = $_POST['domain']; //bapi_site_cdn_domain } update_option('bapi_site_cdn_domain', $liveurl); update_option('bapi_cloudfrontid', $cf['Id']); $new_site = array("status" => "success", "data" => array("blog_id" => $_POST['blogid'], "blog_url" => get_site_url())); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } $prefix = $_POST['siteprefix']; $sname = $_POST['sitename']; $tagline = ''; if (isset($_POST['tagline']) && !empty($_POST['tagline'])) { $tagline = $_POST['tagline']; } $apikey = ""; if (isset($_POST['apikey']) && !empty($_POST['apikey'])) { $apikey = $_POST['apikey']; } $username = $_POST['username']; $password = $_POST['password']; $domain = $_SERVER['SERVER_NAME']; $siteurl = $prefix . '.' . $domain; //How to check which domain is used for current service $liveurl = 'http://' . $siteurl; if (isset($_POST['domain']) && !empty($_POST['domain'])) { $liveurl = $_POST['domain']; //bapi_site_cdn_domain } $cf_url = str_replace('http://', '', $liveurl); $cf_origin = str_replace('http://', '', $siteurl); if ($apikey == "") { header('Content-Type: application/javascript'); $new_site = array("status" => "error", "data" => array("errors" => array("apikey_not_set" => "A valid API key is required."), "error_data" => "")); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } $cf = create_cf_distro($cf_origin, $cf_url); if ($cf['CreatingDistrib'] === false) { header('Content-Type: application/javascript'); $new_site = array("status" => "error", "data" => array("errors" => array("cloudfront_distrib" => 'Error Creating CloudFront Distribution'), "message" => $cf['Message'], "error_data" => "")); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } $meta = array('api_key' => $apikey, 'bapi_secureurl' => '', 'bapi_site_cdn_domain' => $liveurl, 'bapi_cloudfronturl' => $cf['DomainName'], 'bapi_cloudfrontid' => $cf['Id'], 'blogdescription' => $tagline, 'bapi_first_look' => 1, 'blog_public' => 1); //http://codex.wordpress.org/Option_Reference#Privacy if (defined('BAPI_BASEURL') && BAPI_BASEURL == 'connect.bookt.biz') { $meta['bapi_secureurl'] = $prefix . '.lodgingcloud.com'; $meta['bapi_baseurl'] = BAPI_BASEURL; } //$siteurl = $prefix.'.imbookingsecure.com'; $u = username_exists($username); if (empty($u)) { $u = wpmu_create_user($username, $password, $username); } //$u = wpmu_create_user($username,$password,$username); if (is_numeric($u)) { $s = wpmu_create_blog($siteurl, '/', $sname, $u, $meta); //$t = wpmu_create_blog('wpmutest.localhost','/','Test1',1); //use this one to force a 'blog_taken' failure. if (is_numeric($s)) { //success switch_to_blog($s); //echo get_site_url();exit(); if (defined('KIGO_SELF_HOSTED') && !KIGO_SELF_HOSTED) { switch_theme(WP_DEFAULT_THEME); } else { switch_theme('instatheme01'); } bapi_wp_site_options(); //Initialize menu and pages //$path = '/bapi.init?p=1'; //$url = get_site_url().$path; //$server_output = file_get_contents($url); //Provide response header('Content-Type: application/javascript'); $new_site = array("status" => "success", "data" => array("blog_id" => $s, "blog_url" => get_site_url())); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } } else { //fail //print_r($s->errors['blog_taken'][0]); exit(); //Not sure if this is the only error returned. Need a more generic message handler. header('Content-Type: application/javascript'); $new_site = array("status" => "error", "data" => $s); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } } else { header('Content-Type: application/javascript'); $new_site = array("status" => "error", "data" => array("errors" => array("user_unknown" => "Sorry, the username specified is invalid."), "error_data" => "")); echo json_encode($new_site); if (extension_loaded('newrelic')) { newrelic_end_transaction(); } exit; } exit; }
function activate_signup($key) { global $wpdb; $signup = $wpdb->get_row($wpdb->prepare("select * from {$wpdb->signups} where activation_key = %s", $key)); if (empty($signup)) { return new \WP_Error('invalid_key', __('Invalid activation key.', 'mtv')); } if ($signup->active) { return new \WP_Error('already_active', __('This account is already activated.', 'mtv'), $signup); } $user_meta = unserialize($signup->meta); $user_login = $wpdb->escape($signup->user_login); $user_email = $wpdb->escape($signup->user_email); $user_pass = $user_meta['user_pass']; $user_id = username_exists($user_login); if (!$user_id) { $user_id = wpmu_create_user($user_login, wp_generate_password(12, false), $user_email); } if (!$user_id) { return new \WP_Error('create_user', __('Could not create user', 'mtv'), $signup); } // Be sure to unset the user pass because // we don't want to store it as meta once // the user is activated unset($user_meta['user_pass']); foreach ($user_meta as $k => $v) { update_user_meta($user_id, $k, $v); } $wpdb->update($wpdb->users, array('user_pass' => $user_pass, 'user_activation_key' => ''), array('ID' => $user_id)); $wpdb->update($wpdb->signups, array('active' => 1, 'activated' => current_time('mysql', true), 'meta' => ''), array('activation_key' => $key)); add_new_user_to_blog($user_id, $user_email, ''); return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta); }
/** * provisions new user account - does not add to any particular blog * @param $user_name * @return nothing */ function wind_create_wp_user($user_name, $wind_affiliations) { # now all the site options are available as variables extract(wind_getSiteOptions()); require_once "wind_defaults.php"; global $wpdb; $debug = false; // get_ldap_info returns // array(first_name => $firstName, last_name => $lastName, email => $email, uni => $uni); error_log("getting ldap info for {$user_name}\n", 3, $wind_log_file); $ldap_user_data = get_ldap_information($user_name); $user_email = $ldap_user_data['email']; $random_password = substr(md5(uniqid(microtime())), 0, 20); // create user $user_id = wpmu_create_user($user_name, $random_password, $user_email); /* for reference - other options $user_data = array( 'ID' => $user_id, 'user_login' => x, 'user_nicename' => x, 'first_name' => x, 'last_name' => x, 'nickname' => x, 'display_name' => x, 'user_email' => x, ); */ update_usermeta($user_id, 'first_name', $ldap_user_data['first_name']); update_usermeta($user_id, 'last_name', $ldap_user_data['last_name']); $superadmins = explode(" ", $wind_super_admins); if (in_array($user_name, $superadmins)) { error_log("{$user_name} is a super admin\n", 3, $wind_log_file); require_once WIND_WP_PATH . "wp-admin/includes/ms.php"; grant_super_admin($user_id); } $display_name = $ldap_user_data['display_name'] ? $ldap_user_data['display_name'] : $ldap_user_data['nickname']; if (empty($display_name) & !empty($ldap_user_data['first_name'])) { $display_name = $ldap_user_data['first_name'] . " " . $ldap_user_data['last_name']; } if (!empty($display_name)) { $wpdb->update($wpdb->users, compact('display_name'), array('ID' => $user_id)); } //This is for plugin events do_action('wpmu_activate_user', $user_id, $random_password, false); error_log("In create user - wind check course affils is {$wind_check_course_affils} \n", 3, $wind_log_file); if ($wind_check_course_affils) { error_log("yes check course affils for {$result->user_login}\n", 3, $wind_log_file); wind_add_to_blogs($result, $wind_affiliations, $debug); } }
/** * Create a single user * * @param WP_REST_Request $request Full details about the request. * @return WP_Error|WP_REST_Response */ public function create_item($request) { global $wp_roles; if (!empty($request['id'])) { return new WP_Error('rest_user_exists', __('Cannot create existing user.'), array('status' => 400)); } $user = $this->prepare_item_for_database($request); if (is_multisite()) { $ret = wpmu_validate_user_signup($user->user_login, $user->user_email); if (is_wp_error($ret['errors']) && !empty($ret['errors']->errors)) { return $ret['errors']; } } if (is_multisite()) { $user_id = wpmu_create_user($user->user_login, $user->user_pass, $user->user_email); if (!$user_id) { return new WP_Error('rest_user_create', __('Error creating new user.'), array('status' => 500)); } $user->ID = $user_id; $user_id = wp_update_user($user); if (is_wp_error($user_id)) { return $user_id; } } else { $user_id = wp_insert_user($user); if (is_wp_error($user_id)) { return $user_id; } $user->ID = $user_id; } $this->update_additional_fields_for_object($user, $request); /** * Fires after a user is created or updated via the REST API. * * @param object $user Data used to create the user (not a WP_User object). * @param WP_REST_Request $request Request object. * @param bool $creating True when creating user, false when updating user. */ do_action('rest_insert_user', $user, $request, true); $response = $this->get_item(array('id' => $user_id, 'context' => 'edit')); $response = rest_ensure_response($response); $response->set_status(201); $response->header('Location', rest_url('/wp/v2/users/' . $user_id)); return $response; }
function step3() { global $wpdb, $current_site, $dirs, $wpmu_version; $base = stripslashes(dirname($_SERVER["SCRIPT_NAME"])); if ($base != "/") { $base .= "/"; } $domain = get_clean_basedomain(); $email = $wpdb->escape($_POST['email']); if ($email == '') { die('You must enter an email address!'); } // set up site tables $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'site_name', '" . $wpdb->escape($_POST['weblog_title']) . "')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'admin_email', '" . $email . "')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'admin_user_id', '1')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'registration', 'none')"); $wpdb->query("INSERT INTO " . $wpdb->site . " ( id, domain, path ) VALUES ( NULL, '{$domain}', '{$base}' )"); $wpdb->query("INSERT INTO " . $wpdb->sitecategories . " ( cat_ID, cat_name, category_nicename, last_updated ) VALUES (1, 'Uncategorized', 'uncategorized', NOW())"); $wpdb->query("INSERT INTO " . $wpdb->sitecategories . " ( cat_ID, cat_name, category_nicename, last_updated ) VALUES (2, 'Blogroll', 'blogroll', NOW())"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'upload_filetypes', 'jpg jpeg png gif mp3 mov avi wmv midi mid pdf' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'blog_upload_space', '10' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'fileupload_maxk', '1500' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'site_admins', '" . serialize(array('admin')) . "' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'allowedthemes', '" . serialize(array('classic' => 1, 'default' => 1)) . "' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'illegal_names', '" . serialize(array("www", "web", "root", "admin", "main", "invite", "administrator")) . "' )"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'welcome_email', 'Dear User,\n\nYour new SITE_NAME blog has been successfully set up at:\nBLOG_URL\n\nYou can log in to the administrator account with the following information:\nUsername: USERNAME\nPassword: PASSWORD\nLogin Here: BLOG_URLwp-login.php\n\nWe hope you enjoy your new blog.\nThanks!\n\n--The Team @ SITE_NAME')"); $wpdb->query("INSERT INTO " . $wpdb->sitemeta . " (meta_id, site_id, meta_key, meta_value) VALUES (NULL, 1, 'first_post', 'Welcome to <a href=\"SITE_URL\">SITE_NAME</a>. This is your first post. Edit or delete it, then start blogging!' )"); $weblog_title = stripslashes($_POST['weblog_title']); $pass = substr(md5(rand()), 5, 12); $user_id = wpmu_create_user('admin', $pass, $email); $current_site->domain = $domain; $current_site->path = $base; $current_site->site_name = ucfirst($domain); wpmu_create_blog($domain, $base, $weblog_title, $user_id, array('blog_public' => 1, 'public' => 1)); update_blog_option(1, 'template', 'home'); update_blog_option(1, 'stylesheet', 'home'); if (constant('VHOST') == 'yes') { update_blog_option(1, 'permalink_structure', '/%year%/%monthnum%/%day%/%postname%/'); } else { update_blog_option(1, 'permalink_structure', '/blog/%year%/%monthnum%/%day%/%postname%/'); } update_blog_option(1, 'rewrite_rules', ''); $msg = "Your new WordPress MU site has been created at\nhttp://{$domain}{$base}\n\nLogin details:\nUsername: admin\nPassword: {$pass}\nLogin: http://{$domain}{$base}wp-login.php\n"; wp_mail($email, "Your new WordPress MU site is ready!", $msg, "From: wordpress@" . $_SERVER['HTTP_HOST']); ?> <h2>Installation Finished!</h2> <p>Congratulations! <br />Your <a href='http://<?php echo $domain . $base; ?> '>WordPress µ site</a> has been configured.</p> <p>You can <a class="button" href='wp-login.php'>log in</a> using the username "admin" and password <?php echo $pass; ?> </p> <h2>Directory Permissions</h2> <p>Please remember to reset the permissions on the following directories: <ul> <?php reset($dirs); foreach ((array) $dirs as $dir) { echo "<li>{$dir}</li>"; } ?> </ul> </p> <p>You can probably use the following command to fix the permissions but check with your host if it doubt: <br /> <code>chmod 755 <?php reset($dirs); foreach ((array) $dirs as $dir) { echo "{$dir} "; } ?> </code> </p> <h2>Further reading</h2> <p> <ul> <li>If you run into problems, please search the <a href='http://mu.wordpress.org/forums/'>WordPress µ Forums</a> where you will most likely find a solution. Please don't post there before searching. It's not polite.</li> <li>There is also the <a href='http://trac.mu.wordpress.org/'>WordPress µ Trac</a>. That's our bug tracker.</li> </ul> </p> <p>Thanks for installing WordPress µ!<br /><br />Donncha<br /><code>wpmu version: <?php echo $wpmu_version; ?> </code></p> <?php }
/** * Activate a signup. * * Hook to 'wpmu_activate_user' or 'wpmu_activate_blog' for events * that should happen only when users or sites are self-created (since * those actions are not called when users and sites are created * by a Super Admin). * * @since MU * @uses wp_generate_password() * @uses wpmu_welcome_user_notification() * @uses add_user_to_blog() * @uses add_new_user_to_blog() * @uses wpmu_create_user() * @uses wpmu_create_blog() * @uses wpmu_welcome_notification() * * @param string $key The activation key provided to the user. * @return array An array containing information about the activated user and/or blog */ function wpmu_activate_signup($key) { global $wpdb, $current_site; $signup = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->signups} WHERE activation_key = %s", $key)); if (empty($signup)) { return new WP_Error('invalid_key', __('Invalid activation key.')); } if ($signup->active) { if (empty($signup->domain)) { return new WP_Error('already_active', __('The user is already active.'), $signup); } else { return new WP_Error('already_active', __('The site is already active.'), $signup); } } $meta = unserialize($signup->meta); $user_login = $wpdb->escape($signup->user_login); $user_email = $wpdb->escape($signup->user_email); $password = wp_generate_password(12, false); $user_id = username_exists($user_login); if (!$user_id) { $user_id = wpmu_create_user($user_login, $password, $user_email); } else { $user_already_exists = true; } if (!$user_id) { return new WP_Error('create_user', __('Could not create user'), $signup); } $now = current_time('mysql', true); if (empty($signup->domain)) { $wpdb->update($wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key)); if (isset($user_already_exists)) { return new WP_Error('user_already_exists', __('That username is already activated.'), $signup); } wpmu_welcome_user_notification($user_id, $password, $meta); add_new_user_to_blog($user_id, $user_email, $meta); do_action('wpmu_activate_user', $user_id, $password, $meta); return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta); } $blog_id = wpmu_create_blog($signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid); // TODO: What to do if we create a user but cannot create a blog? if (is_wp_error($blog_id)) { // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and // setting the activation flag. Let's just set the active flag and instruct the user to reset their password. if ('blog_taken' == $blog_id->get_error_code()) { $blog_id->add_data($signup); $wpdb->update($wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key)); } return $blog_id; } $wpdb->update($wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key)); wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta); do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta); return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta); }
if (!is_email($email)) { wp_die(__('Invalid email address.')); } if (is_subdomain_install()) { $newdomain = $domain . '.' . preg_replace('|^www\\.|', '', $current_site->domain); $path = $current_site->path; } else { $newdomain = $current_site->domain; $path = $current_site->path . $domain . '/'; } $password = '******'; $user_id = email_exists($email); if (!$user_id) { // Create a new user with a random password $password = wp_generate_password(12, false); $user_id = wpmu_create_user($domain, $password, $email); if (false === $user_id) { wp_die(__('There was an error creating the user.')); } /** * Fires after a new user has been created via the network site-new.php page. * * @since 4.4.0 * * @param int $user_id ID of the newly created user. */ do_action('network_site_new_created_user', $user_id); } $wpdb->hide_errors(); $id = wpmu_create_blog($newdomain, $path, $title, $user_id, $meta, $current_site->id); $wpdb->show_errors();
function bernie_signup_user($user_name, $user_email) { // check if the user name is available, and if // not, we try to add a number to the username. $tempname = $user_name; $suffix = 2; // this test fails if there's no user with the username while ($user = get_user_by('login', $tempname)) { $tempname = $user_name . $suffix; } $user_name = $tempname; // let WP plugins have a crack at the username and email $signup_user_defaults = array('user_name' => $user_name, 'user_email' => $user_email, 'errors' => $errors); $filtered_results = apply_filters('signup_user_init', $signup_user_defaults); $user_name = $filtered_results['user_name']; $user_email = $filtered_results['user_email']; $errors = $filtered_results['errors']; if ($errors && $errors->get_error_codes()) { // do something with the errors } else { $password = wp_generate_password(12, false); $user_id = wpmu_create_user($user_name, $password, $user_email); $result = array('user_id' => $user_id, 'user_name' => $user_name, 'user_email' => $user_email, 'password' => $password); if (!$user_id) { $results['errors'] = new WP_Error('create_user', __('Could not create user'), $signup); } return $result; } }
/** * Maybe add a child from the "Children" section * * @since 0.1.0 */ function wp_user_parents_add_child() { // Bail if no signup nonce if (empty($_REQUEST['signup_nonce'])) { return; } // Bail if nonce fails if (!wp_verify_nonce($_REQUEST['signup_nonce'], 'wp_user_dashboard_child_signup')) { return; } // Bail if current user cannot have children if (!current_user_can('have_user_children')) { return; } // Sanitize fields $redirect = false; $email = sanitize_email($_REQUEST['email']); $firstname = !empty($_REQUEST['firstname']) ? $_REQUEST['firstname'] : ''; $lastname = !empty($_REQUEST['lastname']) ? $_REQUEST['lastname'] : ''; $password = !empty($_REQUEST['password']) ? $_REQUEST['password'] : wp_generate_password(12, false); $username = !empty($_REQUEST['username']) ? $_REQUEST['username'] : "******"; // Names are empty if (empty($firstname) || empty($lastname) || strlen($firstname) < 2 || strlen($lastname) < 2) { $args = array('error' => 'name'); $url = wp_get_user_dashboard_url('children'); $redirect = add_query_arg($args, $url); } // Username exists if (username_exists($username) || strlen($username) < 4) { $args = array('error' => 'username'); $url = wp_get_user_dashboard_url('children'); $redirect = add_query_arg($args, $url); } // Email exists if (email_exists($email)) { $args = array('error' => 'username'); $url = wp_get_user_dashboard_url('children'); $redirect = add_query_arg($args, $url); } // Redirect if (!empty($redirect)) { wp_safe_redirect($redirect); exit; } // Requires activation if (is_multisite() && apply_filters('wp_join_page_requires_activation', true)) { wpmu_signup_user($username, $email, array('add_to_blog' => get_current_blog_id(), 'new_role' => get_option('default_role'), 'first_name' => $firstname, 'last_name' => $lastname)); } // Create the user account $user_id = wpmu_create_user(esc_html(sanitize_key($username)), $password, $email); // Bail if no user ID for site if (empty($user_id)) { $args = array('error' => 'unknown'); $url = wp_get_user_dashboard_url('children'); $redirect = add_query_arg($args, $url); } // Get new userdata $user = new WP_User($user_id); $user->add_role('pending'); // Get the current user ID $current_user_id = get_current_user_id(); // Save fullname to usermeta update_user_meta($user->ID, 'first_name', $firstname); update_user_meta($user->ID, 'last_name', $lastname); add_user_meta($user->ID, 'user_parent', $current_user_id, false); // Do action do_action('wp_user_parents_added_child', $user, $current_user_id); // Redirect $args = array('success' => 'yay'); $url = wp_get_user_dashboard_url('children'); $redirect = add_query_arg($args, $url); wp_safe_redirect($redirect); die; }
/** * Creates a single user. * * @since 4.7.0 * @access public * * @param WP_REST_Request $request Full details about the request. * @return WP_REST_Response|WP_Error Response object on success, or WP_Error object on failure. */ public function create_item($request) { if (!empty($request['id'])) { return new WP_Error('rest_user_exists', __('Cannot create existing resource.'), array('status' => 400)); } $schema = $this->get_item_schema(); if (!empty($request['roles']) && !empty($schema['properties']['roles'])) { $check_permission = $this->check_role_update($request['id'], $request['roles']); if (is_wp_error($check_permission)) { return $check_permission; } } $user = $this->prepare_item_for_database($request); if (is_multisite()) { $ret = wpmu_validate_user_signup($user->user_login, $user->user_email); if (is_wp_error($ret['errors']) && !empty($ret['errors']->errors)) { return $ret['errors']; } } if (is_multisite()) { $user_id = wpmu_create_user($user->user_login, $user->user_pass, $user->user_email); if (!$user_id) { return new WP_Error('rest_user_create', __('Error creating new resource.'), array('status' => 500)); } $user->ID = $user_id; $user_id = wp_update_user($user); if (is_wp_error($user_id)) { return $user_id; } add_user_to_blog(get_site()->id, $user_id, ''); } else { $user_id = wp_insert_user($user); if (is_wp_error($user_id)) { return $user_id; } } $user = get_user_by('id', $user_id); if (!empty($request['roles']) && !empty($schema['properties']['roles'])) { array_map(array($user, 'add_role'), $request['roles']); } if (!empty($schema['properties']['meta']) && isset($request['meta'])) { $meta_update = $this->meta->update_value($request['meta'], $user_id); if (is_wp_error($meta_update)) { return $meta_update; } } $fields_update = $this->update_additional_fields_for_object($user, $request); if (is_wp_error($fields_update)) { return $fields_update; } /** * Fires immediately after a user is created or updated via the REST API. * * @since 4.7.0 * * @param WP_User $user Data used to create the user. * @param WP_REST_Request $request Request object. * @param bool $creating True when creating user, false when updating user. */ do_action('rest_insert_user', $user, $request, true); $request->set_param('context', 'edit'); $response = $this->prepare_item_for_response($user, $request); $response = rest_ensure_response($response); $response->set_status(201); $response->header('Location', rest_url(sprintf('%s/%s/%d', $this->namespace, $this->rest_base, $user_id))); return $response; }
/** * Import users from a CSV file. * * ## OPTIONS * * <file> * : The local or remote CSV file of users to import. * * [--send-email] * : Send an email to new users with their account details. * * [--skip-update] * : Don't update users that already exist. * * ## EXAMPLES * * # Import users from local CSV file * $ wp user import-csv /path/to/users.csv * Success: bobjones created * Success: newuser1 created * Success: existinguser created * * # Import users from remote CSV file * $ wp user import-csv http://example.com/users.csv * * Sample users.csv file: * * user_login,user_email,display_name,role * bobjones,bobjones@example.com,Bob Jones,contributor * newuser1,newuser1@example.com,New User,author * existinguser,existinguser@example.com,Existing User,administrator * * @subcommand import-csv */ public function import_csv($args, $assoc_args) { $blog_users = get_users(); $filename = $args[0]; if (0 === stripos($filename, 'http://') || 0 === stripos($filename, 'https://')) { $response = wp_remote_head($filename); $response_code = (string) wp_remote_retrieve_response_code($response); if (in_array($response_code[0], array(4, 5))) { WP_CLI::error("Couldn't access remote CSV file (HTTP {$response_code} response)."); } } else { if (!file_exists($filename)) { WP_CLI::error(sprintf("Missing file: %s", $filename)); } } foreach (new \WP_CLI\Iterators\CSV($filename) as $i => $new_user) { $defaults = array('role' => get_option('default_role'), 'user_pass' => wp_generate_password(), 'user_registered' => strftime("%F %T", time()), 'display_name' => false); $new_user = array_merge($defaults, $new_user); $secondary_roles = array(); if (!empty($new_user['roles'])) { $roles = array_map('trim', explode(',', $new_user['roles'])); $invalid_role = false; foreach ($roles as $role) { if (is_null(get_role($role))) { WP_CLI::warning("{$new_user['user_login']} has an invalid role."); $invalid_role = true; break; } } if ($invalid_role) { continue; } $new_user['role'] = array_shift($roles); $secondary_roles = $roles; } else { if ('none' === $new_user['role']) { $new_user['role'] = false; } elseif (is_null(get_role($new_user['role']))) { WP_CLI::warning("{$new_user['user_login']} has an invalid role."); continue; } } // User already exists and we just need to add them to the site if they aren't already there $existing_user = get_user_by('email', $new_user['user_email']); if (!$existing_user) { $existing_user = get_user_by('login', $new_user['user_login']); } if ($existing_user && \WP_CLI\Utils\get_flag_value($assoc_args, 'skip-update')) { WP_CLI::log("{$existing_user->user_login} exists and has been skipped."); continue; } else { if ($existing_user) { $new_user['ID'] = $existing_user->ID; $user_id = wp_update_user($new_user); if (!in_array($existing_user->user_login, wp_list_pluck($blog_users, 'user_login')) && is_multisite() && $new_user['role']) { add_user_to_blog(get_current_blog_id(), $existing_user->ID, $new_user['role']); WP_CLI::log("{$existing_user->user_login} added as {$new_user['role']}."); } // Create the user } else { unset($new_user['ID']); // Unset else it will just return the ID if (is_multisite()) { $ret = wpmu_validate_user_signup($new_user['user_login'], $new_user['user_email']); if (is_wp_error($ret['errors']) && !empty($ret['errors']->errors)) { WP_CLI::warning($ret['errors']); continue; } $user_id = wpmu_create_user($new_user['user_login'], $new_user['user_pass'], $new_user['user_email']); if (!$user_id) { WP_CLI::warning("Unknown error creating new user."); continue; } $new_user['ID'] = $user_id; $user_id = wp_update_user($new_user); if (is_wp_error($user_id)) { WP_CLI::warning($user_id); continue; } } else { $user_id = wp_insert_user($new_user); } if (\WP_CLI\Utils\get_flag_value($assoc_args, 'send-email')) { self::wp_new_user_notification($user_id, $new_user['user_pass']); } } } if (is_wp_error($user_id)) { WP_CLI::warning($user_id); continue; } else { if ($new_user['role'] === false) { delete_user_option($user_id, 'capabilities'); delete_user_option($user_id, 'user_level'); } } $user = get_user_by('id', $user_id); foreach ($secondary_roles as $secondary_role) { $user->add_role($secondary_role); } if (!empty($existing_user)) { WP_CLI::success($new_user['user_login'] . " updated."); } else { WP_CLI::success($new_user['user_login'] . " created."); } } }
/** * Outputs widget content. Overrides WP_Widget::widget(). Must be overidden by child class. * * @param array $args array of form elements * @param object $instance widget instance */ public function widget($args, $instance) { $username = null; extract($args); // output custom WP widget wrapper echo $before_widget; // output title based on option input $title = apply_filters('widget_title', $instance['title']); $customLink = empty($instance['customLink']) ? $this->defaults['customLink'] : $instance['customLink']; $customLinkTitle = empty($instance['customLinkTitle']) ? $this->defaults['customLinkTitle'] : $instance['customLinkTitle']; $default_tab = empty($instance['defaultTab']) ? $this->defaults['defaultTab'] : $instance['defaultTab']; $displayAvatar = empty($instance['displayAvatar']) ? $this->defaults['displayAvatar'] : $instance['displayAvatar']; $loginButtonLabel = empty($instance['loginButtonLabel']) ? $this->defaults['loginButtonLabel'] : $instance['loginButtonLabel']; $loginTabLabel = empty($instance['loginTabLabel']) ? $this->defaults['loginTabLabel'] : $instance['loginTabLabel']; $registerButtonLabel = empty($instance['registerButtonLabel']) ? $this->defaults['registerButtonLabel'] : $instance['registerButtonLabel']; $registerTabLabel = empty($instance['registerTabLabel']) ? $this->defaults['registerTabLabel'] : $instance['registerTabLabel']; $resetButtonLabel = empty($instance['resetButtonLabel']) ? $this->defaults['resetButtonLabel'] : $instance['resetButtonLabel']; $resetTabLabel = empty($instance['resetTabLabel']) ? $this->defaults['resetTabLabel'] : $instance['resetTabLabel']; // set default active tab $active_tab = $default_tab; // output widget title with WP wrapper if (!empty($title)) { echo $before_title . $title . $after_title; } // output html try { ?> <div id="wp-user-control-login-register-password"> <?php global $user_ID, $blog_id; get_currentuserinfo(); global $user_login, $user_email; // if user is not already logged in... if (!$user_ID) { // grab POST variables $login = array_key_exists('login', $_GET) ? trim($_GET['login']) : false; $register = array_key_exists('register', $_GET) ? trim($_GET['register']) : false; $reset = array_key_exists('reset', $_GET) ? trim($_GET['reset']) : false; ?> <?php // Output tabs ?> <ul class="tabs_login"> <li id="login_tab"><a href="#login_div"><?php echo $loginTabLabel; ?> </a></li> <li id="register_tab"><a href="#register_div"><?php echo $registerTabLabel; ?> </a></li> <li id="reset_tab"><a href="#reset_div"><?php echo $resetTabLabel; ?> </a></li> </ul> <div class="tab_container_login"> <?php // LOGIN FORM BEGIN ?> <div id="login_div" class="tab_content_login" style="display:none;"> <?php // handle user signon failure if ($login == 'failed') { $user_login = array_key_exists('user_login', $_REQUEST) ? trim($_REQUEST['user_login']) : false; $active_tab = 'login'; ?> <p><span class="loginfail"> <?php _e('Please check your username and password.', 'wp-user-control'); ?> </span></p> <?php } else { ?> <p> <?php _e('Enter your username and password below to login.', 'wp-user-control'); ?> </p><?php } ?> <form method="post" action="<?php echo wp_user_control_cleanURI($_SERVER['REQUEST_URI']) . '?wp_uc_login_request=true'; ?> " class="wp-user-form"> <div class="username"> <label for="user_login"><?php _e('Username', 'wp-user-control'); ?> : </label> <input type="text" name="user_login" value="<?php if (!isset($username)) { echo trim(stripslashes($user_login)); } else { echo trim(stripslashes($username)); } ?> " id="user_login" tabindex="11" /> </div> <div class="password"> <label for="user_pass"><?php _e('Password', 'wp-user-control'); ?> : </label> <input type="password" name="user_pass" value="" id="user_pass" tabindex="12" /> </div> <div class="login_fields"> <div class="remember"> <label for="remember"> <input type="checkbox" name="remember" value="forever" checked="checked" id="remember" tabindex="13" /> <?php _e('Remember me', 'wp-user-control'); ?> </label> </div> <?php do_action('login_form'); ?> <input type="submit" name="user-submit" value="<?php echo $loginButtonLabel; ?> " tabindex="14" class="user-submit" /> <input type="hidden" name="redirect_to" value="<?php echo wp_user_control_cleanURI($_SERVER['REQUEST_URI']); ?> " /> <input type="hidden" name="user-cookie" value="1" /> </div> </form> </div> <?php // LOGIN FORM END ?> <?php // REGISTRATION FORM BEGIN ?> <div id="register_div" class="tab_content_login" style="display:none;"> <?php // if register == true then set register as the active tab if ($register == 'true') { $active_tab = 'register'; } // set default for register error to none $register_error = 'none'; // first, determine user registration setting for site if (is_multisite()) { // make sure user registration is enabled $active_signup = get_site_option('registration'); // if signup option doesn't exist assume everything is enabled (blog and user signup) if (!$active_signup) { $active_signup = 'all'; } // determine specifics of what is enabled $active_signup = apply_filters('wpmu_active_signup', $active_signup); // return "all", "none", "blog" or "user" // if registration is enabled, proceed --- "all" or "user" if ($active_signup == 'all' || $active_signup == 'user') { $registrations_disabled = false; } else { $registrations_disabled = true; } // if not multisite, check user registration option for standard install } else { $registrations_disabled = get_option('users_can_register') ? false : true; } // check registration honey pot $reg_pot = array_key_exists('reg_pot', $_REQUEST) ? trim($_REQUEST['reg_pot']) : false; // grab desired user name and email $user_login = array_key_exists('user_login', $_REQUEST) ? trim($_REQUEST['user_login']) : false; $user_email = array_key_exists('user_email', $_REQUEST) ? trim($_REQUEST['user_email']) : false; /** * TODO: implement email validation function to check for valid email address format */ if (!empty($reg_pot)) { $register_error = 'honeypot'; // reset register flag $register = 'false'; } elseif (empty($user_login) && !empty($register) || empty($user_email) && !empty($register)) { $register_error = 'empty_fields'; // reset register flag $register = 'false'; // make sure user is not already signed in } elseif (is_user_logged_in() && !empty($register)) { // if they are then return an error message and we're done $register_error = 'logged_in'; // reset register flag $register = 'false'; // if registration has actually been submitted, proceed } elseif ($register) { if (username_exists($user_login)) { $register_error = 'username_exists'; // reset register flag $register = 'false'; // make sure user email is not already registered } elseif (email_exists($user_email)) { $register_error = 'email_exists'; // reset register flag $register = 'false'; // check for uppercase } elseif (preg_match("/[A-Z]/", $user_login)) { $register_error = 'uppercase'; // reset register flag $register = 'false'; // check for spaces } elseif (strpos($user_login, " ") !== false) { $register_error = 'spaces'; // reset register flag $register = 'false'; // otherwise proceed with registration checks } else { // make sure user registration is enabled if (!$registrations_disabled) { // set flag for successful registration $register = 'true'; // generate temp password $temp_password = wp_PluginUtilities::generatePassword(); // check for WPMS if (is_multisite()) { // register user for WPMS wpmu_create_user($user_login, $temp_password, $user_email); // get user info after it has been created if ($user = get_user_by('login', $user_login)) { // add user to current blog as subscriber add_user_to_blog($blog_id, $user->id, 'subscriber'); } // otherwise this is a standard WP install } else { // register user for WP standard wp_create_user($user_login, $temp_password, $user_email); } // send user notification email $message = wp_user_control_user_email_msg('new', $temp_password, home_url(), $user_login); // send new user registration email meassage wp_user_control_mail($message, 'New User Registration', $user_email); // otherwise, we're done - return message to WP User Control widget } else { $register_error = 'registration_disabled'; // reset register flag $register = 'false'; } } } // if registration attempt returned success if ($register == 'true') { ?> <p><?php _e('Check your email for the password and then return to log in.', 'wp-user-control'); ?> </p> <?php // if registration request has not been sent, output initial message } elseif ($register_error == 'none') { ?> <p><?php _e('Complete the form below to register.', 'wp-user-control'); ?> </p><?php // if registration request failed, process error } elseif ($register == 'false') { $registerError = $register_error; // output friendly registration error wp_user_control_output_registration_error($registerError); // other possibility is that user registrations are currently disabled } elseif ($registrations_disabled) { ?> <p><?php _e('New registrations currently disabled.', 'wp-user-control'); ?> </p><?php } ?> <form method="post" action="<?php echo wp_user_control_cleanURI($_SERVER['REQUEST_URI']) . '?register=true'; ?> " class="wp-user-form"> <div class="username"> <label for="user_login"><?php _e('Username', 'wp-user-control'); ?> : </label> <input type="text" <?php if ($registrations_disabled) { ?> disabled="disabled" <?php } ?> name="user_login" value="<?php echo stripslashes($user_login); ?> " id="user_login" tabindex="101" /> </div> <div class="password"> <label for="user_email"><?php _e('Email', 'wp-user-control'); ?> : </label> <input type="text" <?php if ($registrations_disabled) { ?> disabled="disabled" <?php } ?> name="user_email" value="<?php echo stripslashes($user_email); ?> " id="user_email" tabindex="102" /> </div> <div class="reg_pot"> <input type="text" name="reg_pot" value="" alt="if this field is not empty your registration will not be processed" /> </div> <div class="login_fields"> <?php do_action('register_form'); ?> <input type="submit" name="user-submit" value="<?php echo $registerButtonLabel; ?> " <?php if ($registrations_disabled) { ?> disabled="disabled" <?php } ?> class="user-submit" tabindex="103" /> <input type="hidden" name="redirect_to" value="<?php echo wp_user_control_cleanURI($_SERVER['REQUEST_URI']); ?> ?register=true" /> <input type="hidden" name="user-cookie" value="1" /> </div> </form> </div> <?php // REGISTRATION FORM END ?> <?php // RESET FORM BEGIN ?> <div id="reset_div" class="tab_content_login" style="display:none;"><?php if ($reset == 'true') { $active_tab = 'reset'; global $wpdb; $user_email = array_key_exists('user_email', $_POST) ? trim($_POST['user_email']) : null; $user_exists = false; if (!empty($user_email)) { // check for email if (email_exists($user_email)) { $user_exists = true; $reset_user = get_user_by('email', $user_email); // otherwise, user does not exist } else { $error[] = '<p><span class="registerfail">' . __('Email does not exist.', 'wp-user-control') . '</span></p>'; $reset = false; } } else { $error[] = '<p><span class="registerfail">' . __('Invalid email. Please try again.', 'wp-user-control') . '</span></p>'; } // if user exists, then proceed if ($user_exists) { $user_login = $reset_user->user_login; $user_email = $reset_user->user_email; // generate password $temp_password = wp_PluginUtilities::generatePassword(); // insert new password into WP DB wp_update_user(array('ID' => $reset_user->ID, 'user_pass' => $temp_password)); // create password reset email message $message = wp_user_control_user_email_msg('reset', $temp_password, home_url(), $user_login); wp_user_control_mail($message, 'Password Reset', $user_email); } // output errors, if appropriate if (isset($error) && count($error) > 0) { foreach ($error as $e) { echo $e; } $reset = false; // otherwise password reset was successful, so output message } else { ?> <p><?php _e('Check your email for your new password.', 'wp-user-control'); ?> </p><?php } } else { ?> <p><?php _e('Enter your email address to reset your password.', 'wp-user-control'); ?> </p><?php } ?> <form method="post" action="<?php echo wp_user_control_cleanURI($_SERVER['REQUEST_URI']); ?> ?reset=true" class="wp-user-form"> <div class="username"> <label for="user_email" class="hide"><?php _e('Email', 'wp-user-control'); ?> : </label> <input type="text" name="user_email" value="<?php if (!empty($user_email)) { echo $user_email; } ?> " id="user_email" tabindex="1001" /> </div> <div class="login_fields"> <?php do_action('login_form', 'resetpass'); ?> <input type="submit" name="user-submit" value="<?php echo $resetButtonLabel; ?> " class="user-submit" tabindex="1002" /> <input type="hidden" name="user-cookie" value="1" /> </div> </form> </div> </div> <?php // RESET FORM END ?> <?php // LOGGED IN USER BEGIN ?> <?php } else { // is logged in // output logged in user control box wp_user_control_logged_in_user($customLink, $customLinkTitle, $displayAvatar); } ?> <!-- WP User Control Widget JS --> <script type="text/javascript"> wp_user_control_widget_js( '<?php echo $active_tab; ?> ' ); </script> <!-- WP User Control Widget JS --> </div> <?php } catch (wp_PluginException $e) { echo $e->getError(); } // output custom WP widget wrapper echo $after_widget; }
public static function create_wp_user($wp_user_data) { if (self::is_multisite_install()) { //MS install global $blog_id; if ($wp_user_id = email_exists($wp_user_data['user_email'])) { // if user exists then just add him to current blog. add_existing_user_to_blog(array('user_id' => $wp_user_id, 'role' => 'subscriber')); return $wp_user_id; } $wp_user_id = wpmu_create_user($wp_user_data['user_login'], $wp_user_data['password'], $wp_user_data['user_email']); $role = 'subscriber'; //TODO - add user as a subscriber first. The subsequent update user role function to update the role to the correct one add_user_to_blog($blog_id, $wp_user_id, $role); } else { //Single site install $wp_user_id = email_exists($wp_user_data['user_email']); if ($wp_user_id) { return $wp_user_id; } $wp_user_id = wp_create_user($wp_user_data['user_login'], $wp_user_data['password'], $wp_user_data['user_email']); } $wp_user_data['ID'] = $wp_user_id; wp_update_user($wp_user_data); $user_info = get_userdata($wp_user_id); $user_cap = isset($user_info->wp_capabilities) && is_array($user_info->wp_capabilities) ? array_keys($user_info->wp_capabilities) : array(); if (!in_array('administrator', $user_cap)) { SwpmUtils::update_wp_user_Role($wp_user_id, $wp_user_data['role']); } return $wp_user_id; }
/** * Creates an admin user if no user exists with this email * @since 0.2.0 * @param string $email the email * @param string $domain the domain * @return int id of the user */ public static function create_admin($email, $domain) { // Create New site Admin if not exists $password = '******'; $user_id = email_exists($email); if (!$user_id) { // Create a new user with a random password $password = wp_generate_password(12, false); $user_id = wpmu_create_user($domain, $password, $email); if (false == $user_id) { return new WP_Error('file_copy', MUCD_NETWORK_PAGE_DUPLICATE_ADMIN_ERROR_CREATE_USER); } else { wp_new_user_notification($user_id, $password); } } return $user_id; }