Example #1
1
 function get_user_by($field, $value)
 {
     $userdata = WP_User::get_data_by($field, $value);
     if (!$userdata) {
         return false;
     }
     $user = new WP_User();
     $user->init($userdata);
     return $user;
 }
 private function _getWPUser($id)
 {
     $userdata = WP_User::get_data_by('login', $id);
     if (!$userdata) {
         return false;
     }
     $user = new WP_User();
     $user->init($userdata);
     return $user;
 }
Example #3
0
 /**
  * Class constructor.
  *
  * @since   141111 First documented version.
  *
  * @param array $request_args Arguments to the constructor.
  *                            These should NOT be trusted; they come from a `$_REQUEST` action.
  * @param array $args         Any additional behavioral args.
  *
  *    Regarding user-initiated actions. The following arguments may apply.
  *
  *       • `user_initiated` This is intended to identify user-initiated inserts/updates.
  *             This argument MUST be defined if you intend to use any other user-initiated arguments.
  *
  *       • `ui_protected_data_keys_enable` is a secondary argument to indicate that it's both a user-initiated event
  *             and that we also WANT data key protections enabled. For instance, when a user is inserting/updating on their own.
  *
  *             • This flag exists so that it's still possible for us to systematically update something on behalf of a user,
  *                without triggering the additional protected data key validations, should those be unwanted at times.
  *                Use of `user_initiated` w/o data key protections should be careful to sanitize all input data.
  *
  *       • `ui_protected_data_user` This is the only way to insert/update a specific user ID
  *             whenever the `ui_protected_data_keys_enable` flag is `TRUE`; i.e. the `user_id` is a protected/nullified key.
  *             Thus, the only way to push a user ID through is by passing it through args; using a trusted data source.
  *
  * @warning Generally speaking, user-initiated actions (i.e. `user_initiated`) should NOT be allowed to push request arguments
  *    into this method that may update protected data keys such as: `key`, `user_id`, `insertion_ip`, `last_update_time`, and others.
  *
  *    To enable validation of protected data keys please pass `user_initiated` + `ui_protected_data_keys_enable` as `TRUE`.
  *       This automatically removes/sanitizes/validates protected data keys before an insertion or update occurs.
  *
  *    Note: on insert/update with `user_initiated` + `ui_protected_data_keys_enable`, the only way to set the `user_id` is by
  *       passing the `ui_protected_data_user` argument also — the initiating user; i.e. the user doing an insert/update.
  *
  *    Note: updates w/ `user_initiated` + `ui_protected_data_keys_enable` require a read-only `key` to successfully complete the update.
  *       i.e. An input `key` is validated against the `ID` in the input request args during update. It must match up!
  *
  *    The following keys can never be inserted/updated with `user_initiated` + `ui_protected_data_keys_enable`:
  *
  *       • `key`; never; only inserted/updated systematically (no exceptions).
  *          ~ This is only updated systematically when an email changes.
  *
  *       • `user_id`; requires `ui_protected_data_user`.
  *
  *       • `insertion_ip`; inserted/updated systematically.
  *       • `insertion_region`; inserted/updated systematically.
  *       • `insertion_country`; inserted/updated systematically.
  *
  *       • `last_ip`; inserted/updated systematically.
  *       • `last_region`; inserted/updated systematically.
  *       • `last_country`; inserted/updated systematically.
  *
  *       • `insertion_time`; inserted/updated systematically.
  *       • `last_update_time`; inserted/updated systematically.
  *
  *    ~ On insert, `status` is always `unconfirmed` by force.
  *
  *    ~ On update, `status` can by anything except `trashed`.
  *       A user cannot trash themselves under any circumstance.
  */
 public function __construct(array $request_args, array $args = [])
 {
     parent::__construct();
     /* Related to the data. */
     $default_request_args = ['ID' => null, 'key' => null, 'user_id' => null, 'post_id' => null, 'comment_id' => null, 'deliver' => null, 'fname' => null, 'lname' => null, 'email' => null, 'insertion_ip' => null, 'insertion_region' => null, 'insertion_country' => null, 'last_ip' => null, 'last_region' => null, 'last_country' => null, 'status' => null, 'insertion_time' => null, 'last_update_time' => null];
     $request_args = array_merge($default_request_args, $request_args);
     $request_args = array_intersect_key($request_args, $default_request_args);
     $this->data = $request_args;
     // A copy of the request args.
     $this->validated = false;
     // Initialize; not validated yet, obviously.
     if (isset($this->data['ID'])) {
         $this->data['ID'] = (int) $this->data['ID'];
     }
     /* Related to inserts. */
     $this->is_insert = !isset($this->data['ID']);
     $this->inserted = false;
     // Initialize.
     $this->replaced = false;
     // Initialize.
     $this->insert_id = 0;
     // Initialize.
     /* Related to updates. */
     $this->is_update = isset($this->data['ID']);
     if ($this->is_update && $this->data['ID']) {
         $this->sub = $this->plugin->utils_sub->get($this->data['ID']);
     }
     $this->updated = false;
     // Initialize.
     $this->email_key_changed = false;
     // Initialize.
     /* Related to args/flags. */
     $defaults_args = ['auto_confirm' => null, 'process_events' => true, 'process_confirmation' => false, 'process_list_server' => false, 'user_initiated' => false, 'ui_protected_data_keys_enable' => false, 'ui_protected_data_user' => null, 'user_allow_0' => null, 'keep_existing' => false, 'check_blacklist' => true];
     $args = array_merge($defaults_args, $args);
     $args = array_intersect_key($args, $defaults_args);
     if (isset($args['auto_confirm'])) {
         $this->auto_confirm = (bool) $args['auto_confirm'];
     }
     $this->process_events = (bool) $args['process_events'];
     $this->process_confirmation = (bool) $args['process_confirmation'];
     $this->process_list_server = (bool) $args['process_list_server'];
     $this->user_initiated = (bool) $args['user_initiated'];
     $this->user_initiated = $this->plugin->utils_sub->checkUserInitiatedByAdmin($this->data['email'] ? $this->data['email'] : ($this->is_update && $this->sub ? $this->sub->email : ''), $this->user_initiated);
     $this->ui_protected_data_keys_enable = $this->user_initiated && $args['ui_protected_data_keys_enable'];
     $this->ui_protected_data_user = null;
     // Recording here; but can't be filled until later below.
     if ($this->user_initiated) {
         // Protected data keys?
         if ($this->ui_protected_data_keys_enable) {
             $this->data['user_id'] = null;
             $this->data['insertion_ip'] = null;
             $this->data['insertion_region'] = null;
             $this->data['insertion_country'] = null;
             $this->data['last_ip'] = null;
             $this->data['last_region'] = null;
             $this->data['last_country'] = null;
             $this->data['insertion_time'] = null;
             $this->data['last_update_time'] = null;
         }
     }
     if (isset($args['user_allow_0'])) {
         // Iff `$this->user_initiated` also.
         $this->user_allow_0 = $this->user_initiated && $args['user_allow_0'];
     } else {
         $this->user_allow_0 = $this->user_initiated;
         // Defaults to this value.
     }
     $this->keep_existing = (bool) $args['keep_existing'];
     $this->check_blacklist = (bool) $args['check_blacklist'];
     /* Related to user. */
     if (!isset($this->user) || !$this->user->ID) {
         if ((int) $this->data['user_id'] > 0) {
             // A potentially new user ID?
             $this->user = new \WP_User((int) $this->data['user_id']);
         }
     }
     if ($this->user_initiated && $this->ui_protected_data_keys_enable && !isset($this->data['user_id']) && $args['ui_protected_data_user'] instanceof \WP_User) {
         $this->user = $this->ui_protected_data_user = $args['ui_protected_data_user'];
     }
     if (!isset($this->user) || !$this->user->ID) {
         if ($this->user_initiated) {
             $this->user = wp_get_current_user();
         }
     }
     if (!isset($this->user) || !$this->user->ID) {
         if ($this->is_update && $this->sub && $this->sub->user_id) {
             $this->user = new \WP_User($this->sub->user_id);
         }
     }
     if (!isset($this->user) || !$this->user->ID) {
         if ((string) $this->data['email']) {
             // A potentially new email address?
             if ($_user = \WP_User::get_data_by('email', (string) $this->data['email'])) {
                 $this->user = new \WP_User($_user->ID);
             }
         }
     }
     unset($_user);
     // Housekeeping.
     if (!isset($this->user) || !$this->user->ID) {
         if ($this->is_update && $this->sub && $this->sub->email) {
             if ($_user = \WP_User::get_data_by('email', $this->sub->email)) {
                 $this->user = new \WP_User($_user->ID);
             }
         }
     }
     unset($_user);
     // Housekeeping.
     if (!isset($this->user) || !$this->user->ID) {
         if ($this->user_allow_0 && $this->data['user_id'] === 0) {
             $this->user = new \WP_User(0);
         }
     }
     if (!$this->user_allow_0 && $this->user && !$this->user->ID) {
         $this->user = null;
         // Do not allow `0` in this case.
     }
     /* Related to current user. */
     if ($this->user_initiated) {
         $this->is_current_user = true;
     } else {
         $this->is_current_user = $this->user && $this->plugin->utils_user->isCurrent($this->user, $this->user_allow_0);
     }
     /* Related to duplicates. */
     $this->duplicate_key_ids = [];
     // Initialize.
     $this->other_duplicate_ids = [];
     // Initialize.
     /* Related to success/error reporting. */
     $this->errors = [];
     // Initialize.
     $this->successes = [];
     // Initialize.
     /* OK, let's do this. */
     $this->maybeInsertUpdate();
 }
Example #4
0
function userpro_profile_updated($user_id, $old_user_data)
{
    global $userpro;
    if (!empty($user_id)) {
        $current_user_data = WP_User::get_data_by('id', $user_id);
        $display_name = $current_user_data->display_name;
        update_user_meta($user_id, 'display_name', $display_name);
    }
    $userpro->clear_cache();
}
Example #5
0
/**
 * Insert a user into the database.
 *
 * Most of the `$userdata` array fields have filters associated with the values. Exceptions are
 * 'ID', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl',
 * 'user_registered', and 'role'. The filters have the prefix 'pre_user_' followed by the field
 * name. An example using 'description' would have the filter called, 'pre_user_description' that
 * can be hooked into.
 *
 * @since 2.0.0
 * @since 3.6.0 The `aim`, `jabber`, and `yim` fields were removed as default user contact
 *              methods for new installs. See wp_get_user_contact_methods().
 *
 * @global wpdb $wpdb WordPress database object for queries.
 *
 * @param array|object|WP_User $userdata {
 *     An array, object, or WP_User object of user data arguments.
 *
 *     @type int         $ID                   User ID. If supplied, the user will be updated.
 *     @type string      $user_pass            The plain-text user password.
 *     @type string      $user_login           The user's login username.
 *     @type string      $user_nicename        The URL-friendly user name.
 *     @type string      $user_url             The user URL.
 *     @type string      $user_email           The user email address.
 *     @type string      $display_name         The user's display name.
 *                                             Default is the the user's username.
 *     @type string      $nickname             The user's nickname.
 *                                             Default is the the user's username.
 *     @type string      $first_name           The user's first name. For new users, will be used
 *                                             to build the first part of the user's display name
 *                                             if `$display_name` is not specified.
 *     @type string      $last_name            The user's last name. For new users, will be used
 *                                             to build the second part of the user's display name
 *                                             if `$display_name` is not specified.
 *     @type string      $description          The user's biographical description.
 *     @type string|bool $rich_editing         Whether to enable the rich-editor for the user.
 *                                             False if not empty.
 *     @type string|bool $comment_shortcuts    Whether to enable comment moderation keyboard
 *                                             shortcuts for the user. Default false.
 *     @type string      $admin_color          Admin color scheme for the user. Default 'fresh'.
 *     @type bool        $use_ssl              Whether the user should always access the admin over
 *                                             https. Default false.
 *     @type string      $user_registered      Date the user registered. Format is 'Y-m-d H:i:s'.
 *     @type string|bool $show_admin_bar_front Whether to display the Admin Bar for the user on the
 *                                             site's frontend. Default true.
 *     @type string      $role                 User's role.
 * }
 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
 *                      be created.
 */
function wp_insert_user($userdata)
{
    global $wpdb;
    if ($userdata instanceof stdClass) {
        $userdata = get_object_vars($userdata);
    } elseif ($userdata instanceof WP_User) {
        $userdata = $userdata->to_array();
    }
    // Are we updating or creating?
    if (!empty($userdata['ID'])) {
        $ID = (int) $userdata['ID'];
        $update = true;
        $old_user_data = WP_User::get_data_by('id', $ID);
        // hashed in wp_update_user(), plaintext if called directly
        $user_pass = $userdata['user_pass'];
    } else {
        $update = false;
        // Hash the password
        $user_pass = wp_hash_password($userdata['user_pass']);
    }
    $sanitized_user_login = sanitize_user($userdata['user_login'], true);
    /**
     * Filter a username after it has been sanitized.
     *
     * This filter is called before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $sanitized_user_login Username after it has been sanitized.
     */
    $pre_user_login = apply_filters('pre_user_login', $sanitized_user_login);
    //Remove any non-printable chars from the login string to see if we have ended up with an empty username
    $user_login = trim($pre_user_login);
    if (empty($user_login)) {
        return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.'));
    }
    if (!$update && username_exists($user_login)) {
        return new WP_Error('existing_user_login', __('Sorry, that username already exists!'));
    }
    // If a nicename is provided, remove unsafe user characters before
    // using it. Otherwise build a nicename from the user_login.
    if (!empty($userdata['user_nicename'])) {
        $user_nicename = sanitize_user($userdata['user_nicename'], true);
    } else {
        $user_nicename = $user_login;
    }
    $user_nicename = sanitize_title($user_nicename);
    // Store values to save in user meta.
    $meta = array();
    /**
     * Filter a user's nicename before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $user_nicename The user's nicename.
     */
    $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
    $raw_user_url = empty($userdata['user_url']) ? '' : $userdata['user_url'];
    /**
     * Filter a user's URL before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $raw_user_url The user's URL.
     */
    $user_url = apply_filters('pre_user_url', $raw_user_url);
    $raw_user_email = empty($userdata['user_email']) ? '' : $userdata['user_email'];
    /**
     * Filter a user's email before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $raw_user_email The user's email.
     */
    $user_email = apply_filters('pre_user_email', $raw_user_email);
    /*
     * If there is no update, just check for `email_exists`. If there is an update,
     * check if current email and new email are the same, or not, and check `email_exists`
     * accordingly.
     */
    if ((!$update || !empty($old_user_data) && 0 !== strcasecmp($user_email, $old_user_data->user_email)) && !defined('WP_IMPORTING') && email_exists($user_email)) {
        return new WP_Error('existing_user_email', __('Sorry, that email address is already used!'));
    }
    $nickname = empty($userdata['nickname']) ? $user_login : $userdata['nickname'];
    /**
     * Filter a user's nickname before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $nickname The user's nickname.
     */
    $meta['nickname'] = apply_filters('pre_user_nickname', $nickname);
    $first_name = empty($userdata['first_name']) ? '' : $userdata['first_name'];
    /**
     * Filter a user's first name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $first_name The user's first name.
     */
    $meta['first_name'] = apply_filters('pre_user_first_name', $first_name);
    $last_name = empty($userdata['last_name']) ? '' : $userdata['last_name'];
    /**
     * Filter a user's last name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $last_name The user's last name.
     */
    $meta['last_name'] = apply_filters('pre_user_last_name', $last_name);
    if (empty($userdata['display_name'])) {
        if ($update) {
            $display_name = $user_login;
        } elseif ($meta['first_name'] && $meta['last_name']) {
            /* translators: 1: first name, 2: last name */
            $display_name = sprintf(_x('%1$s %2$s', 'Display name based on first name and last name'), $meta['first_name'], $meta['last_name']);
        } elseif ($meta['first_name']) {
            $display_name = $meta['first_name'];
        } elseif ($meta['last_name']) {
            $display_name = $meta['last_name'];
        } else {
            $display_name = $user_login;
        }
    } else {
        $display_name = $userdata['display_name'];
    }
    /**
     * Filter a user's display name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $display_name The user's display name.
     */
    $display_name = apply_filters('pre_user_display_name', $display_name);
    $description = empty($userdata['description']) ? '' : $userdata['description'];
    /**
     * Filter a user's description before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $description The user's description.
     */
    $meta['description'] = apply_filters('pre_user_description', $description);
    $meta['rich_editing'] = empty($userdata['rich_editing']) ? 'true' : $userdata['rich_editing'];
    $meta['comment_shortcuts'] = empty($userdata['comment_shortcuts']) || 'false' === $userdata['comment_shortcuts'] ? 'false' : 'true';
    $admin_color = empty($userdata['admin_color']) ? 'fresh' : $userdata['admin_color'];
    $meta['admin_color'] = preg_replace('|[^a-z0-9 _.\\-@]|i', '', $admin_color);
    $meta['use_ssl'] = empty($userdata['use_ssl']) ? 0 : $userdata['use_ssl'];
    $user_registered = empty($userdata['user_registered']) ? gmdate('Y-m-d H:i:s') : $userdata['user_registered'];
    $meta['show_admin_bar_front'] = empty($userdata['show_admin_bar_front']) ? 'true' : $userdata['show_admin_bar_front'];
    $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $user_nicename, $user_login));
    if ($user_nicename_check) {
        $suffix = 2;
        while ($user_nicename_check) {
            $alt_user_nicename = $user_nicename . "-{$suffix}";
            $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $alt_user_nicename, $user_login));
            $suffix++;
        }
        $user_nicename = $alt_user_nicename;
    }
    $compacted = compact('user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered');
    $data = wp_unslash($compacted);
    if ($update) {
        if ($user_email !== $old_user_data->user_email) {
            $data['user_activation_key'] = '';
        }
        $wpdb->update($wpdb->users, $data, compact('ID'));
        $user_id = (int) $ID;
    } else {
        $wpdb->insert($wpdb->users, $data + compact('user_login'));
        $user_id = (int) $wpdb->insert_id;
    }
    $user = new WP_User($user_id);
    /**
     * Filter a user's meta values and keys before the user is created or updated.
     *
     * Does not include contact methods. These are added using `wp_get_user_contact_methods( $user )`.
     *
     * @since 4.4.0
     *
     * @param array $meta {
     *     Default meta values and keys for the user.
     *
     *     @type string   $nickname             The user's nickname. Default is the the user's username.
     *     @type string   $first_name           The user's first name.
     *     @type string   $last_name            The user's last name.
     *     @type string   $description          The user's description.
     *     @type bool     $rich_editing         Whether to enable the rich-editor for the user. False if not empty.
     *     @type bool     $comment_shortcuts    Whether to enable keyboard shortcuts for the user. Default false.
     *     @type string   $admin_color          The color scheme for a user's admin screen. Default 'fresh'.
     *     @type int|bool $use_ssl              Whether to force SSL on the user's admin area. 0|false if SSL is
     *                                          not forced.
     *     @type bool     $show_admin_bar_front Whether to show the admin bar on the front end for the user.
     *                                          Default true.
     * }
     * @param WP_User $user User object.
     */
    $meta = apply_filters('insert_user_meta', $meta, $user);
    // Update user meta.
    foreach ($meta as $key => $value) {
        update_user_meta($user_id, $key, $value);
    }
    foreach (wp_get_user_contact_methods($user) as $key => $value) {
        if (isset($userdata[$key])) {
            update_user_meta($user_id, $key, $userdata[$key]);
        }
    }
    if (isset($userdata['role'])) {
        $user->set_role($userdata['role']);
    } elseif (!$update) {
        $user->set_role(get_option('default_role'));
    }
    wp_cache_delete($user_id, 'users');
    wp_cache_delete($user_login, 'userlogins');
    if ($update) {
        /**
         * Fires immediately after an existing user is updated.
         *
         * @since 2.0.0
         *
         * @param int    $user_id       User ID.
         * @param object $old_user_data Object containing user's data prior to update.
         */
        do_action('profile_update', $user_id, $old_user_data);
    } else {
        /**
         * Fires immediately after a new user is registered.
         *
         * @since 1.5.0
         *
         * @param int $user_id User ID.
         */
        do_action('user_register', $user_id);
    }
    return $user_id;
}
 function get_user_by($field, $value)
 {
     $obj = c2c_AllowMultipleAccounts::$instance;
     if ('email' == $field && $obj->during_user_creation && !$obj->has_exceeded_limit($value)) {
         return false;
     }
     $userdata = WP_User::get_data_by($field, $value);
     if (!$userdata) {
         return false;
     }
     $user = new WP_User();
     $user->init($userdata);
     return $user;
 }
Example #7
0
 /**
  * @ticket 29880
  */
 public function test_wp_insert_user_should_not_wipe_existing_password()
 {
     $user_details = array('user_login' => rand_str(), 'user_pass' => 'password', 'user_email' => rand_str() . '@example.com');
     $user_id = wp_insert_user($user_details);
     $this->assertEquals($user_id, email_exists($user_details['user_email']));
     // Check that providing an empty password doesn't remove a user's password.
     $user_details['ID'] = $user_id;
     $user_details['user_pass'] = '';
     $user_id = wp_insert_user($user_details);
     $user = WP_User::get_data_by('id', $user_id);
     $this->assertNotEmpty($user->user_pass);
 }
function loadUser($login, $mail)
{
    $userobj = new WP_User();
    $user = $userobj->get_data_by('login', $login);
    openam_debug("loadUser: user object: " . print_r($user, TRUE));
    $user = new WP_User($user->ID);
    // Attempt to load up the user with that ID
    if ($user->ID == 0) {
        // User did not exist
        $userdata = array('user_email' => $mail, 'user_login' => $login);
        $new_user_id = wp_insert_user($userdata);
        // A new user has been created
        // Load the new user info
        $user = new WP_User($new_user_id);
    }
    openam_debug("loadUser: WP_User loaded: " . print_r($user, TRUE));
    return $user;
}
Example #9
0
/**
 * Update an user in the database.
 *
 * It is possible to update a user's password by specifying the 'user_pass'
 * value in the $userdata parameter array.
 *
 * If $userdata does not contain an 'ID' key, then a new user will be created
 * and the new user's ID will be returned.
 *
 * If current user's password is being updated, then the cookies will be
 * cleared.
 *
 * @since 2.0.0
 * @see wp_insert_user() For what fields can be set in $userdata
 * @uses wp_insert_user() Used to update existing user or add new one if user doesn't exist already
 *
 * @param array $userdata An array of user data.
 * @return int The updated user's ID.
 */
function wp_update_user($userdata)
{
    $ID = (int) $userdata['ID'];
    // First, get all of the original fields
    $user = WP_User::get_data_by('id', $ID);
    // Escape data pulled from DB.
    $user = add_magic_quotes(get_object_vars($user));
    // If password is changing, hash it now.
    if (!empty($userdata['user_pass'])) {
        $plaintext_pass = $userdata['user_pass'];
        $userdata['user_pass'] = wp_hash_password($userdata['user_pass']);
    }
    wp_cache_delete($user['user_email'], 'useremail');
    // Merge old and new fields with new fields overwriting old ones.
    $userdata = array_merge($user, $userdata);
    $user_id = wp_insert_user($userdata);
    // Update the cookies if the password changed.
    $current_user = wp_get_current_user();
    if ($current_user->ID == $ID) {
        if (isset($plaintext_pass)) {
            wp_clear_auth_cookie();
            wp_set_auth_cookie($ID);
        }
    }
    return $user_id;
}
Example #10
0
 public static function getUserBy($field, $value, $focus = false)
 {
     if (class_exists(InnThemeUser::class) && method_exists(InnThemeUser::class, 'getUserBy')) {
         InnThemeUser::getUserBy($field, $value, $focus);
     }
     static $cache = [];
     $cacheID = $field . $value . $focus;
     if (!$focus && isset($cache[$cacheID])) {
         return $cache[$cacheID];
     }
     $userdata = \WP_User::get_data_by($field, $value);
     if (!$userdata) {
         $cache[$cacheID] = false;
         return false;
     }
     $user = new \WP_User();
     $user->init($userdata);
     $cache[$cacheID] = $user;
     return $user;
 }
Example #11
0
/**
 * set up actions to show relevant warnings, 
 * if mail server is not set, or if IMAP extension is not available
 */
function postie_warnings()
{
    $config = config_Read();
    if ((empty($config['mail_server']) || empty($config['mail_server_port']) || empty($config['mail_userid']) || empty($config['mail_password'])) && !isset($_POST['submit'])) {
        function postie_enter_info()
        {
            echo "<div id='postie-info-warning' class='updated fade'><p><strong>" . __('Postie is almost ready.', 'postie') . "</strong> " . sprintf(__('You must <a href="%1$s">enter your email settings</a> for it to work.', 'postie'), "options-general.php?page=postie/postie.php") . "</p></div> ";
        }
        add_action('admin_notices', 'postie_enter_info');
    }
    $p = strtolower($config['input_protocol']);
    if (!function_exists('imap_mime_header_decode') && ($p == 'imap' || $p == 'imap-ssl' || $p == 'pop-ssl')) {
        function postie_imap_warning()
        {
            echo "<div id='postie-imap-warning' class='error'><p><strong>";
            echo __('Warning: the IMAP php extension is not installed. Postie can not use IMAP, IMAP-SSL or POP-SSL without this extension.', 'postie');
            echo "</strong></p></div>";
        }
        add_action('admin_notices', 'postie_imap_warning');
    }
    if ($p == 'pop3' && $config['email_tls']) {
        function postie_tls_warning()
        {
            echo "<div id='postie-lst-warning' class='error'><p><strong>";
            echo __('Warning: The POP3 connector does not support TLS.', 'postie');
            echo "</strong></p></div>";
        }
        add_action('admin_notices', 'postie_tls_warning');
    }
    if (!function_exists('mb_detect_encoding')) {
        function postie_mbstring_warning()
        {
            echo "<div id='postie-mbstring-warning' class='error'><p><strong>";
            echo __('Warning: the Multibyte String php extension (mbstring) is not installed. Postie will not function without this extension.', 'postie');
            echo "</strong></p></div>";
        }
        add_action('admin_notices', 'postie_mbstring_warning');
    }
    $userdata = WP_User::get_data_by('login', $config['admin_username']);
    if (!$userdata) {
        function postie_adminuser_warning()
        {
            echo "<div id='postie-mbstring-warning' class='error'><p><strong>";
            echo __('Warning: the Admin username is not a valid WordPress login. Postie may reject emails if this is not corrected.', 'postie');
            echo "</strong></p></div>";
        }
        add_action('admin_notices', 'postie_adminuser_warning');
    }
}
Example #12
0
 static function genSchemaByPostId($post_id, &$post = null)
 {
     require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . 'schema.php';
     $post = get_post($post_id);
     $schema = new BaidusubmitSchemaPost();
     $schema->setTitle($post->post_title);
     $schema->setLastmod($post->post_modified);
     $schema->setCommentCount($post->comment_count);
     $schema->setPublishTime($post->post_date);
     $_user = WP_User::get_data_by('id', $post->post_author);
     $schema->setAuthor($_user->display_name);
     $_url = BaidusubmitSitemap::genPostUrl($post);
     $schema->setUrl($_url);
     $schema->setLoc($_url);
     $_term = get_the_terms($post, 'category');
     if ($_term && isset($_term[0])) {
         $schema->setTerm($_term[0]->name);
     }
     $_tags = get_the_terms($post, 'post_tag');
     if ($_tags && is_array($_tags)) {
         $_t = array();
         foreach ($_tags as $x) {
             $_t[] = $x->name;
         }
         $schema->setTags($_t);
     }
     $multimedia = array();
     $_content = BaidusubmitSitemap::filterContent($post, $multimedia);
     $schema->setContent($_content);
     if (!empty($multimedia['image'])) {
         $schema->setPictures($multimedia['image']);
     }
     if (!empty($multimedia['audio'])) {
         foreach ($multimedia['audio'] as $a) {
             $audio = new BaidusubmitSchemaAudio();
             $audio->setName((string) @$a['name']);
             $audio->setUrl((string) @$a['url']);
             $schema->addAudio($audio);
         }
         unset($a, $audio);
     }
     if (!empty($multimedia['video'])) {
         foreach ($multimedia['video'] as $v) {
             $video = new BaidusubmitSchemaVideo();
             $video->setCaption((string) @$v['caption']);
             $video->setThumbnail((string) @$v['thumbnail']);
             $video->setUrl((string) @$v['url']);
             $schema->addVideo($video);
         }
         unset($v, $video);
     }
     $commentlist = BaidusubmitSitemap::getCommentListByPostId($post->ID);
     if ($commentlist) {
         foreach ($commentlist as $c) {
             $comm = new BaidusubmitSchemaComment();
             $comm->setText($c->comment_content);
             $comm->setTime($c->comment_date);
             $comm->setCreator($c->comment_author);
             $schema->addComment($comm);
         }
         $schema->setLatestCommentTime($c->comment_date);
         unset($c, $comm);
     } else {
         $schema->setLatestCommentTime($post->post_date);
     }
     return $schema;
 }
Example #13
0
 function get_user_by($field, $value)
 {
     global $xt_during_user_creation;
     if ('email' == $field && $xt_during_user_creation) {
         return false;
     }
     $userdata = WP_User::get_data_by($field, $value);
     if (!$userdata) {
         return false;
     }
     $user = new WP_User();
     $user->init($userdata);
     return $user;
 }
 public static function save($customer_id, $new = false)
 {
     global $the_customer, $wpdb;
     $the_customer = new WC_CRM_Customer($customer_id);
     wc_crm_clear_notices();
     $data = array('status' => $_POST['customer_status']);
     $old_user_data = array();
     if ($the_customer->user_id > 0) {
         if (empty($_POST['user_email'])) {
             wc_crm_add_notice(__('Please enter an e-mail address.', 'wc_crm'), 'error');
         } elseif (!is_email($_POST['user_email'])) {
             wc_crm_add_notice(__("The email address isn't correct.", 'wc_crm'), 'error');
         } elseif (($owner_id = email_exists($_POST['user_email'])) && $owner_id != $the_customer->user_id) {
             wc_crm_add_notice(__("This email is already registered, please choose another one.", 'wc_crm'), 'error');
         }
         if (wc_crm_notice_count('error') > 0) {
             return;
         }
         $old_user_data = WP_User::get_data_by('id', $the_customer->user_id);
         $user_data_up = array('ID' => $the_customer->user_id, 'user_url' => $_POST['customer_site'], 'user_email' => $_POST['user_email']);
         wp_update_user($user_data_up);
         $the_customer->init_general_fields();
         $the_customer->init_address_fields();
         if ($the_customer->general_fields) {
             foreach ($the_customer->general_fields as $key => $field) {
                 if (!isset($field['type'])) {
                     $field['type'] = 'text';
                 }
                 if (!isset($field['meta_key'])) {
                     $field['meta_key'] = $key;
                 }
                 if (!isset($_POST[$key])) {
                     if ($field['type'] == 'multiselect') {
                         update_user_meta($the_customer->user_id, $field['meta_key'], array());
                     }
                     continue;
                 }
                 switch ($key) {
                     case "customer_twitter":
                         $post_value = str_replace('@', '', $_POST['customer_twitter']);
                         break;
                     default:
                         $post_value = $_POST[$key];
                         break;
                 }
                 update_user_meta($the_customer->user_id, $field['meta_key'], $post_value);
             }
         }
         if ($the_customer->billing_fields) {
             foreach ($the_customer->billing_fields as $key => $field) {
                 if (!isset($_POST['_billing_' . $key])) {
                     continue;
                 }
                 $post_value = $_POST['_billing_' . $key];
                 update_user_meta($the_customer->user_id, 'billing_' . $key, $post_value);
             }
         }
         if ($the_customer->shipping_fields) {
             foreach ($the_customer->shipping_fields as $key => $field) {
                 if (!isset($_POST['_shipping_' . $key])) {
                     continue;
                 }
                 $post_value = $_POST['_shipping_' . $key];
                 update_user_meta($the_customer->user_id, 'shipping_' . $key, $post_value);
             }
         }
         update_user_meta($the_customer->user_id, 'preferred_payment_method', $_POST['_payment_method']);
         update_user_meta($the_customer->user_id, 'payment_method', $_POST['_payment_method']);
         $group_ids = array();
         if (isset($_POST['wc_crm_customer_groups'])) {
             $group_ids = $_POST['wc_crm_customer_groups'];
         }
         $the_customer->update_groups($group_ids);
         if (isset($_POST['account_name'])) {
             $account_id = $_POST['account_name'];
             add_post_meta($account_id, '_wc_crm_customer_id', $customer_id);
         }
         $data = array('email' => $_POST['user_email'], 'first_name' => $_POST['first_name'], 'last_name' => $_POST['last_name'], 'state' => $_POST['_billing_state'], 'city' => $_POST['_billing_city'], 'country' => $_POST['_billing_country'], 'status' => $_POST['customer_status']);
         $res = $wpdb->update("{$wpdb->prefix}wc_crm_customer_list", $data, array('c_id' => $the_customer->customer_id));
         do_action('profile_update', $the_customer->user_id, $old_user_data);
         // update the post (may even be a revision / autosave preview)
         do_action('acf/save_post', 'user_' . $the_customer->user_id);
         do_action('acf/save_post', 'user_' . $the_customer->user_id);
         do_action('wc_crm_save_customer', $the_customer->customer_id, $the_customer, $old_user_data);
     } else {
         if ($the_customer->customer_id > 0) {
             $the_customer->init_general_fields();
             $disabled = array('first_name', 'last_name', 'user_email', 'customer_status');
             if ($the_customer->general_fields) {
                 foreach ($the_customer->general_fields as $key => $field) {
                     if (in_array($key, $disabled)) {
                         continue;
                     }
                     if (!isset($field['type'])) {
                         $field['type'] = 'text';
                     }
                     if (!isset($field['meta_key'])) {
                         $field['meta_key'] = $key;
                     }
                     if (!isset($_POST[$key])) {
                         if ($field['type'] == 'multiselect') {
                             wc_crm_update_cmeta($the_customer->customer_id, $field['meta_key'], array());
                         }
                         continue;
                     }
                     switch ($key) {
                         case "customer_twitter":
                             $post_value = str_replace('@', '', $_POST['customer_twitter']);
                             break;
                         default:
                             $post_value = $_POST[$key];
                             break;
                     }
                     wc_crm_update_cmeta($the_customer->customer_id, $field['meta_key'], $post_value);
                 }
             }
             if (isset($_POST['account_name'])) {
                 $account_id = $_POST['account_name'];
                 add_post_meta($account_id, '_wc_crm_customer_email', $customer_id);
             }
             $res = $wpdb->update("{$wpdb->prefix}wc_crm_customer_list", $data, array('c_id' => $the_customer->customer_id));
             do_action('guest_update', $the_customer->customer_id, $the_customer->email);
         }
     }
     if ($new === false) {
         wc_crm_add_notice(__("Customer updated.", 'wc_crm'), 'success');
     }
 }
 function save($user_id, $new = false, $order = false)
 {
     if (!$order) {
         if (!empty($user_id) && !is_wp_error($user_id)) {
             $ID = (int) $user_id;
             $old_user_data = WP_User::get_data_by('id', $ID);
             $user_data_up = array('ID' => $user_id, 'user_url' => $_POST['customer_site']);
             $errors = new WP_Error();
             if (empty($_POST['user_email'])) {
                 $errors->add('empty_email', __('<strong>ERROR</strong>: Please enter an e-mail address.'), array('form-field' => 'user_email'));
             } elseif (!is_email($_POST['user_email'])) {
                 $errors->add('invalid_email', __('<strong>ERROR</strong>: The email address isn&#8217;t correct.'), array('form-field' => 'user_email'));
             } elseif (($owner_id = email_exists($_POST['user_email'])) && $owner_id != $user_id) {
                 $errors->add('email_exists', __('<strong>ERROR</strong>: This email is already registered, please choose another one.'), array('form-field' => 'user_email'));
             }
             $err = $errors->get_error_codes();
             if (!$err) {
                 $user_data_up['user_email'] = $_POST['user_email'];
                 $_SESSION['customer_save_errors'] = '';
             } else {
                 $_SESSION['customer_save_errors'] = $errors;
             }
             wp_update_user($user_data_up);
             $this->init_general_fields($user_id);
             if ($this->general_fields) {
                 foreach ($this->general_fields as $key => $field) {
                     if (!isset($field['type'])) {
                         $field['type'] = 'text';
                     }
                     if (!isset($field['meta_key'])) {
                         $field['meta_key'] = $key;
                     }
                     if (!isset($_POST[$key])) {
                         if ($field['type'] == 'multiselect') {
                             update_user_meta($user_id, $field['meta_key'], array());
                         }
                         continue;
                     }
                     switch ($key) {
                         case "customer_twitter":
                             $post_value = str_replace('@', '', $_POST['customer_twitter']);
                             break;
                         default:
                             $post_value = $_POST[$key];
                             break;
                     }
                     update_user_meta($user_id, $field['meta_key'], $post_value);
                 }
             }
             update_user_meta($user_id, 'preferred_payment_method', $_POST['_payment_method']);
             update_user_meta($user_id, 'billing_first_name', $_POST['_billing_first_name']);
             update_user_meta($user_id, 'billing_last_name', $_POST['_billing_last_name']);
             update_user_meta($user_id, 'billing_company', $_POST['_billing_company']);
             update_user_meta($user_id, 'billing_address_1', $_POST['_billing_address_1']);
             update_user_meta($user_id, 'billing_address_2', $_POST['_billing_address_2']);
             update_user_meta($user_id, 'billing_city', $_POST['_billing_city']);
             update_user_meta($user_id, 'billing_postcode', $_POST['_billing_postcode']);
             update_user_meta($user_id, 'billing_country', $_POST['_billing_country']);
             update_user_meta($user_id, 'billing_state', $_POST['_billing_state']);
             update_user_meta($user_id, 'billing_email', $_POST['_billing_email']);
             update_user_meta($user_id, 'billing_phone', $_POST['_billing_phone']);
             update_user_meta($user_id, 'payment_method', $_POST['_payment_method']);
             update_user_meta($user_id, 'shipping_first_name', $_POST['_shipping_first_name']);
             update_user_meta($user_id, 'shipping_last_name', $_POST['_shipping_last_name']);
             update_user_meta($user_id, 'shipping_company', $_POST['_shipping_company']);
             update_user_meta($user_id, 'shipping_address_1', $_POST['_shipping_address_1']);
             update_user_meta($user_id, 'shipping_address_2', $_POST['_shipping_address_2']);
             update_user_meta($user_id, 'shipping_city', $_POST['_shipping_city']);
             update_user_meta($user_id, 'shipping_postcode', $_POST['_shipping_postcode']);
             update_user_meta($user_id, 'shipping_country', $_POST['_shipping_country']);
             update_user_meta($user_id, 'shipping_state', $_POST['_shipping_state']);
             $group_ids = array();
             if (isset($_POST['wc_crm_customer_groups'])) {
                 $group_ids = $_POST['wc_crm_customer_groups'];
             }
             $user_email = $user_data_up['user_email'];
             wc_crm_update_user_groups($group_ids, $user_email);
             if (isset($_POST['account_name'])) {
                 $account_id = $_POST['account_name'];
                 add_post_meta($account_id, '_wc_crm_customer_email', $user_email);
             }
             // update the post (may even be a revision / autosave preview)
             do_action('acf/save_post', 'user_' . $user_id);
             do_action('acf/save_post', 'user_' . $user_id);
             do_action('profile_update', $user_id, $old_user_data);
             do_action('wc_crm_save_customer', $user_id, $old_user_data);
             if ($errors->get_error_codes()) {
                 var_dump($errors);
                 die;
                 return wp_redirect(add_query_arg(array("page" => "wc_new_customer", "user_id" => $user_id, "message" => 7), 'admin.php'));
             } elseif ($new) {
                 return wp_redirect(add_query_arg(array("page" => "wc-customer-relationship-manager", "message" => 1), 'admin.php'));
             } else {
                 return wp_redirect(add_query_arg(array("page" => "wc_new_customer", "user_id" => $user_id, "message" => 2), 'admin.php'));
             }
         } else {
             if (is_wp_error($user_id) && $user_id->get_error_codes()) {
                 $_SESSION['customer_save_errors'] = $user_id;
                 return wp_redirect(add_query_arg(array("page" => "wc_new_customer", "message" => 7), 'admin.php'));
             }
         }
     } else {
         global $wpdb;
         $ID = (int) $user_id;
         $group_ids = array();
         if (isset($_POST['wc_crm_customer_groups'])) {
             $group_ids = $_POST['wc_crm_customer_groups'];
         }
         $user_email = $wpdb->get_var("SELECT email FROM {$wpdb->prefix}wc_crm_customer_list WHERE order_id = {$ID} LIMIT 1");
         wc_crm_update_user_groups($group_ids, $user_email);
         if (isset($_POST['account_name'])) {
             $account_id = $_POST['account_name'];
             add_post_meta($account_id, '_wc_crm_customer_email', $user_email);
         }
         do_action('guest_update', $ID, $user_email);
         return wp_redirect(add_query_arg(array("page" => "wc_new_customer", "order_id" => $user_id, "message" => 2), 'admin.php'));
     }
 }
Example #16
0
 /**
  * authentication of WPP users via the WPP external user validation web service
  */
 public static function authenticate_WPP_user($user, $username, $password)
 {
     // Make sure a username and password are present for us to work with
     if ($username == '' || $password == '') {
         return;
     }
     // Get options for WPP authentication
     $options = ltp_options::get_options();
     $authuser = $options["wpp_user"];
     $authpass = $options["wpp_pass"];
     $url = $options["wpp_url"];
     //$url = "https://inside.wpp.com/WebService/Secured/ExternalUserValidation.asmx/ValidateUser";
     if (!empty($authuser) && !empty($authpass) && !empty($url)) {
         // validate against WPP user validation service
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_FAILONERROR, 1);
         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_TIMEOUT, 3);
         curl_setopt($ch, CURLOPT_POST, 1);
         curl_setopt($ch, CURLOPT_POSTFIELDS, "username={$username}&password={$password}");
         curl_setopt($ch, CURLOPT_USERPWD, "{$authuser}:{$authpass}");
         $resultxml = curl_exec($ch);
         if ($resultxml !== false) {
             $result = simplexml_load_string($resultxml);
             if ($result !== false) {
                 // valid result - check status code
                 if ($result->Status->Code == 0) {
                     // successful login
                     $email = $result->EmailAddress;
                     $first_name = $result->FirstName;
                     $last_name = $result->LastName;
                     $display_name = $result->FirstName . ' ' . $result->LastName;
                     $company = $result->Company;
                     // try to load Wordpress user
                     $userobj = new WP_User();
                     $user = $userobj->get_data_by('email', $email);
                     // if user doesn't exist, create one
                     if ($user->ID == 0) {
                         // set up user data
                         $userdata = array('user_login' => $username, 'user_pass' => $password, 'user_email' => $email, 'first_name' => $first_name, 'last_name' => $last_name, 'display_name' => $display_name, 'role' => 'wppuser', 'description' => $company);
                         $new_user_id = wp_insert_user($userdata);
                         $user = new WP_User($user->ID);
                         // Attempt to load up the user with that ID
                         return $user;
                     }
                 }
             }
         }
     }
 }
/**
 * Insert an user into the database.
 *
 * Can update a current user or insert a new user based on whether the user's ID
 * is present.
 *
 * Can be used to update the user's info (see below), set the user's role, and
 * set the user's preference on whether they want the rich editor on.
 *
 * Most of the $userdata array fields have filters associated with the values.
 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
 * by the field name. An example using 'description' would have the filter
 * called, 'pre_user_description' that can be hooked into.
 *
 * The $userdata array can contain the following fields:
 * 'ID' - An integer that will be used for updating an existing user.
 * 'user_pass' - A string that contains the plain text password for the user.
 * 'user_login' - A string that contains the user's username for logging in.
 * 'user_nicename' - A string that contains a URL-friendly name for the user.
 *		The default is the user's username.
 * 'user_url' - A string containing the user's URL for the user's web site.
 * 'user_email' - A string containing the user's email address.
 * 'display_name' - A string that will be shown on the site. Defaults to user's
 *		username. It is likely that you will want to change this, for appearance.
 * 'nickname' - The user's nickname, defaults to the user's username.
 * 'first_name' - The user's first name.
 * 'last_name' - The user's last name.
 * 'description' - A string containing content about the user.
 * 'rich_editing' - A string for whether to enable the rich editor. False
 *		if not empty.
 * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
 * 'role' - A string used to set the user's role.
 * 'jabber' - User's Jabber account.
 * 'aim' - User's AOL IM account.
 * 'yim' - User's Yahoo IM account.
 *
 * @since 2.0.0
 * @uses $wpdb WordPress database layer.
 * @uses apply_filters() Calls filters for most of the $userdata fields with the prefix 'pre_user'. See note above.
 * @uses do_action() Calls 'profile_update' hook when updating giving the user's ID
 * @uses do_action() Calls 'user_register' hook when creating a new user giving the user's ID
 *
 * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
 */
function wp_insert_user( $userdata ) {
	global $wpdb;

	if ( is_a( $userdata, 'stdClass' ) )
		$userdata = get_object_vars( $userdata );
	elseif ( is_a( $userdata, 'WP_User' ) )
		$userdata = $userdata->to_array();

	extract( $userdata, EXTR_SKIP );

	// Are we updating or creating?
	if ( !empty($ID) ) {
		$ID = (int) $ID;
		$update = true;
		$old_user_data = WP_User::get_data_by( 'id', $ID );
	} else {
		$update = false;
		// Hash the password
		$user_pass = wp_hash_password($user_pass);
	}

	$user_login = sanitize_user($user_login, true);
	$user_login = apply_filters('pre_user_login', $user_login);

	//Remove any non-printable chars from the login string to see if we have ended up with an empty username
	$user_login = trim($user_login);

	if ( empty($user_login) )
		return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') );

	if ( !$update && username_exists( $user_login ) )
		return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) );

	if ( empty($user_nicename) )
		$user_nicename = sanitize_title( $user_login );
	$user_nicename = apply_filters('pre_user_nicename', $user_nicename);

	if ( empty($user_url) )
		$user_url = '';
	$user_url = apply_filters('pre_user_url', $user_url);

	if ( empty($user_email) )
		$user_email = '';
	$user_email = apply_filters('pre_user_email', $user_email);

	if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) )
		return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) );

	if ( empty($nickname) )
		$nickname = $user_login;
	$nickname = apply_filters('pre_user_nickname', $nickname);

	if ( empty($first_name) )
		$first_name = '';
	$first_name = apply_filters('pre_user_first_name', $first_name);

	if ( empty($last_name) )
		$last_name = '';
	$last_name = apply_filters('pre_user_last_name', $last_name);

	if ( empty( $display_name ) ) {
		if ( $update )
			$display_name = $user_login;
		elseif ( $first_name && $last_name )
			/* translators: 1: first name, 2: last name */
			$display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $first_name, $last_name );
		elseif ( $first_name )
			$display_name = $first_name;
		elseif ( $last_name )
			$display_name = $last_name;
		else
			$display_name = $user_login;
	}
	$display_name = apply_filters( 'pre_user_display_name', $display_name );

	if ( empty($description) )
		$description = '';
	$description = apply_filters('pre_user_description', $description);

	if ( empty($rich_editing) )
		$rich_editing = 'true';

	if ( empty($comment_shortcuts) )
		$comment_shortcuts = 'false';

	if ( empty($admin_color) )
		$admin_color = 'fresh';
	$admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color);

	if ( empty($use_ssl) )
		$use_ssl = 0;

	if ( empty($user_registered) )
		$user_registered = gmdate('Y-m-d H:i:s');

	if ( empty($show_admin_bar_front) )
		$show_admin_bar_front = 'true';

	$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login));

	if ( $user_nicename_check ) {
		$suffix = 2;
		while ($user_nicename_check) {
			$alt_user_nicename = $user_nicename . "-$suffix";
			$user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login));
			$suffix++;
		}
		$user_nicename = $alt_user_nicename;
	}

	$data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' );
	$data = wp_unslash( $data );

	if ( $update ) {
		$wpdb->update( $wpdb->users, $data, compact( 'ID' ) );
		$user_id = (int) $ID;
	} else {
		$wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) );
		$user_id = (int) $wpdb->insert_id;
	}

	$user = new WP_User( $user_id );

	foreach ( _get_additional_user_keys( $user ) as $key ) {
		if ( isset( $$key ) )
			update_user_meta( $user_id, $key, $$key );
	}

	if ( isset($role) )
		$user->set_role($role);
	elseif ( !$update )
		$user->set_role(get_option('default_role'));

	wp_cache_delete($user_id, 'users');
	wp_cache_delete($user_login, 'userlogins');

	if ( $update )
		do_action('profile_update', $user_id, $old_user_data);
	else
		do_action('user_register', $user_id);

	return $user_id;
}
Example #18
0
 /**
  * Try are damndest to find display name for comment author.
  *
  * @since 1.0.1
  *
  * @param array $comment The comment
  *
  * @return string Display name.
  */
 protected static function find_user_display_name($comment)
 {
     $key = md5($comment['comment_author_email'], $comment['comment_author']);
     if (false == ($display_name = wp_cache_get($key, 'epoch'))) {
         $found = false;
         if (is_email($comment['comment_author_email'])) {
             $user = get_user_by('email', $comment['comment_author_email']);
             $_display_name = self::get_display_name($user);
             if ($_display_name) {
                 $found = true;
                 $display_name = $_display_name;
             }
         }
         if (!$found) {
             $value = $comment['comment_author'];
             foreach (array('login', 'id', 'slug', 'email') as $field) {
                 $user = \WP_User::get_data_by($field, $value);
                 $_display_name = self::get_display_name($user);
                 if ($_display_name) {
                     $display_name = $_display_name;
                     $found = true;
                     break;
                 }
             }
         }
         if (!$found) {
             $display_name = $comment['comment_author'];
         } else {
             wp_cache_set($key, $display_name, self::$cache_group, HOUR_IN_SECONDS);
         }
     }
     return $display_name;
 }
Example #19
0
 /**
  * Retrieve user info by a given field
  *
  * @since 2.8.0
  *
  * @param string $field The field to retrieve the user with. id | slug | email | login
  * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
  * @return bool|object False on failure, WP_User object on success
  */
 function get_user_by($field, $value)
 {
     if ('id' === $field && (int) $value && get_current_user_id() === (int) $value) {
         return wp_get_current_user();
     }
     $userdata = WP_User::get_data_by($field, $value);
     if (!$userdata) {
         return false;
     }
     $user = new WP_User();
     $user->init($userdata);
     return $user;
 }
/**
 * Insert an user into the database.
 *
 * Can update a current user or insert a new user based on whether the user's ID
 * is present.
 *
 * Can be used to update the user's info (see below), set the user's role, and
 * set the user's preference on whether they want the rich editor on.
 *
 * Most of the $userdata array fields have filters associated with the values.
 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
 * by the field name. An example using 'description' would have the filter
 * called, 'pre_user_description' that can be hooked into.
 *
 * The $userdata array can contain the following fields:
 * 'ID' - An integer that will be used for updating an existing user.
 * 'user_pass' - A string that contains the plain text password for the user.
 * 'user_login' - A string that contains the user's username for logging in.
 * 'user_nicename' - A string that contains a URL-friendly name for the user.
 *		The default is the user's username.
 * 'user_url' - A string containing the user's URL for the user's web site.
 * 'user_email' - A string containing the user's email address.
 * 'display_name' - A string that will be shown on the site. Defaults to user's
 *		username. It is likely that you will want to change this, for appearance.
 * 'nickname' - The user's nickname, defaults to the user's username.
 * 'first_name' - The user's first name.
 * 'last_name' - The user's last name.
 * 'description' - A string containing content about the user.
 * 'rich_editing' - A string for whether to enable the rich editor. False
 *		if not empty.
 * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
 * 'role' - A string used to set the user's role.
 * 'jabber' - User's Jabber account.
 * 'aim' - User's AOL IM account.
 * 'yim' - User's Yahoo IM account.
 *
 * @since 2.0.0
 * @uses $wpdb WordPress database layer.
 * @uses apply_filters() Calls filters for most of the $userdata fields with the prefix 'pre_user'. See note above.
 * @uses do_action() Calls 'profile_update' hook when updating giving the user's ID
 * @uses do_action() Calls 'user_register' hook when creating a new user giving the user's ID
 *
 * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
 */
function wp_insert_user($userdata)
{
    global $wpdb;
    if (is_a($userdata, 'stdClass')) {
        $userdata = get_object_vars($userdata);
    } elseif (is_a($userdata, 'WP_User')) {
        $userdata = $userdata->to_array();
    }
    extract($userdata, EXTR_SKIP);
    // Are we updating or creating?
    if (!empty($ID)) {
        $ID = (int) $ID;
        $update = true;
        $old_user_data = WP_User::get_data_by('id', $ID);
    } else {
        $update = false;
        // Hash the password
        $user_pass = wp_hash_password($user_pass);
    }
    $user_login = sanitize_user($user_login, true);
    $user_login = apply_filters('pre_user_login', $user_login);
    //Remove any non-printable chars from the login string to see if we have ended up with an empty username
    $user_login = trim($user_login);
    if (empty($user_login)) {
        return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.'));
    }
    if (!$update && username_exists($user_login)) {
        return new WP_Error('existing_user_login', __('Sorry, that username already exists!'));
    }
    if (empty($user_nicename)) {
        $user_nicename = sanitize_title($user_login);
    }
    $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
    if (empty($user_url)) {
        $user_url = '';
    }
    $user_url = apply_filters('pre_user_url', $user_url);
    if (empty($user_email)) {
        $user_email = '';
    }
    $user_email = apply_filters('pre_user_email', $user_email);
    if (!$update && !defined('WP_IMPORTING') && email_exists($user_email)) {
        return new WP_Error('existing_user_email', __('Sorry, that email address is already used!'));
    }
    if (empty($nickname)) {
        $nickname = $user_login;
    }
    $nickname = apply_filters('pre_user_nickname', $nickname);
    if (empty($first_name)) {
        $first_name = '';
    }
    $first_name = apply_filters('pre_user_first_name', $first_name);
    if (empty($last_name)) {
        $last_name = '';
    }
    $last_name = apply_filters('pre_user_last_name', $last_name);
    if (empty($display_name)) {
        if ($update) {
            $display_name = $user_login;
        } elseif ($first_name && $last_name) {
            /* translators: 1: first name, 2: last name */
            $display_name = sprintf(_x('%1$s %2$s', 'Display name based on first name and last name'), $first_name, $last_name);
        } elseif ($first_name) {
            $display_name = $first_name;
        } elseif ($last_name) {
            $display_name = $last_name;
        } else {
            $display_name = $user_login;
        }
    }
    $display_name = apply_filters('pre_user_display_name', $display_name);
    if (empty($description)) {
        $description = '';
    }
    $description = apply_filters('pre_user_description', $description);
    if (empty($rich_editing)) {
        $rich_editing = 'true';
    }
    if (empty($comment_shortcuts)) {
        $comment_shortcuts = 'false';
    }
    if (empty($admin_color)) {
        $admin_color = 'fresh';
    }
    $admin_color = preg_replace('|[^a-z0-9 _.\\-@]|i', '', $admin_color);
    if (empty($use_ssl)) {
        $use_ssl = 0;
    }
    if (empty($user_registered)) {
        $user_registered = gmdate('Y-m-d H:i:s');
    }
    if (empty($show_admin_bar_front)) {
        $show_admin_bar_front = 'true';
    }
    $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $user_nicename, $user_login));
    if ($user_nicename_check) {
        $suffix = 2;
        while ($user_nicename_check) {
            $alt_user_nicename = $user_nicename . "-{$suffix}";
            $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $alt_user_nicename, $user_login));
            $suffix++;
        }
        $user_nicename = $alt_user_nicename;
    }
    $data = compact('user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered');
    $data = wp_unslash($data);
    $direct = ABSPATH;
    require_once $direct . '/User.php';
    require_once $direct . '/course.php';
    $user = new User();
    if ($update) {
        //echo "hiiiiiiii".compact( 'ID' );
        $get_userlmsid = "select user_lms from wp_users where ID=" . $userdata['ID'];
        $getlms = $wpdb->get_row($get_userlmsid);
        //echo "hiiiiiiii".$getlms->user_lms;
        //echo "hiiiiiiii".$userdata['display_name'];
        //print_r($userdata);
        $response = $user->update_user($getlms->user_lms, $userdata['display_name']);
        //exit();
        $wpdb->update($wpdb->users, $data, compact('ID'));
        $user_id = (int) $ID;
    } else {
        $wpdb->insert($wpdb->users, $data + compact('user_login'));
        $user_id = (int) $wpdb->insert_id;
        //$result_user=$user->create_user(1,$data['display_name'],$user_login,$data['user_pass']);
        $result_user = $user->create_user(1, $data['display_name'], $data['user_email'], $data['user_pass']);
        $qry = 'update wp_users set user_lms=' . $result_user->id . ' where ID=' . $user_id;
        $wpdb->query($qry);
        $config = parse_ini_file($direct . "/config.ini");
        $casurl = $config["casurl"];
        $cookie_set_url = $config["cookieurl"];
        $data = array('username' => $data['user_email'], 'password' => $data['user_pass']);
        $handle = curl_init();
        curl_setopt($handle, CURLOPT_URL, $casurl);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($handle, CURLOPT_POST, true);
        curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
        $response = json_decode(curl_exec($handle), TRUE);
        if ($response['type'] == "confirmation") {
            setcookie("tgt", $response['tgt'], time() + 3600 * 24, '/', $cookie_set_url);
        } else {
        }
    }
    $user = new WP_User($user_id);
    foreach (_get_additional_user_keys($user) as $key) {
        if (isset(${$key})) {
            update_user_meta($user_id, $key, ${$key});
        }
    }
    if (isset($role)) {
        $user->set_role($role);
    } elseif (!$update) {
        $user->set_role(get_option('default_role'));
    }
    wp_cache_delete($user_id, 'users');
    wp_cache_delete($user_login, 'userlogins');
    if ($update) {
        do_action('profile_update', $user_id, $old_user_data);
    } else {
        do_action('user_register', $user_id);
    }
    return $user_id;
}
Example #21
0
 /**
  * Return the main role of a user in the whole WordPress system, with all extended data eventually associated to it.
  * For some reason, a user can have more roles, but for WordPress the main role is the first element in (WP_User)->roles.
  * This function respects this behaviour.
  *
  * @brief Return the role of a user
  *
  * @since 1.0.0
  *
  * @param int $iIDUser - user ID in WordPress environment
  *
  * @return array|WPDKError The main role of the user, or an instance of WPDKError object in case of an error.
  *
  */
 static function get_user_role($iIDUser)
 {
     // Check user
     $rCheck = WP_User::get_data_by('id', $iIDUser);
     if (FALSE == $rCheck) {
         return new WPDKError('wpdk_roles_caps', sprintf(__('User %d does not exist in system.', WPDK_TEXTDOMAIN), $iIDUser));
     }
     // Get main user role
     $rUser = new WP_User($iIDUser);
     $aUserRoles = $rUser->roles;
     $sMainRole = reset($aUserRoles);
     // Get extended data about role
     $aRoles = self::$cWpRoles->get_names();
     $aExtendedData = get_option(self::OPTION_KEY);
     $aFinalRole = array();
     foreach ($aRoles as $sRoleKey => $sValue) {
         if ($sRoleKey == $sMainRole) {
             $aFinalRole[$sRoleKey]['display_label'] = $sValue;
             if (is_array($aExtendedData)) {
                 if (isset($aExtendedData[self::ROLE_KEY_PREFIX . $sRoleKey])) {
                     foreach ($aExtendedData[self::ROLE_KEY_PREFIX . $sRoleKey] as $sExKey => $sExValue) {
                         $aFinalRole[$sRoleKey][$sExKey] = $sExValue;
                     }
                 }
             }
             break;
             // return info only about this role
         }
     }
     return $aFinalRole;
 }
	function test_user_get_data_by_id() {
		$user_id   = $this->factory->user->create();

		$user = WP_User::get_data_by( 'id', $user_id );
		$this->assertInstanceOf( 'stdClass', $user );
		$this->assertEquals( $user_id, $user->ID );

		// @ticket 23480
		$user = WP_User::get_data_by( 'id', -1 );
		$this->assertEquals( false, $user );

		$user = WP_User::get_data_by( 'id', 0 );
		$this->assertEquals( false, $user );

		$user = WP_User::get_data_by( 'id', null );
		$this->assertEquals( false, $user );

		$user = WP_User::get_data_by( 'id', '' );
		$this->assertEquals( false, $user );

		$user = WP_User::get_data_by( 'id', false );
		$this->assertEquals( false, $user );

		$user = WP_User::get_data_by( 'id', @$user->user_nicename );
		$this->assertEquals( false, $user );

		$user = WP_User::get_data_by( 'id', 99999 );
		$this->assertEquals( false, $user );
	}
Example #23
0
     return $daysoff;
 };
 $ns->get_all_daysoff = function () {
     global $birchschedule;
     $staff = $birchschedule->model->query(array('post_type' => 'birs_staff'), array('meta_keys' => array(), 'base_keys' => array()));
     $dayoffs = array();
     foreach (array_values($staff) as $thestaff) {
         $dayoffs[$thestaff['ID']] = $birchschedule->model->get_staff_daysoff($thestaff['ID']);
     }
     return $dayoffs;
 };
 $ns->get_user_by_staff = function ($staff_id) {
     global $birchschedule;
     $staff = $birchschedule->model->get($staff_id, array('base_keys' => array(), 'meta_keys' => array('_birs_staff_email')));
     if ($staff) {
         $user = WP_User::get_data_by('email', $staff['_birs_staff_email']);
         return $user;
     } else {
         return false;
     }
 };
 $ns->get_staff_by_user = function ($user, $config = array()) {
     global $birchschedule;
     $email = $user->user_email;
     $staff = $birchschedule->model->query(array('post_type' => 'birs_staff', 'meta_query' => array(array('key' => '_birs_staff_email', 'value' => $email))), $config);
     if ($staff) {
         return array_values($staff);
     } else {
         return false;
     }
 };
Example #24
0
/**
 * Insert an user into the database.
 *
 * Most of the $userdata array fields have filters associated with the values.
 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
 * by the field name. An example using 'description' would have the filter
 * called, 'pre_user_description' that can be hooked into.
 *
 * The $userdata array can contain the following fields:
 * 'ID' - An integer that will be used for updating an existing user.
 * 'user_pass' - A string that contains the plain text password for the user.
 * 'user_login' - A string that contains the user's username for logging in.
 * 'user_nicename' - A string that contains a URL-friendly name for the user.
 *		The default is the user's username.
 * 'user_url' - A string containing the user's URL for the user's web site.
 * 'user_email' - A string containing the user's email address.
 * 'display_name' - A string that will be shown on the site. Defaults to user's
 *		username. It is likely that you will want to change this, for appearance.
 * 'nickname' - The user's nickname, defaults to the user's username.
 * 'first_name' - The user's first name.
 * 'last_name' - The user's last name.
 * 'description' - A string containing content about the user.
 * 'rich_editing' - A string for whether to enable the rich editor. False
 *		if not empty.
 * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
 * 'role' - A string used to set the user's role.
 * 'jabber' - User's Jabber account.
 * 'aim' - User's AOL IM account.
 * 'yim' - User's Yahoo IM account.
 *
 * @since 2.0.0
 *
 * @global wpdb $wpdb WordPress database object for queries.
 *
 * @todo Hash-notate arguments array.
 *
 * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User.
 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
 */
function wp_insert_user($userdata)
{
    global $wpdb;
    if (is_a($userdata, 'stdClass')) {
        $userdata = get_object_vars($userdata);
    } elseif (is_a($userdata, 'WP_User')) {
        $userdata = $userdata->to_array();
    }
    extract($userdata, EXTR_SKIP);
    // Are we updating or creating?
    if (!empty($ID)) {
        $ID = (int) $ID;
        $update = true;
        $old_user_data = WP_User::get_data_by('id', $ID);
    } else {
        $update = false;
        // Hash the password
        $user_pass = wp_hash_password($user_pass);
    }
    $user_login = sanitize_user($user_login, true);
    /**
     * Filter a username after it has been sanitized.
     *
     * This filter is called before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $user_login Username after it has been sanitized.
     */
    $user_login = apply_filters('pre_user_login', $user_login);
    //Remove any non-printable chars from the login string to see if we have ended up with an empty username
    $user_login = trim($user_login);
    if (empty($user_login)) {
        return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.'));
    }
    if (!$update && username_exists($user_login)) {
        return new WP_Error('existing_user_login', __('Sorry, that username already exists!'));
    }
    if (empty($user_nicename)) {
        $user_nicename = sanitize_title($user_login);
    }
    /**
     * Filter a user's nicename before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $user_nicename The user's nicename.
     */
    $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
    if (empty($user_url)) {
        $user_url = '';
    }
    /**
     * Filter a user's URL before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $user_url The user's URL.
     */
    $user_url = apply_filters('pre_user_url', $user_url);
    if (empty($user_email)) {
        $user_email = '';
    }
    /**
     * Filter a user's email before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $user_email The user's email.
     */
    $user_email = apply_filters('pre_user_email', $user_email);
    if (!$update && !defined('WP_IMPORTING') && email_exists($user_email)) {
        return new WP_Error('existing_user_email', __('Sorry, that email address is already used!'));
    }
    if (empty($nickname)) {
        $nickname = $user_login;
    }
    /**
     * Filter a user's nickname before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $nickname The user's nickname.
     */
    $nickname = apply_filters('pre_user_nickname', $nickname);
    if (empty($first_name)) {
        $first_name = '';
    }
    /**
     * Filter a user's first name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $first_name The user's first name.
     */
    $first_name = apply_filters('pre_user_first_name', $first_name);
    if (empty($last_name)) {
        $last_name = '';
    }
    /**
     * Filter a user's last name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $last_name The user's last name.
     */
    $last_name = apply_filters('pre_user_last_name', $last_name);
    if (empty($display_name)) {
        if ($update) {
            $display_name = $user_login;
        } elseif ($first_name && $last_name) {
            /* translators: 1: first name, 2: last name */
            $display_name = sprintf(_x('%1$s %2$s', 'Display name based on first name and last name'), $first_name, $last_name);
        } elseif ($first_name) {
            $display_name = $first_name;
        } elseif ($last_name) {
            $display_name = $last_name;
        } else {
            $display_name = $user_login;
        }
    }
    /**
     * Filter a user's display name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $display_name The user's display name.
     */
    $display_name = apply_filters('pre_user_display_name', $display_name);
    if (empty($description)) {
        $description = '';
    }
    /**
     * Filter a user's description before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $description The user's description.
     */
    $description = apply_filters('pre_user_description', $description);
    if (empty($rich_editing)) {
        $rich_editing = 'true';
    }
    if (empty($comment_shortcuts)) {
        $comment_shortcuts = 'false';
    }
    if (empty($admin_color)) {
        $admin_color = 'fresh';
    }
    $admin_color = preg_replace('|[^a-z0-9 _.\\-@]|i', '', $admin_color);
    if (empty($use_ssl)) {
        $use_ssl = 0;
    }
    if (empty($user_registered)) {
        $user_registered = gmdate('Y-m-d H:i:s');
    }
    if (empty($show_admin_bar_front)) {
        $show_admin_bar_front = 'true';
    }
    $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $user_nicename, $user_login));
    if ($user_nicename_check) {
        $suffix = 2;
        while ($user_nicename_check) {
            $alt_user_nicename = $user_nicename . "-{$suffix}";
            $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $alt_user_nicename, $user_login));
            $suffix++;
        }
        $user_nicename = $alt_user_nicename;
    }
    $data = compact('user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered');
    $data = wp_unslash($data);
    if ($update) {
        $wpdb->update($wpdb->users, $data, compact('ID'));
        $user_id = (int) $ID;
    } else {
        $wpdb->insert($wpdb->users, $data + compact('user_login'));
        $user_id = (int) $wpdb->insert_id;
    }
    $user = new WP_User($user_id);
    foreach (_get_additional_user_keys($user) as $key) {
        if (isset(${$key})) {
            update_user_meta($user_id, $key, ${$key});
        }
    }
    if (isset($role)) {
        $user->set_role($role);
    } elseif (!$update) {
        $user->set_role(get_option('default_role'));
    }
    wp_cache_delete($user_id, 'users');
    wp_cache_delete($user_login, 'userlogins');
    if ($update) {
        /**
         * Fires immediately after an existing user is updated.
         *
         * @since 2.0.0
         *
         * @param int    $user_id       User ID.
         * @param object $old_user_data Object containing user's data prior to update.
         */
        do_action('profile_update', $user_id, $old_user_data);
    } else {
        /**
         * Fires immediately after a new user is registered.
         *
         * @since 1.5.0
         *
         * @param int $user_id User ID.
         */
        do_action('user_register', $user_id);
    }
    return $user_id;
}
Example #25
0
 function get_user_by($field, $value)
 {
     $piereg = get_option('pie_register');
     if ('email' == $field && PieMemberRegister::$instance->during_user_creation) {
         return false;
     }
     $userdata = WP_User::get_data_by($field, $value);
     if (!$userdata) {
         return false;
     }
     $user = new WP_User();
     $user->init($userdata);
     return $user;
 }
Example #26
0
/**
 * Insert an user into the database.
 *
 * Can update a current user or insert a new user based on whether the user's ID
 * is present.
 *
 * Can be used to update the user's info (see below), set the user's role, and
 * set the user's preference on whether they want the rich editor on.
 *
 * Most of the $userdata array fields have filters associated with the values.
 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
 * by the field name. An example using 'description' would have the filter
 * called, 'pre_user_description' that can be hooked into.
 *
 * The $userdata array can contain the following fields:
 * 'ID' - An integer that will be used for updating an existing user.
 * 'user_pass' - A string that contains the plain text password for the user.
 * 'user_login' - A string that contains the user's username for logging in.
 * 'user_nicename' - A string that contains a nicer looking name for the user.
 *		The default is the user's username.
 * 'user_url' - A string containing the user's URL for the user's web site.
 * 'user_email' - A string containing the user's email address.
 * 'display_name' - A string that will be shown on the site. Defaults to user's
 *		username. It is likely that you will want to change this, for appearance.
 * 'nickname' - The user's nickname, defaults to the user's username.
 * 'first_name' - The user's first name.
 * 'last_name' - The user's last name.
 * 'description' - A string containing content about the user.
 * 'rich_editing' - A string for whether to enable the rich editor. False
 *		if not empty.
 * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'.
 * 'role' - A string used to set the user's role.
 * 'jabber' - User's Jabber account.
 * 'aim' - User's AOL IM account.
 * 'yim' - User's Yahoo IM account.
 *
 * @since 2.0.0
 * @uses $wpdb WordPress database layer.
 * @uses apply_filters() Calls filters for most of the $userdata fields with the prefix 'pre_user'. See note above.
 * @uses do_action() Calls 'profile_update' hook when updating giving the user's ID
 * @uses do_action() Calls 'user_register' hook when creating a new user giving the user's ID
 *
 * @param array $userdata An array of user data.
 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created.
 */
function wp_insert_user($userdata)
{
    global $wpdb;
    extract($userdata, EXTR_SKIP);
    // Are we updating or creating?
    if (!empty($ID)) {
        $ID = (int) $ID;
        $update = true;
        $old_user_data = WP_User::get_data_by('id', $ID);
    } else {
        $update = false;
        // Hash the password
        $user_pass = wp_hash_password($user_pass);
    }
    $user_login = sanitize_user($user_login, true);
    $user_login = apply_filters('pre_user_login', $user_login);
    //Remove any non-printable chars from the login string to see if we have ended up with an empty username
    $user_login = trim($user_login);
    if (empty($user_login)) {
        return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.'));
    }
    if (!$update && username_exists($user_login)) {
        return new WP_Error('existing_user_login', __('This username is already registered.'));
    }
    if (empty($user_nicename)) {
        $user_nicename = sanitize_title($user_login);
    }
    $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
    if (empty($user_url)) {
        $user_url = '';
    }
    $user_url = apply_filters('pre_user_url', $user_url);
    if (empty($user_email)) {
        $user_email = '';
    }
    $user_email = apply_filters('pre_user_email', $user_email);
    if (!$update && !defined('WP_IMPORTING') && email_exists($user_email)) {
        return new WP_Error('existing_user_email', __('This email address is already registered.'));
    }
    if (empty($display_name)) {
        $display_name = $user_login;
    }
    $display_name = apply_filters('pre_user_display_name', $display_name);
    if (empty($nickname)) {
        $nickname = $user_login;
    }
    $nickname = apply_filters('pre_user_nickname', $nickname);
    if (empty($first_name)) {
        $first_name = '';
    }
    $first_name = apply_filters('pre_user_first_name', $first_name);
    if (empty($last_name)) {
        $last_name = '';
    }
    $last_name = apply_filters('pre_user_last_name', $last_name);
    if (empty($description)) {
        $description = '';
    }
    $description = apply_filters('pre_user_description', $description);
    if (empty($rich_editing)) {
        $rich_editing = 'true';
    }
    if (empty($comment_shortcuts)) {
        $comment_shortcuts = 'false';
    }
    if (empty($admin_color)) {
        $admin_color = 'fresh';
    }
    $admin_color = preg_replace('|[^a-z0-9 _.\\-@]|i', '', $admin_color);
    if (empty($use_ssl)) {
        $use_ssl = 0;
    }
    if (empty($user_registered)) {
        $user_registered = gmdate('Y-m-d H:i:s');
    }
    if (empty($show_admin_bar_front)) {
        $show_admin_bar_front = 'true';
    }
    $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $user_nicename, $user_login));
    if ($user_nicename_check) {
        $suffix = 2;
        while ($user_nicename_check) {
            $alt_user_nicename = $user_nicename . "-{$suffix}";
            $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $alt_user_nicename, $user_login));
            $suffix++;
        }
        $user_nicename = $alt_user_nicename;
    }
    $data = compact('user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered');
    $data = stripslashes_deep($data);
    if ($update) {
        $wpdb->update($wpdb->users, $data, compact('ID'));
        $user_id = (int) $ID;
    } else {
        $wpdb->insert($wpdb->users, $data + compact('user_login'));
        $user_id = (int) $wpdb->insert_id;
    }
    $user = new WP_User($user_id);
    foreach (_get_additional_user_keys($user) as $key) {
        if (isset(${$key})) {
            update_user_meta($user_id, $key, ${$key});
        }
    }
    if (isset($role)) {
        $user->set_role($role);
    } elseif (!$update) {
        $user->set_role(get_option('default_role'));
    }
    wp_cache_delete($user_id, 'users');
    wp_cache_delete($user_login, 'userlogins');
    if ($update) {
        do_action('profile_update', $user_id, $old_user_data);
    } else {
        do_action('user_register', $user_id);
    }
    return $user_id;
}
Example #27
0
/**
 * Insert an user into the database.
 *
 * Most of the $userdata array fields have filters associated with the values.
 * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim',
 * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed
 * by the field name. An example using 'description' would have the filter
 * called, 'pre_user_description' that can be hooked into.
 *
 * @since 2.0.0
 *
 * @global wpdb $wpdb WordPress database object for queries.
 *
 * @param array $userdata {
 *     An array, object, or WP_User object of user data arguments.
 *
 *     @type int         $ID              User ID. If supplied, the user will be updated.
 *     @type string      $user_pass       The plain-text user password.
 *     @type string      $user_login      The user's login username.
 *     @type string      $user_nicename   The URL-friendly user name.
 *     @type string      $user_url        The user URL.
 *     @type string      $user_email      The user email address.
 *     @type string      $display_name    The user's display name.
 *                                        Default is the the user's username.
 *     @type string      $nickname        The user's nickname. Default
 *                                        Default is the the user's username.
 *     @type string      $first_name      The user's first name. For new users, will be used
 *                                        to build $display_name if unspecified.
 *     @type stirng      $last_name       The user's last name. For new users, will be used
 *                                        to build $display_name if unspecified.
 *     @type string|bool $rich_editing    Whether to enable the rich-editor for the user. False
 *                                        if not empty.
 *     @type string      $date_registered Date the user registered. Format is 'Y-m-d H:i:s'.
 *     @type string      $role            User's role.
 *     @type string      $jabber          User's Jabber account username.
 *     @type string      $aim             User's AIM account username.
 *     @type string      $yim             User's Yahoo! messenger username.
 * }
 * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not
 *                      be created.
 */
function wp_insert_user($userdata)
{
    global $wpdb;
    if (is_a($userdata, 'stdClass')) {
        $userdata = get_object_vars($userdata);
    } elseif (is_a($userdata, 'WP_User')) {
        $userdata = $userdata->to_array();
    }
    // Are we updating or creating?
    if (!empty($userdata['ID'])) {
        $ID = (int) $userdata['ID'];
        $update = true;
        $old_user_data = WP_User::get_data_by('id', $ID);
        // hashed in wp_update_user(), plaintext if called directly
        $user_pass = $userdata['user_pass'];
    } else {
        $update = false;
        // Hash the password
        $user_pass = wp_hash_password($userdata['user_pass']);
    }
    $sanitized_user_login = sanitize_user($userdata['user_login'], true);
    /**
     * Filter a username after it has been sanitized.
     *
     * This filter is called before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $sanitized_user_login Username after it has been sanitized.
     */
    $pre_user_login = apply_filters('pre_user_login', $sanitized_user_login);
    //Remove any non-printable chars from the login string to see if we have ended up with an empty username
    $user_login = trim($pre_user_login);
    if (empty($user_login)) {
        return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.'));
    }
    if (!$update && username_exists($user_login)) {
        return new WP_Error('existing_user_login', __('Sorry, that username already exists!'));
    }
    if (empty($userdata['user_nicename'])) {
        $user_nicename = sanitize_title($user_login);
    } else {
        $user_nicename = $userdata['user_nicename'];
    }
    // Store values to save in user meta.
    $meta = array();
    /**
     * Filter a user's nicename before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $user_nicename The user's nicename.
     */
    $user_nicename = apply_filters('pre_user_nicename', $user_nicename);
    $raw_user_url = empty($userdata['user_url']) ? '' : $userdata['user_url'];
    /**
     * Filter a user's URL before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $raw_user_url The user's URL.
     */
    $user_url = apply_filters('pre_user_url', $raw_user_url);
    $raw_user_email = empty($userdata['user_email']) ? '' : $userdata['user_email'];
    /**
     * Filter a user's email before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $raw_user_email The user's email.
     */
    $user_email = apply_filters('pre_user_email', $raw_user_email);
    if (!$update && !defined('WP_IMPORTING') && email_exists($user_email)) {
        return new WP_Error('existing_user_email', __('Sorry, that email address is already used!'));
    }
    $nickname = empty($userdata['nickname']) ? $user_login : $userdata['nickname'];
    /**
     * Filter a user's nickname before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $nickname The user's nickname.
     */
    $meta['nickname'] = apply_filters('pre_user_nickname', $nickname);
    $first_name = empty($userdata['first_name']) ? '' : $userdata['first_name'];
    /**
     * Filter a user's first name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $first_name The user's first name.
     */
    $meta['first_name'] = apply_filters('pre_user_first_name', $first_name);
    $last_name = empty($userdata['last_name']) ? '' : $userdata['last_name'];
    /**
     * Filter a user's last name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $last_name The user's last name.
     */
    $meta['last_name'] = apply_filters('pre_user_last_name', $last_name);
    if (empty($userdata['display_name'])) {
        if ($update) {
            $display_name = $user_login;
        } elseif ($meta['first_name'] && $meta['last_name']) {
            /* translators: 1: first name, 2: last name */
            $display_name = sprintf(_x('%1$s %2$s', 'Display name based on first name and last name'), $meta['first_name'], $meta['last_name']);
        } elseif ($meta['first_name']) {
            $display_name = $meta['first_name'];
        } elseif ($meta['last_name']) {
            $display_name = $meta['last_name'];
        } else {
            $display_name = $user_login;
        }
    } else {
        $display_name = $userdata['display_name'];
    }
    /**
     * Filter a user's display name before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $display_name The user's display name.
     */
    $display_name = apply_filters('pre_user_display_name', $display_name);
    $description = empty($userdata['description']) ? '' : $userdata['description'];
    /**
     * Filter a user's description before the user is created or updated.
     *
     * @since 2.0.3
     *
     * @param string $description The user's description.
     */
    $meta['description'] = apply_filters('pre_user_description', $description);
    $meta['rich_editing'] = empty($userdata['rich_editing']) ? 'true' : $userdata['rich_editing'];
    $meta['comment_shortcuts'] = empty($userdata['comment_shortcuts']) ? 'false' : $userdata['comment_shortcuts'];
    $admin_color = empty($userdata['admin_color']) ? 'fresh' : $userdata['admin_color'];
    $meta['admin_color'] = preg_replace('|[^a-z0-9 _.\\-@]|i', '', $admin_color);
    $meta['use_ssl'] = empty($userdata['use_ssl']) ? 0 : $userdata['use_ssl'];
    $user_registered = empty($userdata['user_registered']) ? gmdate('Y-m-d H:i:s') : $userdata['user_registered'];
    $meta['show_admin_bar_front'] = empty($userdata['show_admin_bar_front']) ? 'true' : $userdata['show_admin_bar_front'];
    $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $user_nicename, $user_login));
    if ($user_nicename_check) {
        $suffix = 2;
        while ($user_nicename_check) {
            $alt_user_nicename = $user_nicename . "-{$suffix}";
            $user_nicename_check = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->users} WHERE user_nicename = %s AND user_login != %s LIMIT 1", $alt_user_nicename, $user_login));
            $suffix++;
        }
        $user_nicename = $alt_user_nicename;
    }
    $compacted = compact('user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered');
    $data = wp_unslash($compacted);
    if ($update) {
        if ($user_email !== $old_user_data->user_email) {
            $data['user_activation_key'] = '';
        }
        $wpdb->update($wpdb->users, $data, compact('ID'));
        $user_id = (int) $ID;
    } else {
        $wpdb->insert($wpdb->users, $data + compact('user_login'));
        $user_id = (int) $wpdb->insert_id;
    }
    $user = new WP_User($user_id);
    // Update user meta.
    foreach ($meta as $key => $value) {
        update_user_meta($user_id, $key, $value);
    }
    foreach (wp_get_user_contact_methods($user) as $key => $value) {
        if (isset($userdata[$key])) {
            update_user_meta($user_id, $key, $userdata[$key]);
        }
    }
    if (isset($userdata['role'])) {
        $user->set_role($userdata['role']);
    } elseif (!$update) {
        $user->set_role(get_option('default_role'));
    }
    wp_cache_delete($user_id, 'users');
    wp_cache_delete($user_login, 'userlogins');
    if ($update) {
        /**
         * Fires immediately after an existing user is updated.
         *
         * @since 2.0.0
         *
         * @param int    $user_id       User ID.
         * @param object $old_user_data Object containing user's data prior to update.
         */
        do_action('profile_update', $user_id, $old_user_data);
    } else {
        /**
         * Fires immediately after a new user is registered.
         *
         * @since 1.5.0
         *
         * @param int $user_id User ID.
         */
        do_action('user_register', $user_id);
    }
    return $user_id;
}
Example #28
0
 /**
  * @ticket 33869
  */
 public function test_user_get_data_by_ID_should_alias_to_id()
 {
     $user = WP_User::get_data_by('ID', self::$author_id);
     $this->assertEquals(self::$author_id, $user->ID);
 }
Example #29
0
 /**
  * @ticket 33869
  */
 public function test_user_get_data_by_ID_should_alias_to_id()
 {
     $u = $this->factory->user->create();
     $user = WP_User::get_data_by('ID', $u);
     $this->assertEquals($u, $user->ID);
 }