function ure_is_admin( $user_id = false ) { global $current_user; if ( ! $user_id ) { if (empty($current_user) && function_exists('get_currentuserinfo')) { get_currentuserinfo(); } $user_id = ! empty($current_user) ? $current_user->ID : 0; } if ( ! $user_id ) return false; $user = new WP_User($user_id); $simpleAdmin = ure_has_administrator_role($user_id); if ( is_multisite() ) { $super_admins = get_super_admins(); $superAdmin = is_array( $super_admins ) && in_array( $user->user_login, $super_admins ); } else { $superAdmin = false; } return $simpleAdmin || $superAdmin; }
protected function setUp() { static::$redirect_to = null; $admins = get_super_admins(); $user = get_user_by('login', $admins[0]); if (is_wp_error($user) || !$user) { throw new \Exception('Could not login.'); } wp_set_current_user($user->ID); }
function wphsau_views_users($views) { foreach ($views as $key => $view) { if ('all' == $key || 'administrator' == $key) { $views[$key] = preg_replace_callback('/\\(([^()]*)\\)/', function ($matches) { $super_admins = get_super_admins(); $super_admin_count = count($super_admins); return '(' . (intval($matches[1]) - $super_admin_count) . ')'; }, $view); } } return $views; }
public function dashboard_signups() { global $gMemberNetwork; $query = new \WP_User_Query(array('blog_id' => 0, 'orderby' => 'registered', 'order' => 'DESC', 'number' => 12, 'fields' => array('ID', 'display_name', 'user_email', 'user_registered', 'user_login'))); if (empty($query->results)) { _ex('No User?!', 'Signup Admin Widget', GMEMBER_TEXTDOMAIN); } else { echo '<table class="widefat gmember-dashboard -table-signup"><thead><tr>'; echo '<th>' . _x('On', 'Signup Admin Widget', GMEMBER_TEXTDOMAIN) . '</th>'; echo '<th>' . _x('Name', 'Signup Admin Widget', GMEMBER_TEXTDOMAIN) . '</th>'; echo '<th>' . _x('E-mail', 'Signup Admin Widget', GMEMBER_TEXTDOMAIN) . '</th>'; echo '</tr></thead>'; $last = FALSE; $alt = TRUE; $template = '<tr%1$s>' . '<td class="-month-day" title="%5$s">%4$s</td>' . '<td class="-edit-link"><a title="%8$s" href="%6$s" target="_blank">%2$s</a></td>' . '<td class="-mail-link"><a title="%7$s" href="%7$s" target="_blank">%3$s</a></td>' . '</tr>'; foreach ($query->results as $user) { $registered = strtotime(get_date_from_gmt($user->user_registered)); vprintf($template, array($alt ? ' class="alternate"' : '', esc_html($user->display_name), esc_html(gPluginTextHelper::truncateString($user->user_email, 32)), esc_html($gMemberNetwork->getDate($registered, 'monthday')), esc_attr(human_time_diff($registered) . ' — ' . $gMemberNetwork->getDate($registered)), get_edit_user_link($user->ID), 'mailto:' . esc_attr($user->user_email), $user->user_login)); $alt = !$alt; if (!$last) { $last = $registered; } } echo '</table>'; echo '<table class="gmember-dashboard -table-summary"></tbody>'; echo '<tr><td>'; printf(_x('Last User Registered %s ago', 'Signup Admin Widget', GMEMBER_TEXTDOMAIN), human_time_diff($last)); echo '</td><td>'; if ($spam_users = $gMemberNetwork->get_spam_count()) { printf(_nx('With %s Spam User', 'With %s Spam Users', $spam_users, 'Signup Admin Widget', GMEMBER_TEXTDOMAIN), number_format_i18n($spam_users)); } else { _ex('With No Spam User', 'Signup Admin Widget', GMEMBER_TEXTDOMAIN); } echo '</td></tr><tr><td>'; $super_admins = count(get_super_admins()); printf(_nx('And %s Super Admin', 'And %s Super Admins', $super_admins, 'Signup Admin Widget', GMEMBER_TEXTDOMAIN), number_format_i18n($super_admins)); echo '</td><td>'; $user_count = get_user_count(); printf(_nx('Total of One User', 'Total of %s Users', $user_count, 'Signup Admin Widget', GMEMBER_TEXTDOMAIN), number_format_i18n($user_count)); echo '</td></tr>'; echo '</tbody></table>'; } }
function is_super_admin($user_id = false) { if (!$user_id) { $current_user = wp_get_current_user(); $user_id = !empty($current_user) ? $current_user->id : 0; } if (!$user_id) { return false; } $user = new WP_User($user_id); if (is_multisite()) { $super_admins = get_super_admins(); if (is_array($super_admins) && in_array($user->user_login, $super_admins)) { return true; } } else { if ($user->has_cap('delete_users')) { return true; } } return false; }
/** * Preform upgrade tasks such as deleting and updating options * @since 2.0 */ function code_snippets_upgrader() { /* Get the current plugin version from the database */ $prev_version = get_option('code_snippets_version'); /* Check if this is the first plugin run */ if (!$prev_version) { /* Register capabilities */ $role = get_role(apply_filters('code_snippets_role', 'administrator')); $role->add_cap(apply_filters('code_snippets_cap', 'manage_snippets')); } /* Check if we have upgraded from an older version */ if (version_compare($prev_version, CODE_SNIPPETS_VERSION, '<')) { /* Upgrade the database tables */ create_code_snippets_tables(true); /* Update the plugin version stored in the database */ update_option('code_snippets_version', CODE_SNIPPETS_VERSION); } /* Run multisite-only upgrades */ if (is_multisite() && is_main_site()) { /* Get the current plugin version from the database */ $prev_ms_version = get_site_option('code_snippets_version'); /* Check if this is the first plugin run */ if (!$prev_ms_version) { /* Register multisite capabilities */ $network_cap = apply_filters('code_snippets_network_cap', 'manage_network_snippets'); $supers = get_super_admins(); foreach ($supers as $admin) { $user = new WP_User(0, $admin); $user->add_cap($network_cap); } } /* Check if we have upgraded from an older version */ if (version_compare($prev_ms_version, CODE_SNIPPETS_VERSION, '<')) { /* Update the plugin version stored in the database */ update_site_option('code_snippets_version', CODE_SNIPPETS_VERSION); } } }
/** * Store available users * * @since 1.5 * @since 1.6 Moved to this class from main class * @access public * @return void */ public function store_users() { // Is the current user a super admin? $is_super_admin = is_super_admin($this->get_curUser()->ID); // Is it also one of the manually configured superior admins? $is_superior_admin = VAA_API::is_superior_admin($this->get_curUser()->ID); if (is_network_admin()) { // Get super admins (returns logins) $users = get_super_admins(); // Remove current user if (in_array($this->get_curUser()->user_login, $users)) { unset($users[array_search($this->get_curUser()->user_login, $users)]); } // Convert logins to WP_User objects and filter them for superior admins foreach ($users as $key => $user_login) { $user = get_user_by('login', $user_login); if ($user && !in_array($user->user_login, VAA_API::get_superior_admins())) { $users[$key] = get_user_by('login', $user_login); } else { unset($users[$key]); } } } else { $user_args = array('orderby' => 'display_name', 'exclude' => array_merge(VAA_API::get_superior_admins(), array($this->get_curUser()->ID))); // Do not get regular admins for normal installs (WP 4.4+) if (!is_multisite() && !$is_superior_admin) { $user_args['role__not_in'] = 'administrator'; } // Sort users by role and filter them on available roles $users = $this->filter_sort_users_by_role(get_users($user_args)); } $userids = array(); $usernames = array(); // Loop though all users foreach ($users as $user_key => $user) { // If the current user is not a superior admin, run the user filters if (true !== $is_superior_admin) { /** * Implement checks instead of is_super_admin() because it adds a lot unnecessary queries * * @since 1.5.2 * @See is_super_admin() * @link https://developer.wordpress.org/reference/functions/is_super_admin/ */ //if ( is_super_admin( $user->ID ) ) { if (is_multisite() && in_array($user->user_login, (array) get_super_admins())) { // Remove super admins for multisites unset($users[$user_key]); continue; } elseif (!is_multisite() && $user->has_cap('administrator')) { // Remove regular admins for normal installs unset($users[$user_key]); continue; } elseif (!$is_super_admin && $user->has_cap('view_admin_as')) { // Remove users who can access this plugin for non-admin users with the view_admin_as capability unset($users[$user_key]); continue; } } // Add users who can't access this plugin to the users list $userids[$user->data->ID] = $user->data->display_name; $usernames[$user->data->user_login] = $user->data->display_name; } $this->set_users($users); $this->set_userids($userids); $this->set_usernames($usernames); }
/** * Determine if user is a site admin. * * @since 3.0.0 * * @param int $user_id (Optional) The ID of a user. Defaults to the current user. * @return bool True if the user is a site admin. */ function is_super_admin( $user_id = false ) { if ( $user_id ) $user = new WP_User( $user_id ); else $user = wp_get_current_user(); if ( ! $user->exists() ) return false; if ( is_multisite() ) { $super_admins = get_super_admins(); if ( is_array( $super_admins ) && in_array( $user->user_login, $super_admins ) ) return true; } else { if ( $user->has_cap('delete_users') ) return true; } return false; }
/** * * @param array $users */ function confirm_delete_users($users) { $current_user = wp_get_current_user(); if (!is_array($users) || empty($users)) { return false; } ?> <h1><?php esc_html_e('Users'); ?> </h1> <?php if (1 == count($users)) { ?> <p><?php _e('You have chosen to delete the user from all networks and sites.'); ?> </p> <?php } else { ?> <p><?php _e('You have chosen to delete the following users from all networks and sites.'); ?> </p> <?php } ?> <form action="users.php?action=dodelete" method="post"> <input type="hidden" name="dodelete" /> <?php wp_nonce_field('ms-users-delete'); $site_admins = get_super_admins(); $admin_out = '<option value="' . esc_attr($current_user->ID) . '">' . $current_user->user_login . '</option>'; ?> <table class="form-table"> <?php foreach ($allusers = (array) $_POST['allusers'] as $user_id) { if ($user_id != '' && $user_id != '0') { $delete_user = get_userdata($user_id); if (!current_user_can('delete_user', $delete_user->ID)) { wp_die(sprintf(__('Warning! User %s cannot be deleted.'), $delete_user->user_login)); } if (in_array($delete_user->user_login, $site_admins)) { wp_die(sprintf(__('Warning! User cannot be deleted. The user %s is a network administrator.'), '<em>' . $delete_user->user_login . '</em>')); } ?> <tr> <th scope="row"><?php echo $delete_user->user_login; ?> <?php echo '<input type="hidden" name="user[]" value="' . esc_attr($user_id) . '" />' . "\n"; ?> </th> <?php $blogs = get_blogs_of_user($user_id, true); if (!empty($blogs)) { ?> <td><fieldset><p><legend><?php printf(__('What should be done with content owned by %s?'), '<em>' . $delete_user->user_login . '</em>'); ?> </legend></p> <?php foreach ((array) $blogs as $key => $details) { $blog_users = get_users(array('blog_id' => $details->userblog_id, 'fields' => array('ID', 'user_login'))); if (is_array($blog_users) && !empty($blog_users)) { $user_site = "<a href='" . esc_url(get_home_url($details->userblog_id)) . "'>{$details->blogname}</a>"; $user_dropdown = '<label for="reassign_user" class="screen-reader-text">' . __('Select a user') . '</label>'; $user_dropdown .= "<select name='blog[{$user_id}][{$key}]' id='reassign_user'>"; $user_list = ''; foreach ($blog_users as $user) { if (!in_array($user->ID, $allusers)) { $user_list .= "<option value='{$user->ID}'>{$user->user_login}</option>"; } } if ('' == $user_list) { $user_list = $admin_out; } $user_dropdown .= $user_list; $user_dropdown .= "</select>\n"; ?> <ul style="list-style:none;"> <li><?php printf(__('Site: %s'), $user_site); ?> </li> <li><label><input type="radio" id="delete_option0" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID; ?> ]" value="delete" checked="checked" /> <?php _e('Delete all content.'); ?> </label></li> <li><label><input type="radio" id="delete_option1" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID; ?> ]" value="reassign" /> <?php _e('Attribute all content to:'); ?> </label> <?php echo $user_dropdown; ?> </li> </ul> <?php } } echo "</fieldset></td></tr>"; } else { ?> <td><fieldset><p><legend><?php _e('User has no sites or content and will be deleted.'); ?> </legend></p> <?php } ?> </tr> <?php } } ?> </table> <?php /** This action is documented in wp-admin/users.php */ do_action('delete_user_form', $current_user, $allusers); if (1 == count($users)) { ?> <p><?php _e('Once you hit “Confirm Deletion”, the user will be permanently removed.'); ?> </p> <?php } else { ?> <p><?php _e('Once you hit “Confirm Deletion”, these users will be permanently removed.'); ?> </p> <?php } submit_button(__('Confirm Deletion'), 'primary'); ?> </form> <?php return true; }
function display_rows() { global $current_site, $mode; $alt = ''; $super_admins = get_super_admins(); foreach ($this->items as $user) { $alt = 'alternate' == $alt ? '' : 'alternate'; $status_list = array('spam' => 'site-spammed', 'deleted' => 'site-deleted'); foreach ($status_list as $status => $col) { if ($user->{$status}) { $alt .= " {$col}"; } } ?> <tr class="<?php echo $alt; ?> "> <?php list($columns, $hidden) = $this->get_column_info(); foreach ($columns as $column_name => $column_display_name) { $class = "class='{$column_name} column-{$column_name}'"; $style = ''; if (in_array($column_name, $hidden)) { $style = ' style="display:none;"'; } $attributes = "{$class}{$style}"; switch ($column_name) { case 'cb': ?> <th scope="row" class="check-column"> <input type="checkbox" id="blog_<?php echo $user->ID; ?> " name="allusers[]" value="<?php echo esc_attr($user->ID); ?> " /> </th> <?php break; case 'username': $avatar = get_avatar($user->user_email, 32); if (get_current_user_id() == $user->ID) { $edit_link = esc_url(network_admin_url('profile.php')); } else { $edit_link = esc_url(network_admin_url(add_query_arg('wp_http_referer', urlencode(stripslashes($_SERVER['REQUEST_URI'])), 'user-edit.php?user_id=' . $user->ID))); } echo "<td {$attributes}>"; ?> <?php echo $avatar; ?> <strong><a href="<?php echo $edit_link; ?> " class="edit"><?php echo stripslashes($user->user_login); ?> </a><?php if (in_array($user->user_login, $super_admins)) { echo ' - ' . __('Super Admin'); } ?> </strong> <br/> <?php $actions = array(); $actions['edit'] = '<a href="' . $edit_link . '">' . __('Edit') . '</a>'; if (current_user_can('delete_user', $user->ID) && !in_array($user->user_login, $super_admins)) { $actions['delete'] = '<a href="' . ($delete = esc_url(network_admin_url(add_query_arg('_wp_http_referer', urlencode(stripslashes($_SERVER['REQUEST_URI'])), wp_nonce_url('edit.php', 'deleteuser') . '&action=deleteuser&id=' . $user->ID))) . '" class="delete">' . __('Delete') . '</a>'); } $actions = apply_filters('ms_user_row_actions', $actions, $user); echo $this->row_actions($actions); ?> </td> <?php break; case 'name': echo "<td {$attributes}>{$user->first_name} {$user->last_name}</td>"; break; case 'email': echo "<td {$attributes}><a href='mailto:{$user->user_email}'>{$user->user_email}</a></td>"; break; case 'registered': if ('list' == $mode) { $date = 'Y/m/d'; } else { $date = 'Y/m/d \\<\\b\\r \\/\\> g:i:s a'; } echo "<td {$attributes}>" . mysql2date($date, $user->user_registered) . "</td>"; break; case 'blogs': $blogs = get_blogs_of_user($user->ID, true); echo "<td {$attributes}>"; if (is_array($blogs)) { foreach ((array) $blogs as $key => $val) { if (!can_edit_network($val->site_id)) { continue; } $path = $val->path == '/' ? '' : $val->path; echo '<span class="site-' . $val->site_id . '" >'; echo '<a href="' . esc_url(network_admin_url('site-info.php?id=' . $val->userblog_id)) . '">' . str_replace('.' . $current_site->domain, '', $val->domain . $path) . '</a>'; echo ' <small class="row-actions">'; $actions = array(); $actions['edit'] = '<a href="' . esc_url(network_admin_url('site-info.php?id=' . $val->userblog_id)) . '">' . __('Edit') . '</a>'; $class = ''; if (get_blog_status($val->userblog_id, 'spam') == 1) { $class .= 'site-spammed '; } if (get_blog_status($val->userblog_id, 'mature') == 1) { $class .= 'site-mature '; } if (get_blog_status($val->userblog_id, 'deleted') == 1) { $class .= 'site-deleted '; } if (get_blog_status($val->userblog_id, 'archived') == 1) { $class .= 'site-archived '; } $actions['view'] = '<a class="' . $class . '" href="' . esc_url(get_home_url($val->userblog_id)) . '">' . __('View') . '</a>'; $actions = apply_filters('ms_user_list_site_actions', $actions, $val->userblog_id); $i = 0; $action_count = count($actions); foreach ($actions as $action => $link) { ++$i; $i == $action_count ? $sep = '' : ($sep = ' | '); echo "<span class='{$action}'>{$link}{$sep}</span>"; } echo '</small></span><br/>'; } } ?> </td> <?php break; default: echo "<td {$attributes}>"; echo apply_filters('manage_users_custom_column', '', $column_name, $user->ID); echo "</td>"; break; } } ?> </tr> <?php } }
/** * Generates and displays row action links. * * @since 4.3.0 * @access protected * * @param object $user User being acted upon. * @param string $column_name Current column name. * @param string $primary Primary column name. * @return string Row actions output for users in Multisite. */ protected function handle_row_actions($user, $column_name, $primary) { if ($primary !== $column_name) { return ''; } $super_admins = get_super_admins(); $edit_link = esc_url(add_query_arg('wp_http_referer', urlencode(wp_unslash($_SERVER['REQUEST_URI'])), get_edit_user_link($user->ID))); $actions = array(); $actions['edit'] = '<a href="' . $edit_link . '">' . __('Edit') . '</a>'; if (current_user_can('delete_user', $user->ID) && !in_array($user->user_login, $super_admins)) { $actions['delete'] = '<a href="' . ($delete = esc_url(network_admin_url(add_query_arg('_wp_http_referer', urlencode(wp_unslash($_SERVER['REQUEST_URI'])), wp_nonce_url('users.php', 'deleteuser') . '&action=deleteuser&id=' . $user->ID))) . '" class="delete">' . __('Delete') . '</a>'); } /** * Filter the action links displayed under each user in the Network Admin Users list table. * * @since 3.2.0 * * @param array $actions An array of action links to be displayed. * Default 'Edit', 'Delete'. * @param WP_User $user WP_User object. */ $actions = apply_filters('ms_user_row_actions', $actions, $user); return $this->row_actions($actions); }
public static function becomeAdmin() { $db = new wfDB(); global $wpdb; $adminUserID = false; $userSource = ''; if (is_multisite()) { $users = get_users('role=super&fields=ID'); if (sizeof($users) < 1) { $supers = get_super_admins(); if (sizeof($supers) > 0) { foreach ($supers as $superLogin) { $superDat = get_user_by('login', $superLogin); if ($superDat) { $users = array($superDat->ID); $userSource = 'multisite get_super_admins() function'; break; } } } } else { $userSource = 'multisite get_users() function'; } } else { $users = get_users('role=administrator&fields=ID'); if (sizeof($users) < 1) { $supers = get_super_admins(); if (sizeof($supers) > 0) { foreach ($supers as $superLogin) { $superDat = get_user_by('login', $superLogin); if ($superDat) { $users = array($superDat->ID); $userSource = 'singlesite get_super_admins() function'; break; } } } } else { $userSource = 'singlesite get_users() function'; } } if (sizeof($users) > 0) { sort($users, SORT_NUMERIC); $adminUserID = $users[0]; } else { //Last ditch attempt $adminUserID = $db->querySingle("select user_id from " . $wpdb->usermeta . " where meta_key='" . $wpdb->base_prefix . "user_level' order by meta_value desc, user_id asc limit 1"); if (!$adminUserID) { //One final attempt for those who have changed their table prefixes but the meta_key is still wp_ prefixed... $adminUserID = $db->querySingle("select user_id from " . $wpdb->usermeta . " where meta_key='wp_user_level' order by meta_value desc, user_id asc limit 1"); if (!$adminUserID) { self::status(1, 'error', "Could not get the administrator's user ID. Scan can't continue."); exit; } } $userSource = 'manual DB query'; } $adminUsername = $db->querySingle("select user_login from " . $wpdb->users . " where ID=%d", $adminUserID); self::status(4, 'info', "Scan will run as admin user '{$adminUsername}' with ID '{$adminUserID}' sourced from: {$userSource}"); wp_set_current_user($adminUserID); if (!is_user_logged_in()) { self::status(1, 'error', "Scan could not sign in as user '{$adminUsername}' with ID '{$adminUserID}' from source '{$userSource}'. Scan can't continue."); exit; } self::status(4, 'info', "Scan authentication complete."); }
/** * Create a site in a multisite install. * * ## OPTIONS * * --slug=<slug> * : Path for the new site. Subdomain on subdomain installs, directory on subdirectory installs. * * [--title=<title>] * : Title of the new site. Default: prettified slug. * * [--email=<email>] * : Email for Admin user. User will be created if none exists. Assignement to Super Admin if not included. * * [--network_id=<network-id>] * : Network to associate new site with. Defaults to current network (typically 1). * * [--private] * : If set, the new site will be non-public (not indexed) * * [--porcelain] * : If set, only the site id will be output on success. */ public function create($_, $assoc_args) { if (!is_multisite()) { WP_CLI::error('This is not a multisite install.'); } global $wpdb, $current_site; $base = $assoc_args['slug']; $title = \WP_CLI\Utils\get_flag_value($assoc_args, 'title', ucfirst($base)); $email = empty($assoc_args['email']) ? '' : $assoc_args['email']; // Network if (!empty($assoc_args['network_id'])) { $network = $this->_get_network($assoc_args['network_id']); if ($network === false) { WP_CLI::error(sprintf('Network with id %d does not exist.', $assoc_args['network_id'])); } } else { $network = $current_site; } $public = !\WP_CLI\Utils\get_flag_value($assoc_args, 'private'); // Sanitize if (preg_match('|^([a-zA-Z0-9-])+$|', $base)) { $base = strtolower($base); } // If not a subdomain install, make sure the domain isn't a reserved word if (!is_subdomain_install()) { $subdirectory_reserved_names = apply_filters('subdirectory_reserved_names', array('page', 'comments', 'blog', 'files', 'feed')); if (in_array($base, $subdirectory_reserved_names)) { WP_CLI::error('The following words are reserved and cannot be used as blog names: ' . implode(', ', $subdirectory_reserved_names)); } } // Check for valid email, if not, use the first Super Admin found // Probably a more efficient way to do this so we dont query for the // User twice if super admin $email = sanitize_email($email); if (empty($email) || !is_email($email)) { $super_admins = get_super_admins(); $email = ''; if (!empty($super_admins) && is_array($super_admins)) { // Just get the first one $super_login = $super_admins[0]; $super_user = get_user_by('login', $super_login); if ($super_user) { $email = $super_user->user_email; } } } if (is_subdomain_install()) { $path = '/'; $url = $newdomain = $base . '.' . preg_replace('|^www\\.|', '', $network->domain); } else { $newdomain = $network->domain; $path = '/' . trim($base, '/') . '/'; $url = $network->domain . $path; } $user_id = email_exists($email); if (!$user_id) { // Create a new user with a random password $password = wp_generate_password(12, false); $user_id = wpmu_create_user($base, $password, $email); if (false == $user_id) { WP_CLI::error("Can't create user."); } else { wp_new_user_notification($user_id, $password); } } $wpdb->hide_errors(); $id = wpmu_create_blog($newdomain, $path, $title, $user_id, array('public' => $public), $network->id); $wpdb->show_errors(); if (!is_wp_error($id)) { if (!is_super_admin($user_id) && !get_user_option('primary_blog', $user_id)) { update_user_option($user_id, 'primary_blog', $id, true); } // Prevent mailing admins of new sites // @TODO argument to pass in? // $content_mail = sprintf(__( "New site created by WP Command Line Interface\n\nAddress: %2s\nName: %3s"), get_site_url($id), stripslashes($title)); // wp_mail(get_site_option('admin_email'), sprintf(__('[%s] New Site Created'), $current_site->site_name), $content_mail, 'From: "Site Admin" <'.get_site_option( 'admin_email').'>'); } else { WP_CLI::error($id->get_error_message()); } if (\WP_CLI\Utils\get_flag_value($assoc_args, 'porcelain')) { WP_CLI::line($id); } else { WP_CLI::success("Site {$id} created: {$url}"); } }
function confirm_delete_users($users) { $current_user = wp_get_current_user(); if (!is_array($users)) { return false; } screen_icon(); ?> <h2><?php esc_html_e('Users'); ?> </h2> <p><?php _e('Transfer or delete posts and links before deleting users.'); ?> </p> <form action="users.php?action=dodelete" method="post"> <input type="hidden" name="dodelete" /> <?php wp_nonce_field('ms-users-delete'); $site_admins = get_super_admins(); $admin_out = "<option value='{$current_user->ID}'>{$current_user->user_login}</option>"; foreach ($allusers = (array) $_POST['allusers'] as $key => $val) { if ($val != '' && $val != '0') { $delete_user = new WP_User($val); if (!current_user_can('delete_user', $delete_user->ID)) { wp_die(sprintf(__('Warning! User %s cannot be deleted.'), $delete_user->user_login)); } if (in_array($delete_user->user_login, $site_admins)) { wp_die(sprintf(__('Warning! User cannot be deleted. The user %s is a network admnistrator.'), $delete_user->user_login)); } echo "<input type='hidden' name='user[]' value='{$val}'/>\n"; $blogs = get_blogs_of_user($val, true); if (!empty($blogs)) { ?> <br /><fieldset><p><legend><?php printf(__("What should be done with posts and links owned by <em>%s</em>?"), $delete_user->user_login); ?> </legend></p> <?php foreach ((array) $blogs as $key => $details) { $blog_users = get_users(array('blog_id' => $details->userblog_id)); if (is_array($blog_users) && !empty($blog_users)) { $user_site = "<a href='" . esc_url(get_home_url($details->userblog_id)) . "'>{$details->blogname}</a>"; $user_dropdown = "<select name='blog[{$val}][{$key}]'>"; $user_list = ''; foreach ($blog_users as $user) { if (!in_array($user->ID, $allusers)) { $user_list .= "<option value='{$user->ID}'>{$user->user_login}</option>"; } } if ('' == $user_list) { $user_list = $admin_out; } $user_dropdown .= $user_list; $user_dropdown .= "</select>\n"; ?> <ul style="list-style:none;"> <li><?php printf(__('Site: %s'), $user_site); ?> </li> <li><label><input type="radio" id="delete_option0" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID; ?> ]" value="delete" checked="checked" /> <?php _e('Delete all posts and links.'); ?> </label></li> <li><label><input type="radio" id="delete_option1" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID; ?> ]" value="reassign" /> <?php echo __('Attribute all posts and links to:') . '</label>' . $user_dropdown; ?> </li> </ul> <?php } } echo "</fieldset>"; } } } submit_button(__('Confirm Deletion'), 'delete'); ?> </form> <?php return true; }
/** * Render the Status metabox for user's profile screen. * * Actions are: * - Update profile fields if xProfile component is active * - Spam/Unspam user * * @since 2.0.0 * * @param WP_User|null $user The WP_User object to be edited. */ public function user_admin_status_metabox($user = null) { // Bail if no user id or if the user has not activated their account yet. if (empty($user->ID)) { return; } // Bail if user has not been activated yet (how did you get here?). if (isset($user->user_status) && 2 == $user->user_status) { ?> <p class="not-activated"><?php esc_html_e('User account has not yet been activated', 'buddypress'); ?> </p><br/> <?php return; } ?> <div class="submitbox" id="submitcomment"> <div id="minor-publishing"> <div id="misc-publishing-actions"> <?php // Get the spam status once here to compare against below. $is_spammer = bp_is_user_spammer($user->ID); /** * In configs where BuddyPress is not network activated, * regular admins cannot mark a user as a spammer on front * end. This prevent them to do it in backend. * * Also prevent admins from marking themselves or other * admins as spammers. */ if (empty($this->is_self_profile) && !in_array($user->user_login, get_super_admins()) && empty($this->subsite_activated) || !empty($this->subsite_activated) && current_user_can('manage_network_users')) { ?> <div class="misc-pub-section" id="comment-status-radio"> <label class="approved"><input type="radio" name="user_status" value="ham" <?php checked($is_spammer, false); ?> ><?php esc_html_e('Active', 'buddypress'); ?> </label><br /> <label class="spam"><input type="radio" name="user_status" value="spam" <?php checked($is_spammer, true); ?> ><?php esc_html_e('Spammer', 'buddypress'); ?> </label> </div> <?php } ?> <div class="misc-pub-section curtime misc-pub-section-last"> <?php // Translators: Publish box date format, see http://php.net/date. $datef = __('M j, Y @ G:i', 'buddypress'); $date = date_i18n($datef, strtotime($user->user_registered)); ?> <span id="timestamp"><?php printf(__('Registered on: %s', 'buddypress'), '<strong>' . $date . '</strong>'); ?> </span> </div> </div> <!-- #misc-publishing-actions --> <div class="clear"></div> </div><!-- #minor-publishing --> <div id="major-publishing-actions"> <div id="publishing-action"> <a class="button bp-view-profile" href="<?php echo esc_url(bp_core_get_user_domain($user->ID)); ?> " target="_blank"><?php esc_html_e('View Profile', 'buddypress'); ?> </a> <?php submit_button(esc_html__('Update Profile', 'buddypress'), 'primary', 'save', false); ?> </div> <div class="clear"></div> </div><!-- #major-publishing-actions --> </div><!-- #submitcomment --> <?php }
/** * Perform import operation * @param string $xml XML string to import * @param callback[optional] $logger Method where progress messages are submmitted * @return PMXI_Import_Record * @chainable */ public function process($xml, $logger = NULL, $chunk = false, $is_cron = false, $xpath_prefix = '', $loop = 0) { add_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html')); kses_init(); // do not perform special filtering for imported content kses_remove_filters(); $cxpath = $xpath_prefix . $this->xpath; $this->options += PMXI_Plugin::get_default_import_options(); // make sure all options are defined $avoid_pingbacks = PMXI_Plugin::getInstance()->getOption('pingbacks'); $cron_sleep = (int) PMXI_Plugin::getInstance()->getOption('cron_sleep'); if ($avoid_pingbacks and !defined('WP_IMPORTING')) { define('WP_IMPORTING', true); } $postRecord = new PMXI_Post_Record(); $tmp_files = array(); // compose records to import $records = array(); $is_import_complete = false; try { $chunk == 1 and $logger and call_user_func($logger, __('Composing titles...', 'wp_all_import_plugin')); if (!empty($this->options['title'])) { $titles = XmlImportParser::factory($xml, $cxpath, $this->options['title'], $file)->parse($records); $tmp_files[] = $file; } else { $loop and $titles = array_fill(0, $loop, ''); } $chunk == 1 and $logger and call_user_func($logger, __('Composing excerpts...', 'wp_all_import_plugin')); $post_excerpt = array(); if (!empty($this->options['post_excerpt'])) { $post_excerpt = XmlImportParser::factory($xml, $cxpath, $this->options['post_excerpt'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_excerpt = array_fill(0, count($titles), ''); } if ("xpath" == $this->options['status']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing statuses...', 'wp_all_import_plugin')); $post_status = array(); if (!empty($this->options['status_xpath'])) { $post_status = XmlImportParser::factory($xml, $cxpath, $this->options['status_xpath'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_status = array_fill(0, count($titles), 'publish'); } } if ("xpath" == $this->options['comment_status']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing comment statuses...', 'wp_all_import_plugin')); $comment_status = array(); if (!empty($this->options['comment_status_xpath'])) { $comment_status = XmlImportParser::factory($xml, $cxpath, $this->options['comment_status_xpath'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $comment_status = array_fill(0, count($titles), 'open'); } } if ("xpath" == $this->options['ping_status']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing ping statuses...', 'wp_all_import_plugin')); $ping_status = array(); if (!empty($this->options['ping_status_xpath'])) { $ping_status = XmlImportParser::factory($xml, $cxpath, $this->options['ping_status_xpath'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $ping_status = array_fill(0, count($titles), 'open'); } } if ("xpath" == $this->options['post_format']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing post formats...', 'wp_all_import_plugin')); $post_format = array(); if (!empty($this->options['post_format_xpath'])) { $post_format = XmlImportParser::factory($xml, $cxpath, $this->options['post_format_xpath'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_format = array_fill(0, count($titles), 'open'); } } if ("pid" == $this->options['duplicate_indicator']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing post IDs...', 'wp_all_import_plugin')); $post_ids = array(); if (!empty($this->options['pid_xpath'])) { $post_ids = XmlImportParser::factory($xml, $cxpath, $this->options['pid_xpath'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_ids = array_fill(0, count($titles), ''); } } if ("no" == $this->options['is_multiple_page_template']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing page templates...', 'wp_all_import_plugin')); $page_template = array(); if (!empty($this->options['single_page_template'])) { $page_template = XmlImportParser::factory($xml, $cxpath, $this->options['single_page_template'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $page_template = array_fill(0, count($titles), 'default'); } } if ($this->options['is_override_post_type'] and !empty($this->options['post_type_xpath'])) { $chunk == 1 and $logger and call_user_func($logger, __('Composing post types...', 'wp_all_import_plugin')); $post_type = array(); $post_type = XmlImportParser::factory($xml, $cxpath, $this->options['post_type_xpath'], $file)->parse($records); $tmp_files[] = $file; } else { if ('post' == $this->options['type'] and '' != $this->options['custom_type']) { $pType = $this->options['custom_type']; } else { $pType = $this->options['type']; } count($titles) and $post_type = array_fill(0, count($titles), $pType); } if ("no" == $this->options['is_multiple_page_parent']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing page parent...', 'wp_all_import_plugin')); $page_parent = array(); if (!empty($this->options['single_page_parent'])) { $page_parent = XmlImportParser::factory($xml, $cxpath, $this->options['single_page_parent'], $file)->parse($records); $tmp_files[] = $file; foreach ($page_parent as $key => $identity) { $page = 0; switch ($this->options['type']) { case 'post': if (!empty($identity)) { if (ctype_digit($identity)) { $page = get_post($identity); } else { $page = get_page_by_title($identity, OBJECT, $post_type[$key]); if (empty($page)) { $args = array('name' => $identity, 'post_type' => $post_type[$key], 'post_status' => 'any', 'numberposts' => 1); $my_posts = get_posts($args); if ($my_posts) { $page = $my_posts[0]; } } } } break; case 'page': $page = get_page_by_title($identity) or $page = get_page_by_path($identity) or ctype_digit($identity) and $page = get_post($identity); break; default: # code... break; } $page_parent[$key] = !empty($page) ? $page->ID : 0; } } else { count($titles) and $page_parent = array_fill(0, count($titles), 0); } } $chunk == 1 and $logger and call_user_func($logger, __('Composing authors...', 'wp_all_import_plugin')); $post_author = array(); $current_user = wp_get_current_user(); if (!empty($this->options['author'])) { $post_author = XmlImportParser::factory($xml, $cxpath, $this->options['author'], $file)->parse($records); $tmp_files[] = $file; foreach ($post_author as $key => $author) { $user = get_user_by('login', $author) or $user = get_user_by('slug', $author) or $user = get_user_by('email', $author) or ctype_digit($author) and $user = get_user_by('id', $author); if (!empty($user)) { $post_author[$key] = $user->ID; } else { if ($current_user->ID) { $post_author[$key] = $current_user->ID; } else { $super_admins = get_super_admins(); if (!empty($super_admins)) { $sauthor = array_shift($super_admins); $user = get_user_by('login', $sauthor) or $user = get_user_by('slug', $sauthor) or $user = get_user_by('email', $sauthor) or ctype_digit($sauthor) and $user = get_user_by('id', $sauthor); $post_author[$key] = !empty($user) ? $user->ID : $current_user->ID; } } } } } else { if ($current_user->ID) { count($titles) and $post_author = array_fill(0, count($titles), $current_user->ID); } else { $super_admins = get_super_admins(); if (!empty($super_admins)) { $author = array_shift($super_admins); $user = get_user_by('login', $author) or $user = get_user_by('slug', $author) or $user = get_user_by('email', $author) or ctype_digit($author) and $user = get_user_by('id', $author); count($titles) and $post_author = array_fill(0, count($titles), !empty($user) ? $user->ID : $current_user->ID); } } } $chunk == 1 and $logger and call_user_func($logger, __('Composing slugs...', 'wp_all_import_plugin')); $post_slug = array(); if (!empty($this->options['post_slug'])) { $post_slug = XmlImportParser::factory($xml, $cxpath, $this->options['post_slug'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $post_slug = array_fill(0, count($titles), ''); } $chunk == 1 and $logger and call_user_func($logger, __('Composing menu order...', 'wp_all_import_plugin')); $menu_order = array(); if (!empty($this->options['order'])) { $menu_order = XmlImportParser::factory($xml, $cxpath, $this->options['order'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $menu_order = array_fill(0, count($titles), ''); } $chunk == 1 and $logger and call_user_func($logger, __('Composing contents...', 'wp_all_import_plugin')); if (!empty($this->options['content'])) { $contents = XmlImportParser::factory((!empty($this->options['is_keep_linebreaks']) and intval($this->options['is_keep_linebreaks'])) ? $xml : preg_replace('%\\r\\n?|\\n%', ' ', $xml), $cxpath, $this->options['content'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $contents = array_fill(0, count($titles), ''); } $chunk == 1 and $logger and call_user_func($logger, __('Composing dates...', 'wp_all_import_plugin')); if ('specific' == $this->options['date_type']) { $dates = XmlImportParser::factory($xml, $cxpath, $this->options['date'], $file)->parse($records); $tmp_files[] = $file; $warned = array(); // used to prevent the same notice displaying several times foreach ($dates as $i => $d) { if ($d == 'now') { $d = current_time('mysql'); } // Replace 'now' with the WordPress local time to account for timezone offsets (WordPress references its local time during publishing rather than the server’s time so it should use that) $time = strtotime($d); if (FALSE === $time) { in_array($d, $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $d)); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $time = time(); } $dates[$i] = date('Y-m-d H:i:s', $time); } } else { $dates_start = XmlImportParser::factory($xml, $cxpath, $this->options['date_start'], $file)->parse($records); $tmp_files[] = $file; $dates_end = XmlImportParser::factory($xml, $cxpath, $this->options['date_end'], $file)->parse($records); $tmp_files[] = $file; $warned = array(); // used to prevent the same notice displaying several times foreach ($dates_start as $i => $d) { $time_start = strtotime($dates_start[$i]); if (FALSE === $time_start) { in_array($dates_start[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $dates_start[$i])); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $time_start = time(); } $time_end = strtotime($dates_end[$i]); if (FALSE === $time_end) { in_array($dates_end[$i], $warned) or $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: unrecognized date format `%s`, assigning current date', 'wp_all_import_plugin'), $warned[] = $dates_end[$i])); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $time_end = time(); } $dates[$i] = date('Y-m-d H:i:s', mt_rand($time_start, $time_end)); } } // [custom taxonomies] require_once ABSPATH . 'wp-admin/includes/taxonomy.php'; $taxonomies = array(); $exclude_taxonomies = apply_filters('pmxi_exclude_taxonomies', class_exists('PMWI_Plugin') ? array('post_format', 'product_type', 'product_shipping_class') : array('post_format')); $post_taxonomies = array_diff_key(get_taxonomies_by_object_type(array($this->options['custom_type']), 'object'), array_flip($exclude_taxonomies)); if (!empty($post_taxonomies)) { foreach ($post_taxonomies as $ctx) { if ("" == $ctx->labels->name or class_exists('PMWI_Plugin') and strpos($ctx->name, "pa_") === 0 and $this->options['custom_type'] == "product") { continue; } $chunk == 1 and $logger and call_user_func($logger, sprintf(__('Composing terms for `%s` taxonomy...', 'wp_all_import_plugin'), $ctx->labels->name)); $tx_name = $ctx->name; $mapping_rules = !empty($this->options['tax_mapping'][$tx_name]) ? json_decode($this->options['tax_mapping'][$tx_name], true) : false; $taxonomies[$tx_name] = array(); if (!empty($this->options['tax_logic'][$tx_name]) and !empty($this->options['tax_assing'][$tx_name])) { switch ($this->options['tax_logic'][$tx_name]) { case 'single': if (!empty($this->options['tax_single_xpath'][$tx_name])) { $txes = XmlImportParser::factory($xml, $cxpath, $this->options['tax_single_xpath'][$tx_name], $file)->parse($records); $tmp_files[] = $file; foreach ($txes as $i => $tx) { $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $tx, 'parent' => false, 'assign' => isset($this->options['term_assing'][$tx_name]) ? $this->options['term_assing'][$tx_name] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name); } } break; case 'multiple': if (!empty($this->options['tax_multiple_xpath'][$tx_name])) { $txes = XmlImportParser::factory($xml, $cxpath, $this->options['tax_multiple_xpath'][$tx_name], $file)->parse($records); $tmp_files[] = $file; foreach ($txes as $i => $tx) { $_tx = $tx; // apply mapping rules before splitting via separator symbol if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) { if (!empty($mapping_rules)) { foreach ($mapping_rules as $rule) { if (!empty($rule[trim($_tx)])) { $_tx = trim($rule[trim($_tx)]); break; } } } } $delimeted_taxonomies = explode(!empty($this->options['tax_multiple_delim'][$tx_name]) ? $this->options['tax_multiple_delim'][$tx_name] : ',', $_tx); if (!empty($delimeted_taxonomies)) { foreach ($delimeted_taxonomies as $cc) { $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $cc, 'parent' => false, 'assign' => isset($this->options['multiple_term_assing'][$tx_name]) ? $this->options['multiple_term_assing'][$tx_name] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name); } } } } break; case 'hierarchical': if (!empty($this->options['tax_hierarchical_logic_entire'][$tx_name])) { if (!empty($this->options['tax_hierarchical_xpath'][$tx_name]) and is_array($this->options['tax_hierarchical_xpath'][$tx_name])) { count($titles) and $iterator = array_fill(0, count($titles), 0); $taxonomies_hierarchy_groups = array_fill(0, count($titles), array()); // separate hierarchy groups via symbol if (!empty($this->options['is_tax_hierarchical_group_delim'][$tx_name]) and !empty($this->options['tax_hierarchical_group_delim'][$tx_name])) { foreach ($this->options['tax_hierarchical_xpath'][$tx_name] as $k => $tx_xpath) { if (empty($tx_xpath)) { continue; } $txes = XmlImportParser::factory($xml, $cxpath, $tx_xpath, $file)->parse($records); $tmp_files[] = $file; foreach ($txes as $i => $tx) { $_tx = $tx; // apply mapping rules before splitting via separator symbol if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) { if (!empty($mapping_rules)) { foreach ($mapping_rules as $rule) { if (!empty($rule[trim($_tx)])) { $_tx = trim($rule[trim($_tx)]); break; } } } } $delimeted_groups = explode($this->options['tax_hierarchical_group_delim'][$tx_name], $_tx); if (!empty($delimeted_groups) and is_array($delimeted_groups)) { foreach ($delimeted_groups as $group) { if (!empty($group)) { array_push($taxonomies_hierarchy_groups[$i], $group); } } } } } } else { foreach ($this->options['tax_hierarchical_xpath'][$tx_name] as $k => $tx_xpath) { if (empty($tx_xpath)) { continue; } $txes = XmlImportParser::factory($xml, $cxpath, $tx_xpath, $file)->parse($records); $tmp_files[] = $file; foreach ($txes as $i => $tx) { array_push($taxonomies_hierarchy_groups[$i], $tx); } } } foreach ($taxonomies_hierarchy_groups as $i => $groups) { if (empty($groups)) { continue; } foreach ($groups as $kk => $tx) { $_tx = $tx; // apply mapping rules before splitting via separator symbol if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) { if (!empty($mapping_rules)) { foreach ($mapping_rules as $rule) { if (!empty($rule[trim($_tx)])) { $_tx = trim($rule[trim($_tx)]); break; } } } } $delimeted_taxonomies = explode(!empty($this->options['tax_hierarchical_delim'][$tx_name]) ? $this->options['tax_hierarchical_delim'][$tx_name] : ',', $_tx); if (!empty($delimeted_taxonomies)) { foreach ($delimeted_taxonomies as $j => $cc) { $is_assign_term = isset($this->options['tax_hierarchical_assing'][$tx_name][$k]) ? $this->options['tax_hierarchical_assing'][$tx_name][$k] : true; if (!empty($this->options['tax_hierarchical_last_level_assign'][$tx_name])) { $is_assign_term = count($delimeted_taxonomies) == $j + 1 ? 1 : 0; } $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => $cc, 'parent' => (!empty($taxonomies[$tx_name][$i][$iterator[$i] - 1]) and $j) ? $taxonomies[$tx_name][$i][$iterator[$i] - 1] : false, 'assign' => $is_assign_term, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => $j + 1, 'max_hierarchy_level' => count($delimeted_taxonomies)), $mapping_rules, $tx_name); $iterator[$i]++; } } } } } } if (!empty($this->options['tax_hierarchical_logic_manual'][$tx_name])) { if (!empty($this->options['post_taxonomies'][$tx_name])) { $taxonomies_hierarchy = json_decode($this->options['post_taxonomies'][$tx_name], true); foreach ($taxonomies_hierarchy as $k => $taxonomy) { if ("" == $taxonomy['xpath']) { continue; } $txes_raw = XmlImportParser::factory($xml, $cxpath, $taxonomy['xpath'], $file)->parse($records); $tmp_files[] = $file; $warned = array(); foreach ($txes_raw as $i => $cc) { $_tx = $cc; // apply mapping rules before splitting via separator symbol if (!empty($this->options['tax_enable_mapping'][$tx_name]) and !empty($this->options['tax_logic_mapping'][$tx_name])) { if (!empty($mapping_rules)) { foreach ($mapping_rules as $rule) { if (!empty($rule[trim($_tx)])) { $_tx = trim($rule[trim($_tx)]); break; } } } } if (!empty($this->options['tax_manualhierarchy_delim'][$tx_name])) { $delimeted_taxonomies = explode($this->options['tax_manualhierarchy_delim'][$tx_name], $_tx); } if (empty($delimeted_taxonomies)) { continue; } if (empty($taxonomies_hierarchy[$k]['txn_names'][$i])) { $taxonomies_hierarchy[$k]['txn_names'][$i] = array(); } if (empty($taxonomies[$tx_name][$i])) { $taxonomies[$tx_name][$i] = array(); } $count_cats = count($taxonomies[$tx_name][$i]); foreach ($delimeted_taxonomies as $j => $dc) { if (!empty($taxonomy['parent_id'])) { foreach ($taxonomies_hierarchy as $key => $value) { if ($value['item_id'] == $taxonomy['parent_id'] and !empty($value['txn_names'][$i])) { foreach ($value['txn_names'][$i] as $parent) { $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => trim($dc), 'parent' => $parent, 'assign' => isset($taxonomy['assign']) ? $taxonomy['assign'] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name); } } } } else { $taxonomies[$tx_name][$i][] = wp_all_import_ctx_mapping(array('name' => trim($dc), 'parent' => false, 'assign' => isset($taxonomy['assign']) ? $taxonomy['assign'] : true, 'is_mapping' => !empty($this->options['tax_enable_mapping'][$tx_name]) and empty($this->options['tax_logic_mapping'][$tx_name]), 'hierarchy_level' => 1, 'max_hierarchy_level' => 1), $mapping_rules, $tx_name); } if ($count_cats < count($taxonomies[$tx_name][$i])) { $taxonomies_hierarchy[$k]['txn_names'][$i][] = $taxonomies[$tx_name][$i][count($taxonomies[$tx_name][$i]) - 1]; } } } } } } break; default: break; } } } } // [/custom taxonomies] // Composing featured images $image_sections = apply_filters('wp_all_import_image_sections', array(array('slug' => '', 'title' => __('Images', 'wp_all_import_plugin'), 'type' => 'images'))); if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $uploads['error']); $logger and call_user_func($logger, __('<b>WARNING</b>: No featured images will be created. Uploads folder is not found.', 'wp_all_import_plugin')); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } else { $images_bundle = array(); $auto_rename_images_bundle = array(); $auto_extensions_bundle = array(); $image_meta_titles_bundle = array(); $image_meta_captions_bundle = array(); $image_meta_alts_bundle = array(); $image_meta_descriptions_bundle = array(); foreach ($image_sections as $section) { $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for ' . strtolower($section['title']) . '...', 'wp_all_import_plugin')); $featured_images = array(); if ("no" == $this->options[$section['slug'] . 'download_images']) { if ($this->options[$section['slug'] . 'featured_image']) { $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'featured_image'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $featured_images = array_fill(0, count($titles), ''); } } elseif ("gallery" == $this->options[$section['slug'] . 'download_images']) { if ($this->options[$section['slug'] . 'gallery_featured_image']) { $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'gallery_featured_image'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $featured_images = array_fill(0, count($titles), ''); } } else { if ($this->options[$section['slug'] . 'download_featured_image']) { $featured_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'download_featured_image'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $featured_images = array_fill(0, count($titles), ''); } } $images_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = array('type' => $section['type'], 'files' => $featured_images); // Composing images meta titles if ($this->options[$section['slug'] . 'set_image_meta_title']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (titles)...', 'wp_all_import_plugin')); $image_meta_titles = array(); if ($this->options[$section['slug'] . 'image_meta_title']) { $image_meta_titles = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_title'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_titles = array_fill(0, count($titles), ''); } $image_meta_titles_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_titles; } // Composing images meta captions if ($this->options[$section['slug'] . 'set_image_meta_caption']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (captions)...', 'wp_all_import_plugin')); $image_meta_captions = array(); if ($this->options[$section['slug'] . 'image_meta_caption']) { $image_meta_captions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_caption'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_captions = array_fill(0, count($titles), ''); } $image_meta_captions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_captions; } // Composing images meta alt text if ($this->options[$section['slug'] . 'set_image_meta_alt']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (alt text)...', 'wp_all_import_plugin')); $image_meta_alts = array(); if ($this->options[$section['slug'] . 'image_meta_alt']) { $image_meta_alts = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_alt'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_alts = array_fill(0, count($titles), ''); } $image_meta_alts_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_alts; } // Composing images meta description if ($this->options[$section['slug'] . 'set_image_meta_description']) { $chunk == 1 and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' meta data (description)...', 'wp_all_import_plugin')); $image_meta_descriptions = array(); if ($this->options[$section['slug'] . 'image_meta_description']) { $image_meta_descriptions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'image_meta_description'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $image_meta_descriptions = array_fill(0, count($titles), ''); } $image_meta_descriptions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $image_meta_descriptions; } if ("yes" == $this->options[$section['slug'] . 'download_images']) { // Composing images suffix $chunk == 1 and $this->options[$section['slug'] . 'auto_rename_images'] and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' suffix...', 'wp_all_import_plugin')); $auto_rename_images = array(); if ($this->options[$section['slug'] . 'auto_rename_images'] and !empty($this->options[$section['slug'] . 'auto_rename_images_suffix'])) { $auto_rename_images = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'auto_rename_images_suffix'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $auto_rename_images = array_fill(0, count($titles), ''); } $auto_rename_images_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $auto_rename_images; // Composing images extensions $chunk == 1 and $this->options[$section['slug'] . 'auto_set_extension'] and $logger and call_user_func($logger, __('Composing ' . strtolower($section['title']) . ' extensions...', 'wp_all_import_plugin')); $auto_extensions = array(); if ($this->options[$section['slug'] . 'auto_set_extension'] and !empty($this->options[$section['slug'] . 'new_extension'])) { $auto_extensions = XmlImportParser::factory($xml, $cxpath, $this->options[$section['slug'] . 'new_extension'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $auto_extensions = array_fill(0, count($titles), ''); } $auto_extensions_bundle[empty($section['slug']) ? 'pmxi_gallery_image' : $section['slug']] = $auto_extensions; } } } // Composing attachments if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) { $logger and call_user_func($logger, __('<b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $uploads['error']); $logger and call_user_func($logger, __('<b>WARNING</b>: No attachments will be created', 'wp_all_import_plugin')); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } else { $chunk == 1 and $logger and call_user_func($logger, __('Composing URLs for attachments files...', 'wp_all_import_plugin')); $attachments = array(); if ($this->options['attachments']) { // Detect if attachments is separated by comma $atchs = explode(',', $this->options['attachments']); if (!empty($atchs)) { $parse_multiple = true; foreach ($atchs as $atch) { if (!preg_match("/{.*}/", trim($atch))) { $parse_multiple = false; } } if ($parse_multiple) { foreach ($atchs as $atch) { $posts_attachments = XmlImportParser::factory($xml, $cxpath, trim($atch), $file)->parse($records); $tmp_files[] = $file; foreach ($posts_attachments as $i => $val) { $attachments[$i][] = $val; } } } else { $attachments = XmlImportParser::factory($xml, $cxpath, $this->options['attachments'], $file)->parse($records); $tmp_files[] = $file; } } } else { count($titles) and $attachments = array_fill(0, count($titles), ''); } } $chunk == 1 and $logger and call_user_func($logger, __('Composing unique keys...', 'wp_all_import_plugin')); if (!empty($this->options['unique_key'])) { $unique_keys = XmlImportParser::factory($xml, $cxpath, $this->options['unique_key'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $unique_keys = array_fill(0, count($titles), ''); } $chunk == 1 and $logger and call_user_func($logger, __('Processing posts...', 'wp_all_import_plugin')); $addons = array(); $addons_data = array(); // data parsing for WP All Import add-ons $chunk == 1 and $logger and call_user_func($logger, __('Data parsing via add-ons...', 'wp_all_import_plugin')); $parsingData = array('import' => $this, 'count' => count($titles), 'xml' => $xml, 'logger' => $logger, 'chunk' => $chunk, 'xpath_prefix' => $xpath_prefix); $parse_functions = apply_filters('wp_all_import_addon_parse', array()); foreach (PMXI_Admin_Addons::get_active_addons() as $class) { $model_class = str_replace("_Plugin", "_Import_Record", $class); if (class_exists($model_class)) { $addons[$class] = new $model_class(); $addons_data[$class] = method_exists($addons[$class], 'parse') ? $addons[$class]->parse($parsingData) : false; } else { if (!empty($parse_functions[$class])) { if (is_array($parse_functions[$class]) and is_callable($parse_functions[$class]) or !is_array($parse_functions[$class]) and function_exists($parse_functions[$class])) { $addons_data[$class] = call_user_func($parse_functions[$class], $parsingData); } } } } // save current import state to variables before import $created = $this->created; $updated = $this->updated; $skipped = $this->skipped; $specified_records = array(); $simpleXml = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); $rootNodes = $simpleXml->xpath($cxpath); if ($this->options['is_import_specified']) { $chunk == 1 and $logger and call_user_func($logger, __('Calculate specified records to import...', 'wp_all_import_plugin')); $import_specified_option = apply_filters('wp_all_import_specified_records', $this->options['import_specified'], $this->id, $rootNodes); foreach (preg_split('% *, *%', $import_specified_option, -1, PREG_SPLIT_NO_EMPTY) as $chank) { if (preg_match('%^(\\d+)-(\\d+)$%', $chank, $mtch)) { $specified_records = array_merge($specified_records, range(intval($mtch[1]), intval($mtch[2]))); } else { $specified_records = array_merge($specified_records, array(intval($chank))); } } } foreach ($titles as $i => $void) { $custom_type_details = get_post_type_object($post_type[$i]); if ($is_cron and $cron_sleep) { sleep($cron_sleep); } $logger and call_user_func($logger, __('---', 'wp_all_import_plugin')); $logger and call_user_func($logger, sprintf(__('Record #%s', 'wp_all_import_plugin'), $this->imported + $this->skipped + $i + 1)); if ("manual" == $this->options['duplicate_matching'] and !empty($specified_records) and !in_array($created + $updated + $skipped + 1, $specified_records)) { $skipped++; $logger and call_user_func($logger, __('<b>SKIPPED</b>: by specified records option', 'wp_all_import_plugin')); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++; $logger and !$is_cron and PMXI_Plugin::$session->save_data(); continue; } wp_cache_flush(); $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_before_post_import ...', 'wp_all_import_plugin')); do_action('pmxi_before_post_import', $this->id); if (empty($titles[$i])) { if (!empty($addons_data['PMWI_Plugin']) and !empty($addons_data['PMWI_Plugin']['single_product_parent_ID'][$i])) { $titles[$i] = $addons_data['PMWI_Plugin']['single_product_parent_ID'][$i] . ' Product Variation'; } else { $logger and call_user_func($logger, __('<b>WARNING</b>: title is empty.', 'wp_all_import_plugin')); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } } if ($this->options['custom_type'] == 'import_users') { $articleData = array('user_pass' => $addons_data['PMUI_Plugin']['pmui_pass'][$i], 'user_login' => $addons_data['PMUI_Plugin']['pmui_logins'][$i], 'user_nicename' => $addons_data['PMUI_Plugin']['pmui_nicename'][$i], 'user_url' => $addons_data['PMUI_Plugin']['pmui_url'][$i], 'user_email' => $addons_data['PMUI_Plugin']['pmui_email'][$i], 'display_name' => $addons_data['PMUI_Plugin']['pmui_display_name'][$i], 'user_registered' => $addons_data['PMUI_Plugin']['pmui_registered'][$i], 'first_name' => $addons_data['PMUI_Plugin']['pmui_first_name'][$i], 'last_name' => $addons_data['PMUI_Plugin']['pmui_last_name'][$i], 'description' => $addons_data['PMUI_Plugin']['pmui_description'][$i], 'nickname' => $addons_data['PMUI_Plugin']['pmui_nickname'][$i], 'role' => '' == $addons_data['PMUI_Plugin']['pmui_role'][$i] ? 'subscriber' : strtolower($addons_data['PMUI_Plugin']['pmui_role'][$i])); $logger and call_user_func($logger, sprintf(__('Combine all data for user %s...', 'wp_all_import_plugin'), $articleData['user_login'])); } else { $articleData = array('post_type' => $post_type[$i], 'post_status' => "xpath" == $this->options['status'] ? $post_status[$i] : $this->options['status'], 'comment_status' => "xpath" == $this->options['comment_status'] ? $comment_status[$i] : $this->options['comment_status'], 'ping_status' => "xpath" == $this->options['ping_status'] ? $ping_status[$i] : $this->options['ping_status'], 'post_title' => !empty($this->options['is_leave_html']) ? html_entity_decode($titles[$i]) : $titles[$i], 'post_excerpt' => apply_filters('pmxi_the_excerpt', !empty($this->options['is_leave_html']) ? html_entity_decode($post_excerpt[$i]) : $post_excerpt[$i], $this->id), 'post_name' => $post_slug[$i], 'post_content' => apply_filters('pmxi_the_content', !empty($this->options['is_leave_html']) ? html_entity_decode($contents[$i]) : $contents[$i], $this->id), 'post_date' => $dates[$i], 'post_date_gmt' => get_gmt_from_date($dates[$i]), 'post_author' => $post_author[$i], 'menu_order' => (int) $menu_order[$i], 'post_parent' => "no" == $this->options['is_multiple_page_parent'] ? (int) $page_parent[$i] : (int) $this->options['parent']); $logger and call_user_func($logger, sprintf(__('Combine all data for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title'])); } // Re-import Records Matching $post_to_update = false; $post_to_update_id = false; // An array representation of current XML node $current_xml_node = wp_all_import_xml2array($rootNodes[$i]); $check_for_duplicates = apply_filters('wp_all_import_is_check_duplicates', true, $this->id); if ($check_for_duplicates) { // if Auto Matching re-import option selected if ("manual" != $this->options['duplicate_matching']) { // find corresponding article among previously imported $logger and call_user_func($logger, sprintf(__('Find corresponding article among previously imported for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title'])); $postRecord->clear(); $postRecord->getBy(array('unique_key' => $unique_keys[$i], 'import_id' => $this->id)); if (!$postRecord->isEmpty()) { $logger and call_user_func($logger, sprintf(__('Duplicate post was found for post %s with unique key `%s`...', 'wp_all_import_plugin'), $articleData['post_title'], $unique_keys[$i])); if ($this->options['custom_type'] == 'import_users') { $post_to_update = get_user_by('id', $post_to_update_id = $postRecord->post_id); } else { $post_to_update = get_post($post_to_update_id = $postRecord->post_id); } } else { $logger and call_user_func($logger, sprintf(__('Duplicate post wasn\'t found with unique key `%s`...', 'wp_all_import_plugin'), $unique_keys[$i])); } // if Manual Matching re-import option seleted } else { if ('custom field' == $this->options['duplicate_indicator']) { $custom_duplicate_value = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_value'], $file)->parse($records); $tmp_files[] = $file; $custom_duplicate_name = XmlImportParser::factory($xml, $cxpath, $this->options['custom_duplicate_name'], $file)->parse($records); $tmp_files[] = $file; } else { count($titles) and $custom_duplicate_name = $custom_duplicate_value = array_fill(0, count($titles), ''); } $logger and call_user_func($logger, sprintf(__('Find corresponding article among database for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title'])); if ('pid' == $this->options['duplicate_indicator']) { $duplicate_id = $post_ids[$i]; } else { $duplicates = pmxi_findDuplicates($articleData, $custom_duplicate_name[$i], $custom_duplicate_value[$i], $this->options['duplicate_indicator']); $duplicate_id = !empty($duplicates) ? array_shift($duplicates) : false; } if (!empty($duplicate_id)) { $logger and call_user_func($logger, sprintf(__('Duplicate post was found for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title'])); if ($this->options['custom_type'] == 'import_users') { $post_to_update = get_user_by('id', $post_to_update_id = $duplicate_id); } else { $post_to_update = get_post($post_to_update_id = $duplicate_id); } } else { $logger and call_user_func($logger, sprintf(__('Duplicate post wasn\'t found for post `%s`...', 'wp_all_import_plugin'), $articleData['post_title'])); } } } if (!empty($specified_records)) { if (!in_array($created + $updated + $skipped + 1, $specified_records)) { if (!$postRecord->isEmpty()) { $postRecord->set(array('iteration' => $this->iteration))->update(); } $skipped++; $logger and call_user_func($logger, __('<b>SKIPPED</b>: by specified records option', 'wp_all_import_plugin')); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++; $logger and !$is_cron and PMXI_Plugin::$session->save_data(); continue; } } $missing_images = array(); // Duplicate record is found if ($post_to_update) { $continue_import = true; $continue_import = apply_filters('wp_all_import_is_post_to_update', $post_to_update_id, $current_xml_node, $this->id); if (!$continue_import) { if (!$postRecord->isEmpty()) { $postRecord->set(array('iteration' => $this->iteration))->update(); } $skipped++; $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: By filter wp_all_import_is_post_to_update `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++; $logger and !$is_cron and PMXI_Plugin::$session->save_data(); continue; } //$logger and call_user_func($logger, sprintf(__('Duplicate record is found for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); // Do not update already existing records option selected if ("yes" == $this->options['is_keep_former_posts']) { if (!$postRecord->isEmpty()) { $postRecord->set(array('iteration' => $this->iteration))->update(); } do_action('pmxi_do_not_update_existing', $post_to_update_id, $this->id, $this->iteration); $skipped++; $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: Previously imported record found for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++; $logger and !$is_cron and PMXI_Plugin::$session->save_data(); continue; } $articleData['ID'] = $post_to_update_id; // Choose which data to update if ($this->options['update_all_data'] == 'no') { if (!in_array($this->options['custom_type'], array('import_users'))) { // preserve date of already existing article when duplicate is found if (!$this->options['is_update_categories'] and (is_object_in_taxonomy($post_type[$i], 'category') or is_object_in_taxonomy($post_type[$i], 'post_tag')) or $this->options['is_update_categories'] and $this->options['update_categories_logic'] != "full_update") { $logger and call_user_func($logger, sprintf(__('Preserve taxonomies of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); $existing_taxonomies = array(); foreach (array_keys($taxonomies) as $tx_name) { $txes_list = get_the_terms($articleData['ID'], $tx_name); if (is_wp_error($txes_list)) { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to get current taxonomies for article #%d, updating with those read from XML file', 'wp_all_import_plugin'), $articleData['ID'])); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } else { $txes_new = array(); if (!empty($txes_list)) { foreach ($txes_list as $t) { $txes_new[] = $t->term_taxonomy_id; } } $existing_taxonomies[$tx_name][$i] = $txes_new; } } } if (!$this->options['is_update_dates']) { // preserve date of already existing article when duplicate is found $articleData['post_date'] = $post_to_update->post_date; $articleData['post_date_gmt'] = $post_to_update->post_date_gmt; $logger and call_user_func($logger, sprintf(__('Preserve date of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_status']) { // preserve status and trashed flag $articleData['post_status'] = $post_to_update->post_status; $logger and call_user_func($logger, sprintf(__('Preserve status of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_content']) { $articleData['post_content'] = $post_to_update->post_content; $logger and call_user_func($logger, sprintf(__('Preserve content of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_title']) { $articleData['post_title'] = $post_to_update->post_title; $logger and call_user_func($logger, sprintf(__('Preserve title of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_slug']) { $articleData['post_name'] = $post_to_update->post_name; $logger and call_user_func($logger, sprintf(__('Preserve slug of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } // Check for changed slugs for published post objects and save the old slug. if (!empty($articleData['post_name']) and $articleData['post_name'] != $post_to_update->post_name) { $old_slugs = (array) get_post_meta($post_to_update_id, '_wp_old_slug'); // If we haven't added this old slug before, add it now. if (!empty($post_to_update->post_name) && !in_array($post_to_update->post_name, $old_slugs)) { add_post_meta($post_to_update_id, '_wp_old_slug', $post_to_update->post_name); } // If the new slug was used previously, delete it from the list. if (in_array($articleData['post_name'], $old_slugs)) { delete_post_meta($post_to_update_id, '_wp_old_slug', $articleData['post_name']); } } if (!$this->options['is_update_excerpt']) { $articleData['post_excerpt'] = $post_to_update->post_excerpt; $logger and call_user_func($logger, sprintf(__('Preserve excerpt of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_menu_order']) { $articleData['menu_order'] = $post_to_update->menu_order; $logger and call_user_func($logger, sprintf(__('Preserve menu order of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_parent']) { $articleData['post_parent'] = $post_to_update->post_parent; $logger and call_user_func($logger, sprintf(__('Preserve post parent of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_comment_status']) { $articleData['comment_status'] = $post_to_update->comment_status; $logger and call_user_func($logger, sprintf(__('Preserve comment status of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } if (!$this->options['is_update_author']) { $articleData['post_author'] = $post_to_update->post_author; $logger and call_user_func($logger, sprintf(__('Preserve post author of already existing article for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); } } else { if (!$this->options['is_update_first_name']) { $articleData['first_name'] = $post_to_update->first_name; } if (!$this->options['is_update_last_name']) { $articleData['last_name'] = $post_to_update->last_name; } if (!$this->options['is_update_role']) { unset($articleData['role']); } if (!$this->options['is_update_nickname']) { $articleData['nickname'] = get_user_meta($post_to_update->ID, 'nickname', true); } if (!$this->options['is_update_description']) { $articleData['description'] = get_user_meta($post_to_update->ID, 'description', true); } if (!$this->options['is_update_login']) { $articleData['user_login'] = $post_to_update->user_login; } if (!$this->options['is_update_password']) { unset($articleData['user_pass']); } if (!$this->options['is_update_nicename']) { $articleData['user_nicename'] = $post_to_update->user_nicename; } if (!$this->options['is_update_email']) { $articleData['user_email'] = $post_to_update->user_email; } if (!$this->options['is_update_registered']) { $articleData['user_registered'] = $post_to_update->user_registered; } if (!$this->options['is_update_display_name']) { $articleData['display_name'] = $post_to_update->display_name; } if (!$this->options['is_update_url']) { $articleData['user_url'] = $post_to_update->user_url; } } } if (!in_array($this->options['custom_type'], array('import_users'))) { $is_images_to_delete = apply_filters('pmxi_delete_images', true, $articleData, $current_xml_node); if ($is_images_to_delete) { if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_attachments']) { $logger and call_user_func($logger, sprintf(__('Deleting attachments for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); wp_delete_attachments($articleData['ID'], true, 'files'); } // handle obsolete attachments (i.e. delete or keep) according to import settings if ($this->options['update_all_data'] == 'yes' or $this->options['update_all_data'] == 'no' and $this->options['is_update_images'] and $this->options['update_images_logic'] == "full_update") { $logger and call_user_func($logger, sprintf(__('Deleting images for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); $do_not_remove_images = ($this->options['download_images'] == 'gallery' or $this->options['do_not_remove_images']) ? false : true; $missing_images = wp_delete_attachments($articleData['ID'], $do_not_remove_images, 'images'); } } } } elseif (!$postRecord->isEmpty()) { // existing post not found though it's track was found... clear the leftover, plugin will continue to treat record as new $postRecord->clear(); } $logger and call_user_func($logger, sprintf(__('Applying filter `pmxi_article_data` for `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); $articleData = apply_filters('pmxi_article_data', $articleData, $this, $post_to_update); // no new records are created. it will only update posts it finds matching duplicates for if (!$this->options['create_new_records'] and empty($articleData['ID'])) { if (!$postRecord->isEmpty()) { $postRecord->set(array('iteration' => $this->iteration))->update(); } $logger and call_user_func($logger, __('<b>SKIPPED</b>: by do not create new posts option.', 'wp_all_import_plugin')); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++; $skipped++; $logger and !$is_cron and PMXI_Plugin::$session->save_data(); continue; } // cloak urls with `WP Wizard Cloak` if corresponding option is set if (!empty($this->options['is_cloak']) and class_exists('PMLC_Plugin')) { if (preg_match_all('%<a\\s[^>]*href=(?(?=")"([^"]*)"|(?(?=\')\'([^\']*)\'|([^\\s>]*)))%is', $articleData['post_content'], $matches, PREG_PATTERN_ORDER)) { $hrefs = array_unique(array_merge(array_filter($matches[1]), array_filter($matches[2]), array_filter($matches[3]))); foreach ($hrefs as $url) { if (preg_match('%^\\w+://%i', $url)) { // mask only links having protocol // try to find matching cloaked link among already registered ones $list = new PMLC_Link_List(); $linkTable = $list->getTable(); $rule = new PMLC_Rule_Record(); $ruleTable = $rule->getTable(); $dest = new PMLC_Destination_Record(); $destTable = $dest->getTable(); $list->join($ruleTable, "{$ruleTable}.link_id = {$linkTable}.id")->join($destTable, "{$destTable}.rule_id = {$ruleTable}.id")->setColumns("{$linkTable}.*")->getBy(array("{$linkTable}.destination_type =" => 'ONE_SET', "{$linkTable}.is_trashed =" => 0, "{$linkTable}.preset =" => '', "{$linkTable}.expire_on =" => '0000-00-00', "{$ruleTable}.type =" => 'ONE_SET', "{$destTable}.weight =" => 100, "{$destTable}.url LIKE" => $url), NULL, 1, 1)->convertRecords(); if ($list->count()) { // matching link found $link = $list[0]; } else { // register new cloaked link global $wpdb; $slug = max(intval($wpdb->get_var("SELECT MAX(CONVERT(name, SIGNED)) FROM {$linkTable}")), intval($wpdb->get_var("SELECT MAX(CONVERT(slug, SIGNED)) FROM {$linkTable}")), 0); $i = 0; do { is_int(++$slug) and $slug > 0 or $slug = 1; $is_slug_found = !intval($wpdb->get_var("SELECT COUNT(*) FROM {$linkTable} WHERE name = '{$slug}' OR slug = '{$slug}'")); } while (!$is_slug_found and $i++ < 100000); if ($is_slug_found) { $link = new PMLC_Link_Record(array('name' => strval($slug), 'slug' => strval($slug), 'header_tracking_code' => '', 'footer_tracking_code' => '', 'redirect_type' => '301', 'destination_type' => 'ONE_SET', 'preset' => '', 'forward_url_params' => 1, 'no_global_tracking_code' => 0, 'expire_on' => '0000-00-00', 'created_on' => date('Y-m-d H:i:s'), 'is_trashed' => 0)); $link->insert(); $rule = new PMLC_Rule_Record(array('link_id' => $link->id, 'type' => 'ONE_SET', 'rule' => '')); $rule->insert(); $dest = new PMLC_Destination_Record(array('rule_id' => $rule->id, 'url' => $url, 'weight' => 100)); $dest->insert(); } else { $logger and call_user_func($logger, sprintf(__('<b>WARNING</b>: Unable to create cloaked link for %s', 'wp_all_import_plugin'), $url)); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $link = NULL; } } if ($link) { // cloaked link is found or created for url $articleData['post_content'] = preg_replace('%' . preg_quote($url, '%') . '(?=([\\s\'"]|$))%i', $link->getUrl(), $articleData['post_content']); } } } } } // insert article being imported if ($this->options['is_fast_mode']) { foreach (array('transition_post_status', 'save_post', 'pre_post_update', 'add_attachment', 'edit_attachment', 'edit_post', 'post_updated', 'wp_insert_post', 'save_post_' . $post_type[$i]) as $act) { remove_all_actions($act); } } if (empty($articleData['ID'])) { $continue_import = true; $continue_import = apply_filters('wp_all_import_is_post_to_create', $current_xml_node, $this->id); if (!$continue_import) { $skipped++; $logger and call_user_func($logger, sprintf(__('<b>SKIPPED</b>: By filter wp_all_import_is_post_to_create `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++; $logger and !$is_cron and PMXI_Plugin::$session->save_data(); continue; } } if (!in_array($this->options['custom_type'], array('import_users'))) { if (empty($articleData['ID'])) { $logger and call_user_func($logger, sprintf(__('<b>CREATING</b> `%s` `%s`', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name)); } else { $logger and call_user_func($logger, sprintf(__('<b>UPDATING</b> `%s` `%s`', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name)); } $pid = empty($articleData['ID']) ? wp_insert_post($articleData, true) : wp_update_post($articleData, true); } else { $pid = empty($articleData['ID']) ? wp_insert_user($articleData) : wp_update_user($articleData); $articleData['post_title'] = $articleData['user_login']; } if (empty($pid)) { $logger and call_user_func($logger, __('<b>ERROR</b>', 'wp_all_import_plugin') . ': something wrong, ID = 0 was generated.'); $logger and !$is_cron and PMXI_Plugin::$session->errors++; $skipped++; } elseif (is_wp_error($pid)) { $logger and call_user_func($logger, __('<b>ERROR</b>', 'wp_all_import_plugin') . ': ' . $pid->get_error_message()); $logger and !$is_cron and PMXI_Plugin::$session->errors++; $skipped++; } else { if ("manual" != $this->options['duplicate_matching'] or empty($articleData['ID'])) { // associate post with import $postRecord->isEmpty() and $postRecord->set(array('post_id' => $pid, 'import_id' => $this->id, 'unique_key' => $unique_keys[$i], 'product_key' => ($post_type[$i] == "product" and PMXI_Admin_Addons::get_addon('PMWI_Plugin')) ? $addons_data['PMWI_Plugin']['single_product_ID'][$i] : ''))->insert(); $postRecord->set(array('iteration' => $this->iteration, 'specified' => empty($specified_records) ? 0 : 1))->update(); $logger and call_user_func($logger, sprintf(__('Associate post `%s` with current import ...', 'wp_all_import_plugin'), $articleData['post_title'])); } // [post format] if (current_theme_supports('post-formats') && post_type_supports($post_type[$i], 'post-formats')) { set_post_format($pid, "xpath" == $this->options['post_format'] ? $post_format[$i] : $this->options['post_format']); $logger and call_user_func($logger, sprintf(__('Associate post `%s` with post format %s ...', 'wp_all_import_plugin'), $articleData['post_title'], "xpath" == $this->options['post_format'] ? $post_format[$i] : $this->options['post_format'])); } // [/post format] // [addons import] // prepare data for import $importData = array('pid' => $pid, 'i' => $i, 'import' => $this, 'articleData' => $articleData, 'xml' => $xml, 'is_cron' => $is_cron, 'logger' => $logger, 'xpath_prefix' => $xpath_prefix, 'post_type' => $post_type[$i]); $import_functions = apply_filters('wp_all_import_addon_import', array()); // deligate operation to addons foreach (PMXI_Admin_Addons::get_active_addons() as $class) { if (class_exists($class)) { if (method_exists($addons[$class], 'import')) { $addons[$class]->import($importData); } } else { if (!empty($import_functions[$class])) { if (is_array($import_functions[$class]) and is_callable($import_functions[$class]) or !is_array($import_functions[$class]) and function_exists($import_functions[$class])) { call_user_func($import_functions[$class], $importData, $addons_data[$class]); } } } } // [/addons import] // Page Template if (!empty($articleData['post_type']) and 'page' == $articleData['post_type'] and wp_all_import_is_update_cf('_wp_page_template', $this->options) and (!empty($this->options['page_template']) or "no" == $this->options['is_multiple_page_template'])) { update_post_meta($pid, '_wp_page_template', "no" == $this->options['is_multiple_page_template'] ? $page_template[$i] : $this->options['page_template']); } // [featured image] $is_images_to_update = apply_filters('pmxi_is_images_to_update', true, $articleData, $current_xml_node); $is_allow_import_images = apply_filters('wp_all_import_is_allow_import_images', false, empty($articleData['post_type']) ? '' : $articleData['post_type']); if ($is_images_to_update and !empty($uploads) and false === $uploads['error'] and (!empty($articleData['post_type']) and $articleData['post_type'] == "product" and class_exists('PMWI_Plugin') or $is_allow_import_images) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_images'])) { if (!empty($images_bundle)) { require_once ABSPATH . 'wp-admin/includes/image.php'; $is_show_add_new_images = apply_filters('wp_all_import_is_show_add_new_images', true, $post_type[$i]); foreach ($images_bundle as $slug => $bundle_data) { $featured_images = $bundle_data['files']; $option_slug = $slug == 'pmxi_gallery_image' ? '' : $slug; $gallery_attachment_ids = array(); if (!empty($featured_images[$i])) { $targetDir = $uploads['path']; $targetUrl = $uploads['url']; $logger and call_user_func($logger, __('<b>IMAGES:</b>', 'wp_all_import_plugin')); if (!@is_writable($targetDir)) { $logger and call_user_func($logger, sprintf(__('<b>ERROR</b>: Target directory %s is not writable', 'wp_all_import_plugin'), $targetDir)); } else { $success_images = false; $imgs = array(); switch ($this->options[$option_slug . 'download_images']) { case 'no': $featured_delim = $this->options[$option_slug . 'featured_delim']; break; case 'gallery': $featured_delim = $this->options[$option_slug . 'gallery_featured_delim']; break; default: // yes $featured_delim = $this->options[$option_slug . 'download_featured_delim']; break; } $line_imgs = explode("\n", $featured_images[$i]); if (!empty($line_imgs)) { foreach ($line_imgs as $line_img) { $imgs = array_merge($imgs, !empty($featured_delim) ? str_getcsv($line_img, $featured_delim) : array($line_img)); } } // keep existing and add newest images if (!empty($articleData['ID']) and $this->options['is_update_images'] and $this->options['update_images_logic'] == "add_new" and $this->options['update_all_data'] == "no" and $is_show_add_new_images) { $logger and call_user_func($logger, __('- Keep existing and add newest images ...', 'wp_all_import_plugin')); $attachment_imgs = get_attached_media('image', $pid); if ($post_type[$i] == "product") { $gallery_attachment_ids = array_filter(explode(",", get_post_meta($pid, '_product_image_gallery', true))); } if ($attachment_imgs) { foreach ($attachment_imgs as $attachment_img) { $post_thumbnail_id = get_post_thumbnail_id($pid); if (empty($post_thumbnail_id) and $this->options[$option_slug . 'is_featured']) { set_post_thumbnail($pid, $attachment_img->ID); } elseif (!in_array($attachment_img->ID, $gallery_attachment_ids) and $post_thumbnail_id != $attachment_img->ID) { $gallery_attachment_ids[] = $attachment_img->ID; } } $success_images = true; } if (!empty($gallery_attachment_ids)) { foreach ($gallery_attachment_ids as $aid) { do_action($slug, $pid, $aid, wp_get_attachment_url($aid), 'update_images'); } } } if (!empty($imgs)) { if ($this->options[$option_slug . 'set_image_meta_title'] and !empty($image_meta_titles_bundle[$slug])) { $img_titles = array(); $line_img_titles = explode("\n", $image_meta_titles_bundle[$slug][$i]); if (!empty($line_img_titles)) { foreach ($line_img_titles as $line_img_title) { $img_titles = array_merge($img_titles, !empty($this->options[$option_slug . 'image_meta_title_delim']) ? str_getcsv($line_img_title, $this->options[$option_slug . 'image_meta_title_delim']) : array($line_img_title)); } } } if ($this->options[$option_slug . 'set_image_meta_caption'] and !empty($image_meta_captions_bundle[$slug])) { $img_captions = array(); $line_img_captions = explode("\n", $image_meta_captions_bundle[$slug][$i]); if (!empty($line_img_captions)) { foreach ($line_img_captions as $line_img_caption) { $img_captions = array_merge($img_captions, !empty($this->options[$option_slug . 'image_meta_caption_delim']) ? str_getcsv($line_img_caption, $this->options[$option_slug . 'image_meta_caption_delim']) : array($line_img_caption)); } } } if ($this->options[$option_slug . 'set_image_meta_alt'] and !empty($image_meta_alts_bundle[$slug])) { $img_alts = array(); $line_img_alts = explode("\n", $image_meta_alts_bundle[$slug][$i]); if (!empty($line_img_alts)) { foreach ($line_img_alts as $line_img_alt) { $img_alts = array_merge($img_alts, !empty($this->options[$option_slug . 'image_meta_alt_delim']) ? str_getcsv($line_img_alt, $this->options[$option_slug . 'image_meta_alt_delim']) : array($line_img_alt)); } } } if ($this->options[$option_slug . 'set_image_meta_description'] and !empty($image_meta_descriptions_bundle[$slug])) { $img_descriptions = array(); $line_img_descriptions = ($this->options[$option_slug . 'image_meta_description_delim_logic'] == 'line' or empty($this->options[$option_slug . 'image_meta_description_delim'])) ? explode("\n", $image_meta_descriptions_bundle[$slug][$i]) : array($image_meta_descriptions_bundle[$slug][$i]); if (!empty($line_img_descriptions)) { foreach ($line_img_descriptions as $line_img_description) { $img_descriptions = array_merge($img_descriptions, ($this->options[$option_slug . 'image_meta_description_delim_logic'] == 'separate' and !empty($this->options[$option_slug . 'image_meta_description_delim'])) ? str_getcsv($line_img_description, $this->options[$option_slug . 'image_meta_description_delim']) : array($line_img_description)); } } } $is_keep_existing_images = (!empty($articleData['ID']) and $this->options['is_update_images'] and $this->options['update_images_logic'] == "add_new" and $this->options['update_all_data'] == "no" and $is_show_add_new_images); foreach ($imgs as $k => $img_url) { $attid = false; $attch = null; $url = trim($img_url); if (empty($url)) { continue; } $bn = wp_all_import_sanitize_filename(urldecode(basename($url))); if ("yes" == $this->options[$option_slug . 'download_images'] and !empty($auto_extensions_bundle[$slug][$i]) and preg_match('%^(jpg|jpeg|png|gif)$%i', $auto_extensions_bundle[$slug][$i])) { $img_ext = $auto_extensions_bundle[$slug][$i]; } else { $img_ext = pmxi_getExtensionFromStr($url); $default_extension = pmxi_getExtension($bn); if ($img_ext == "") { $img_ext = pmxi_get_remote_image_ext($url); } } $logger and call_user_func($logger, sprintf(__('- Importing image `%s` for `%s` ...', 'wp_all_import_plugin'), $img_url, $articleData['post_title'])); // generate local file name $image_name = urldecode(($this->options[$option_slug . 'auto_rename_images'] and !empty($auto_rename_images_bundle[$slug][$i])) ? sanitize_file_name($img_ext ? str_replace("." . $default_extension, "", $auto_rename_images_bundle[$slug][$i]) : $auto_rename_images_bundle[$slug][$i]) : sanitize_file_name($img_ext ? str_replace("." . $default_extension, "", $bn) : $bn)) . ("" != $img_ext ? '.' . $img_ext : ''); $image_name = apply_filters("wp_all_import_image_filename", $image_name, empty($img_titles[$k]) ? '' : $img_titles[$k], empty($img_captions[$k]) ? '' : $img_captions[$k], empty($img_alts[$k]) ? '' : $img_alts[$k], $articleData); // if wizard store image data to custom field $create_image = false; $download_image = true; $wp_filetype = false; if ($bundle_data['type'] == 'images' and base64_decode($url, true) !== false) { $img = @imagecreatefromstring(base64_decode($url)); if ($img) { $logger and call_user_func($logger, __('- found base64_encoded image', 'wp_all_import_plugin')); $image_filename = md5(time()) . '.jpg'; $image_filepath = $targetDir . '/' . $image_filename; imagejpeg($img, $image_filepath); if (!($image_info = apply_filters('pmxi_getimagesize', @getimagesize($image_filepath), $image_filepath)) or !in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath)); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } else { $create_image = true; } } } if (!$create_image) { if ($this->options[$option_slug . 'auto_rename_images'] and !empty($auto_rename_images_bundle[$slug][$i])) { if ($k) { $image_name = str_replace('.' . pmxi_getExtension($image_name), '', $image_name) . '-' . $k . '.' . pmxi_getExtension($image_name); } } $image_filename = wp_unique_filename($targetDir, $image_name); $image_filepath = $targetDir . '/' . $image_filename; // keep existing and add newest images if ($is_keep_existing_images) { $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s) AND post_type = %s AND post_parent = %d;", $image_name, preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_name), sanitize_title($image_name), "attachment", $pid)); if ($attch != null) { $post_thumbnail_id = get_post_thumbnail_id($pid); if ($post_thumbnail_id == $attch->ID or in_array($attch->ID, $gallery_attachment_ids)) { continue; } } elseif (file_exists($targetDir . '/' . $image_name)) { if ($bundle_data['type'] == 'images' and $img_meta = wp_read_image_metadata($targetDir . '/' . $image_name)) { if (trim($img_meta['title']) && !is_numeric(sanitize_title($img_meta['title']))) { $img_title = $img_meta['title']; $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE post_title = %s AND post_type = %s AND post_parent = %d;", $img_title, "attachment", $pid)); if ($attch != null) { $post_thumbnail_id = get_post_thumbnail_id($pid); if ($post_thumbnail_id == $attch->ID or in_array($attch->ID, $gallery_attachment_ids)) { continue; } } } } } } // search existing attachment if ($this->options[$option_slug . 'search_existing_images'] or "gallery" == $this->options[$option_slug . 'download_images']) { $image_filename = $image_name; $attch = wp_all_import_get_image_from_gallery($image_name, $targetDir, $bundle_data['type']); if ("gallery" == $this->options[$option_slug . 'download_images']) { $download_image = false; } if (empty($attch)) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Image %s not found in media gallery.', 'wp_all_import_plugin'), trim($image_name))); } else { $logger and call_user_func($logger, sprintf(__('- Using existing image `%s` for post `%s` ...', 'wp_all_import_plugin'), trim($image_name), $articleData['post_title'])); $download_image = false; $create_image = false; $attid = $attch->ID; } } if ($download_image && "gallery" != $this->options[$option_slug . 'download_images']) { // do not download images if ("no" == $this->options[$option_slug . 'download_images']) { $image_filename = $image_name; $image_filepath = $targetDir . '/' . $image_filename; $wpai_uploads = $uploads['basedir'] . DIRECTORY_SEPARATOR . PMXI_Plugin::FILES_DIRECTORY . DIRECTORY_SEPARATOR; $wpai_image_path = $wpai_uploads . str_replace('%20', ' ', $url); $logger and call_user_func($logger, sprintf(__('- Searching for existing image `%s` in `%s` folder', 'wp_all_import_plugin'), $wpai_image_path, $wpai_uploads)); if (@file_exists($wpai_image_path) and @copy($wpai_image_path, $image_filepath)) { $download_image = false; // valdate import attachments if ($bundle_data['type'] == 'files') { if (!($wp_filetype = wp_check_filetype(basename($image_filepath), null))) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($image_filepath))); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; @unlink($image_filepath); } else { $create_image = true; $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully found', 'wp_all_import_plugin'), $wpai_image_path)); } } elseif ($bundle_data['type'] == 'images') { if (preg_match('%\\W(svg)$%i', basename($image_filepath)) or $image_info = apply_filters('pmxi_getimagesize', @getimagesize($image_filepath), $image_filepath) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $create_image = true; $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully found', 'wp_all_import_plugin'), $wpai_image_path)); } else { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $image_filepath)); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; @unlink($image_filepath); } } } } else { $logger and call_user_func($logger, sprintf(__('- Downloading image from `%s`', 'wp_all_import_plugin'), $url)); $request = get_file_curl($url, $image_filepath); $get_ctx = stream_context_create(array('http' => array('timeout' => 5))); if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url, false, $get_ctx))) { @unlink($image_filepath); // delete file since failed upload may result in empty file created } else { if ($bundle_data['type'] == 'images') { if (preg_match('%\\W(svg)$%i', basename($image_filepath)) or $image_info = apply_filters('pmxi_getimagesize', @getimagesize($image_filepath), $image_filepath) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $create_image = true; $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url)); } else { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $url)); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } } elseif ($bundle_data['type'] == 'files') { if ($wp_filetype = wp_check_filetype(basename($image_filepath), null)) { $create_image = true; $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url)); } } } if (!$create_image and $img_url !== pmxi_convert_encoding($img_url)) { $url = trim(pmxi_convert_encoding($img_url)); $request = get_file_curl($url, $image_filepath); $get_ctx = stream_context_create(array('http' => array('timeout' => 5))); if ((is_wp_error($request) or $request === false) and !@file_put_contents($image_filepath, @file_get_contents($url, false, $get_ctx))) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s cannot be saved locally as %s', 'wp_all_import_plugin'), $url, $image_filepath)); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; @unlink($image_filepath); // delete file since failed upload may result in empty file created } else { if ($bundle_data['type'] == 'images') { if (preg_match('%\\W(svg)$%i', basename($image_filepath)) or $image_info = apply_filters('pmxi_getimagesize', @getimagesize($image_filepath), $image_filepath) and in_array($image_info[2], array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG))) { $create_image = true; $logger and call_user_func($logger, sprintf(__('- Image `%s` has been successfully downloaded', 'wp_all_import_plugin'), $url)); } else { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: File %s is not a valid image and cannot be set as featured one', 'wp_all_import_plugin'), $url)); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; @unlink($image_filepath); } } elseif ($bundle_data['type'] == 'files') { if (!($wp_filetype = wp_check_filetype(basename($image_filepath), null))) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($url))); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; @unlink($image_filepath); } else { $create_image = true; $logger and call_user_func($logger, sprintf(__('- File `%s` has been successfully found', 'wp_all_import_plugin'), $url)); } } } } } } } $handle_image = false; if ($create_image) { $file_mime_type = ''; if ($bundle_data['type'] == 'images') { if (!empty($image_info)) { $file_mime_type = image_type_to_mime_type($image_info[2]); } $file_mime_type = apply_filters('wp_all_import_image_mime_type', $file_mime_type, $image_filepath); } else { $file_mime_type = $wp_filetype['type']; } $handle_image = array('file' => $image_filepath, 'url' => $targetUrl . '/' . $image_filename, 'type' => $file_mime_type); //apply_filters( 'wp_handle_upload', , 'upload' ); $logger and call_user_func($logger, sprintf(__('- Creating an attachment for image `%s`', 'wp_all_import_plugin'), $handle_image['url'])); $attachment_title = explode(".", $image_name); if (is_array($attachment_title) and count($attachment_title) > 1) { array_pop($attachment_title); } $attachment = array('post_mime_type' => $handle_image['type'], 'guid' => $handle_image['url'], 'post_title' => implode(".", $attachment_title), 'post_content' => '', 'post_author' => $post_author[$i]); if ($bundle_data['type'] == 'images' and $image_meta = wp_read_image_metadata($handle_image['file'])) { if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $attachment['post_title'] = $image_meta['title']; } if (trim($image_meta['caption'])) { $attachment['post_content'] = $image_meta['caption']; } } $attid = wp_insert_attachment($attachment, $handle_image['file'], $pid); if (is_wp_error($attid)) { $logger and call_user_func($logger, __('- <b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $attid->get_error_message()); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } else { wp_update_attachment_metadata($attid, wp_generate_attachment_metadata($attid, $handle_image['file'])); } } if ($attid and !is_wp_error($attid)) { if ($attch != null and empty($attch->post_parent)) { wp_update_post(array('ID' => $attch->ID, 'post_parent' => $pid)); } $update_attachment_meta = array(); if ($this->options[$option_slug . 'set_image_meta_title'] and !empty($img_titles[$k])) { $update_attachment_meta['post_title'] = trim($img_titles[$k]); } if ($this->options[$option_slug . 'set_image_meta_caption'] and !empty($img_captions[$k])) { $update_attachment_meta['post_excerpt'] = trim($img_captions[$k]); } if ($this->options[$option_slug . 'set_image_meta_description'] and !empty($img_descriptions[$k])) { $update_attachment_meta['post_content'] = trim($img_descriptions[$k]); } if ($this->options[$option_slug . 'set_image_meta_alt'] and !empty($img_alts[$k])) { update_post_meta($attid, '_wp_attachment_image_alt', trim($img_alts[$k])); } if (!empty($update_attachment_meta)) { $this->wpdb->update($this->wpdb->posts, $update_attachment_meta, array('ID' => $attid)); } $logger and call_user_func($logger, __('- <b>ACTION</b>: ' . $slug, 'wp_all_import_plugin')); do_action($slug, $pid, $attid, $handle_image ? $handle_image['file'] : $image_filepath, $is_keep_existing_images ? 'add_images' : 'update_images'); $success_images = true; $post_thumbnail_id = get_post_thumbnail_id($pid); if ($bundle_data['type'] == 'images' and empty($post_thumbnail_id) and $this->options[$option_slug . 'is_featured']) { set_post_thumbnail($pid, $attid); } elseif (!in_array($attid, $gallery_attachment_ids) and $post_thumbnail_id != $attid) { $gallery_attachment_ids[] = $attid; } if ($attch != null and empty($attch->post_parent)) { $logger and call_user_func($logger, sprintf(__('- Attachment has been successfully updated for image `%s`', 'wp_all_import_plugin'), $handle_image ? $handle_image['url'] : $targetUrl . '/' . $image_filename)); } elseif (empty($attch)) { $logger and call_user_func($logger, sprintf(__('- Attachment has been successfully created for image `%s`', 'wp_all_import_plugin'), $handle_image ? $handle_image['url'] : $targetUrl . '/' . $image_filename)); } } } } // Set product gallery images if ($post_type[$i] == "product") { update_post_meta($pid, '_product_image_gallery', !empty($gallery_attachment_ids) ? implode(',', $gallery_attachment_ids) : ''); } // Create entry as Draft if no images are downloaded successfully $final_post_type = get_post_type($pid); if (!$success_images and "yes" == $this->options[$option_slug . 'create_draft'] and $final_post_type != 'product_variation') { $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $pid)); $logger and call_user_func($logger, sprintf(__('- Post `%s` saved as Draft, because no images are downloaded successfully', 'wp_all_import_plugin'), $articleData['post_title'])); } } } else { // Create entry as Draft if no images are downloaded successfully $final_post_type = get_post_type($pid); if ("yes" == $this->options[$option_slug . 'create_draft'] and $final_post_type != 'product_variation') { $this->wpdb->update($this->wpdb->posts, array('post_status' => 'draft'), array('ID' => $pid)); $logger and call_user_func($logger, sprintf(__('Post `%s` saved as Draft, because no images are downloaded successfully', 'wp_all_import_plugin'), $articleData['post_title'])); } } if ($this->options["do_not_remove_images"]) { do_action("wpallimport_after_images_import", $pid, $gallery_attachment_ids, $missing_images); } } } } else { if (!empty($images_bundle)) { foreach ($images_bundle as $slug => $bundle_data) { if (!empty($bundle_data['images'][$i])) { $imgs = array(); $featured_delim = "yes" == $this->options[$option_slug . 'download_images'] ? $this->options[$option_slug . 'download_featured_delim'] : $this->options[$option_slug . 'featured_delim']; $line_imgs = explode("\n", $bundle_data['images'][$i]); if (!empty($line_imgs)) { foreach ($line_imgs as $line_img) { $imgs = array_merge($imgs, !empty($featured_delim) ? str_getcsv($line_img, $featured_delim) : array($line_img)); } } foreach ($imgs as $img) { do_action($slug, $pid, false, $img, false); } } } } } if (!$is_images_to_update) { $logger and call_user_func($logger, sprintf(__('Images import skipped for post `%s` according to \'pmxi_is_images_to_update\' filter...', 'wp_all_import_plugin'), $articleData['post_title'])); } // [/featured image] // [attachments] $is_attachments_to_update = apply_filters('pmxi_is_attachments_to_update', true, $articleData, $current_xml_node); if ($is_attachments_to_update and !empty($uploads) and false === $uploads['error'] and !empty($attachments[$i]) and (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_attachments'])) { $targetDir = $uploads['path']; $targetUrl = $uploads['url']; $logger and call_user_func($logger, __('<b>ATTACHMENTS:</b>', 'wp_all_import_plugin')); if (!@is_writable($targetDir)) { $logger and call_user_func($logger, sprintf(__('- <b>ERROR</b>: Target directory %s is not writable', 'wp_all_import_plugin'), trim($targetDir))); } else { // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once ABSPATH . 'wp-admin/includes/image.php'; if (!is_array($attachments[$i])) { $attachments[$i] = array($attachments[$i]); } $logger and call_user_func($logger, sprintf(__('- Importing attachments for `%s` ...', 'wp_all_import_plugin'), $articleData['post_title'])); foreach ($attachments[$i] as $attachment) { if ("" == $attachment) { continue; } $atchs = str_getcsv($attachment, $this->options['atch_delim']); if (!empty($atchs)) { foreach ($atchs as $atch_url) { if (empty($atch_url)) { continue; } $download_file = true; $atch_url = str_replace(" ", "%20", trim($atch_url)); $attachment_filename = urldecode(basename(parse_url(trim($atch_url), PHP_URL_PATH))); $attachment_filepath = $targetDir . '/' . sanitize_file_name($attachment_filename); if ($this->options['is_search_existing_attach']) { // search existing attachment $attch = $this->wpdb->get_row($this->wpdb->prepare("SELECT * FROM " . $this->wpdb->posts . " WHERE (post_title = %s OR post_title = %s OR post_name = %s OR post_name = %s) AND post_type = %s;", $attachment_filename, preg_replace('/\\.[^.\\s]{3,4}$/', '', $attachment_filename), sanitize_title($attachment_filename), sanitize_title(preg_replace('/\\.[^.\\s]{3,4}$/', '', $attachment_filename)), "attachment")); if ($attch != null) { $download_file = false; $attach_id = $attch->ID; } } if ($download_file) { $attachment_filename = wp_unique_filename($targetDir, $attachment_filename); $attachment_filepath = $targetDir . '/' . sanitize_file_name($attachment_filename); $logger and call_user_func($logger, sprintf(__('- Filename for attachment was generated as %s', 'wp_all_import_plugin'), $attachment_filename)); $request = get_file_curl(trim($atch_url), $attachment_filepath); $get_ctx = stream_context_create(array('http' => array('timeout' => 5))); if ((is_wp_error($request) or $request === false) and !@file_put_contents($attachment_filepath, @file_get_contents(trim($atch_url), false, $get_ctx))) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Attachment file %s cannot be saved locally as %s', 'wp_all_import_plugin'), trim($atch_url), $attachment_filepath)); is_wp_error($request) and $logger and call_user_func($logger, sprintf(__('- <b>WP Error</b>: %s', 'wp_all_import_plugin'), $request->get_error_message())); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; unlink($attachment_filepath); // delete file since failed upload may result in empty file created } elseif (!($wp_filetype = wp_check_filetype(basename($attachment_filename), null))) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: Can\'t detect attachment file type %s', 'wp_all_import_plugin'), trim($atch_url))); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } else { $handle_attachment = array('file' => $attachment_filepath, 'url' => $targetUrl . '/' . basename($attachment_filepath), 'type' => $wp_filetype['type']); //apply_filters( 'wp_handle_upload', , 'upload' ); $logger and call_user_func($logger, sprintf(__('- File %s has been successfully downloaded', 'wp_all_import_plugin'), $atch_url)); $attachment_data = array('guid' => $handle_attachment['url'], 'post_mime_type' => $handle_attachment['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($handle_attachment['file'])), 'post_content' => '', 'post_status' => 'inherit', 'post_author' => $post_author[$i]); $attach_id = wp_insert_attachment($attachment_data, $handle_attachment['file'], $pid); if (is_wp_error($attach_id)) { $logger and call_user_func($logger, __('- <b>WARNING</b>', 'wp_all_import_plugin') . ': ' . $pid->get_error_message()); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } else { wp_update_attachment_metadata($attach_id, wp_generate_attachment_metadata($attach_id, $handle_attachment['file'])); $logger and call_user_func($logger, sprintf(__('- Attachment has been successfully created for post `%s`', 'wp_all_import_plugin'), $articleData['post_title'])); $logger and call_user_func($logger, __('- <b>ACTION</b>: pmxi_attachment_uploaded', 'wp_all_import_plugin')); do_action('pmxi_attachment_uploaded', $pid, $attach_id, $handle_attachment['file']); } } } else { $logger and call_user_func($logger, __('- <b>ACTION</b>: pmxi_attachment_uploaded', 'wp_all_import_plugin')); do_action('pmxi_attachment_uploaded', $pid, $attach_id, $attachment_filepath); } } } } } } if (!$is_attachments_to_update) { $logger and call_user_func($logger, sprintf(__('Attachments import skipped for post `%s` according to \'pmxi_is_attachments_to_update\' filter...', 'wp_all_import_plugin'), $articleData['post_title'])); } // [/attachments] // [custom taxonomies] if (!empty($taxonomies)) { $logger and call_user_func($logger, __('<b>TAXONOMIES:</b>', 'wp_all_import_plugin')); foreach ($taxonomies as $tx_name => $txes) { // Skip updating product attributes if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) { continue; } if (empty($articleData['ID']) or $this->options['update_all_data'] == "yes" or $this->options['update_all_data'] == "no" and $this->options['is_update_categories']) { $logger and call_user_func($logger, sprintf(__('- Importing taxonomy `%s` ...', 'wp_all_import_plugin'), $tx_name)); if (!empty($this->options['tax_logic'][$tx_name]) and $this->options['tax_logic'][$tx_name] == 'hierarchical' and !empty($this->options['tax_hierarchical_logic'][$tx_name]) and $this->options['tax_hierarchical_logic'][$tx_name] == 'entire') { $logger and call_user_func($logger, sprintf(__('- Auto-nest enabled with separator `%s` ...', 'wp_all_import_plugin'), !empty($this->options['tax_hierarchical_delim'][$tx_name]) ? $this->options['tax_hierarchical_delim'][$tx_name] : ',')); } if (!empty($articleData['ID'])) { if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "all_except" and !empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and in_array($tx_name, $this->options['taxonomies_list'])) { $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Leave these taxonomies alone, update all others`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'])); continue; } if ($this->options['update_all_data'] == "no" and $this->options['update_categories_logic'] == "only" and (!empty($this->options['taxonomies_list']) and is_array($this->options['taxonomies_list']) and !in_array($tx_name, $this->options['taxonomies_list']) or empty($this->options['taxonomies_list']))) { $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Update only these taxonomies, leave the rest alone`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'])); continue; } } $assign_taxes = array(); if ($this->options['update_categories_logic'] == "add_new" and !empty($existing_taxonomies[$tx_name][$i])) { $assign_taxes = $existing_taxonomies[$tx_name][$i]; unset($existing_taxonomies[$tx_name][$i]); } elseif (!empty($existing_taxonomies[$tx_name][$i])) { unset($existing_taxonomies[$tx_name][$i]); } // create term if not exists if (!empty($txes[$i])) { foreach ($txes[$i] as $key => $single_tax) { $is_created_term = false; if (is_array($single_tax) and !empty($single_tax['name'])) { $parent_id = !empty($single_tax['parent']) ? pmxi_recursion_taxes($single_tax['parent'], $tx_name, $txes[$i], $key) : ''; $term = empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) ? is_exists_term($single_tax['name'], $tx_name, (int) $parent_id) : is_exists_term($single_tax['name'], $tx_name); if (empty($term) and !is_wp_error($term)) { $term = empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) ? is_exists_term(htmlspecialchars($single_tax['name']), $tx_name, (int) $parent_id) : is_exists_term(htmlspecialchars($single_tax['name']), $tx_name); if (empty($term) and !is_wp_error($term)) { $term_attr = array('parent' => !empty($parent_id) ? $parent_id : 0); $term = wp_insert_term($single_tax['name'], $tx_name, $term_attr); if (!is_wp_error($term)) { $is_created_term = true; if (empty($parent_id)) { $logger and call_user_func($logger, sprintf(__('- Creating parent %s %s `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'])); } else { $logger and call_user_func($logger, sprintf(__('- Creating child %s %s for %s named `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, is_array($single_tax['parent']) ? $single_tax['parent']['name'] : $single_tax['parent'], $single_tax['name'])); } } } } if (is_wp_error($term)) { $logger and call_user_func($logger, sprintf(__('- <b>WARNING</b>: `%s`', 'wp_all_import_plugin'), $term->get_error_message())); $logger and !$is_cron and PMXI_Plugin::$session->warnings++; } elseif (!empty($term)) { $cat_id = $term['term_id']; if ($cat_id and $single_tax['assign']) { $term = get_term_by('id', $cat_id, $tx_name); if ($term->parent != '0' and !empty($this->options['tax_is_full_search_' . $this->options['tax_logic'][$tx_name]][$tx_name]) and empty($this->options['tax_assign_to_one_term_' . $this->options['tax_logic'][$tx_name]][$tx_name])) { $parent_ids = wp_all_import_get_parent_terms($cat_id, $tx_name); if (!empty($parent_ids)) { foreach ($parent_ids as $p) { if (!in_array($p, $assign_taxes)) { $assign_taxes[] = $p; } } } } if (!in_array($term->term_taxonomy_id, $assign_taxes)) { $assign_taxes[] = $term->term_taxonomy_id; } if (!$is_created_term) { if (empty($parent_id)) { $logger and call_user_func($logger, sprintf(__('- Attempted to create parent %s %s `%s`, duplicate detected. Importing %s to existing `%s` %s, ID %d, slug `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'], $custom_type_details->labels->singular_name, $term->name, $tx_name, $term->term_id, $term->slug)); } else { $logger and call_user_func($logger, sprintf(__('- Attempted to create child %s %s `%s`, duplicate detected. Importing %s to existing `%s` %s, ID %d, slug `%s` ...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'], $custom_type_details->labels->singular_name, $term->name, $tx_name, $term->term_id, $term->slug)); } } } } } } } // associate taxes with post $this->associate_terms($pid, empty($assign_taxes) ? false : $assign_taxes, $tx_name, $logger, $is_cron); } else { $logger and call_user_func($logger, sprintf(__('- %s %s `%s` has been skipped attempted to `Do not update Taxonomies (incl. Categories and Tags)`...', 'wp_all_import_plugin'), $custom_type_details->labels->singular_name, $tx_name, $single_tax['name'])); } } if ($this->options['update_all_data'] == "no" and ($this->options['is_update_categories'] and $this->options['update_categories_logic'] != 'full_update' or !$this->options['is_update_categories'] and (is_object_in_taxonomy($post_type[$i], 'category') or is_object_in_taxonomy($post_type[$i], 'post_tag')))) { if (!empty($existing_taxonomies)) { foreach ($existing_taxonomies as $tx_name => $txes) { // Skip updating product attributes if (PMXI_Admin_Addons::get_addon('PMWI_Plugin') and strpos($tx_name, "pa_") === 0) { continue; } if (!empty($txes[$i])) { $this->associate_terms($pid, $txes[$i], $tx_name, $logger, $is_cron); } } } } } // [/custom taxonomies] if (empty($articleData['ID'])) { $logger and call_user_func($logger, sprintf(__('<b>CREATED</b> `%s` `%s` (ID: %s)', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name, $pid)); } else { $logger and call_user_func($logger, sprintf(__('<b>UPDATED</b> `%s` `%s` (ID: %s)', 'wp_all_import_plugin'), $articleData['post_title'], $custom_type_details->labels->singular_name, $pid)); } $is_update = !empty($articleData['ID']); // fire important hooks after custom fields are added if (!$this->options['is_fast_mode'] and $this->options['custom_type'] != 'import_users') { $post_object = get_post($pid); do_action("save_post_" . $articleData['post_type'], $pid, $post_object, $is_update); do_action('save_post', $pid, $post_object, $is_update); do_action('wp_insert_post', $pid, $post_object, $is_update); } // [addons import] // prepare data for import $importData = array('pid' => $pid, 'import' => $this, 'logger' => $logger); $saved_functions = apply_filters('wp_all_import_addon_saved_post', array()); // deligate operation to addons foreach (PMXI_Admin_Addons::get_active_addons() as $class) { if (class_exists($class)) { if (method_exists($addons[$class], 'saved_post')) { $addons[$class]->saved_post($importData); } } else { if (!empty($saved_functions[$class])) { if (is_array($saved_functions[$class]) and is_callable($saved_functions[$class]) or !is_array($saved_functions[$class]) and function_exists($saved_functions[$class])) { call_user_func($saved_functions[$class], $importData); } } } } // [/addons import] $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_saved_post', 'wp_all_import_plugin')); do_action('pmxi_saved_post', $pid, $rootNodes[$i], $is_update); // hook that was triggered immediately after post saved if (empty($articleData['ID'])) { $created++; } else { $updated++; } if (!$is_cron and "default" == $this->options['import_processing']) { $processed_records = $created + $updated + $skipped; $logger and call_user_func($logger, sprintf(__('<span class="processing_info"><span class="created_count">%s</span><span class="updated_count">%s</span><span class="percents_count">%s</span></span>', 'wp_all_import_plugin'), $created, $updated, ceil($processed_records / $this->count * 100))); } } $logger and call_user_func($logger, __('<b>ACTION</b>: pmxi_after_post_import', 'wp_all_import_plugin')); do_action('pmxi_after_post_import', $this->id); $logger and !$is_cron and PMXI_Plugin::$session->chunk_number++; } wp_cache_flush(); $this->set(array('imported' => $created + $updated, 'created' => $created, 'updated' => $updated, 'skipped' => $skipped, 'last_activity' => date('Y-m-d H:i:s')))->update(); if (!$is_cron) { PMXI_Plugin::$session->save_data(); $records_count = $this->created + $this->updated + $this->skipped; $records_to_import = empty($specified_records) ? $this->count : $specified_records[count($specified_records) - 1]; $is_import_complete = $records_count == $records_to_import; // Set out of stock status for missing records [Woocommerce add-on option] if ($is_import_complete and empty($this->options['is_delete_missing']) and $post_type[$i] == "product" and class_exists('PMWI_Plugin') and !empty($this->options['missing_records_stock_status'])) { $logger and call_user_func($logger, __('Update stock status previously imported posts which are no longer actual...', 'wp_all_import_plugin')); $args = array('import_id' => $this->id, 'iteration !=' => $this->iteration); if (!empty($this->options['is_import_specified'])) { $args['specified'] = 1; } $postList = new PMXI_Post_List(); $missingPosts = $postList->getBy($args); if (!$missingPosts->isEmpty()) { foreach ($missingPosts as $missingPost) { update_post_meta($missingPost['post_id'], '_stock_status', 'outofstock'); update_post_meta($missingPost['post_id'], '_stock', 0); $missingPostRecord = new PMXI_Post_Record(); $missingPostRecord->getBy('id', $missingPost['id']); if (!$missingPostRecord->isEmpty()) { $missingPostRecord->set(array('iteration' => $this->iteration))->update(); } unset($missingPostRecord); } } } } } catch (XmlImportException $e) { $logger and call_user_func($logger, __('<b>ERROR</b>', 'wp_all_import_plugin') . ': ' . $e->getMessage()); $logger and !$is_cron and PMXI_Plugin::$session->errors++; } $logger and $is_import_complete and call_user_func($logger, __('Cleaning temporary data...', 'wp_all_import_plugin')); foreach ($tmp_files as $file) { // remove all temporary files created @unlink($file); } remove_filter('user_has_cap', array($this, '_filter_has_cap_unfiltered_html')); kses_init(); // return any filtering rules back if they has been disabled for import procedure return $this; }
/** * @param integer|WP_user $user User object to check. * @param string $action Type of action, either 'view' or 'edit'. * @return boolean If user has access or not. */ public function UserCan($user, $action) { if (is_int($user)) { $user = get_userdata($user); } $allowed = array(); switch ($action) { case 'view': $allowed = $this->GetAllowedPluginViewers(); $allowed = array_merge($allowed, $this->GetAllowedPluginEditors()); $allowed = array_merge($allowed, $this->GetSuperAdmins()); $allowed = array_merge($allowed, $this->GetAdmins()); break; case 'edit': $allowed = $this->GetAllowedPluginEditors(); $allowed = array_merge($allowed, $this->_plugin->IsMultisite() ? $this->GetSuperAdmins() : $this->GetAdmins()); break; default: throw new Exception('Unknown action "' . $action . '".'); } $check = array_merge($user->roles, array($user->user_login)); if (is_multisite()) { $allowed = array_merge($allowed, get_super_admins()); } else { $allowed[] = 'administrator'; } foreach ($check as $item) { if (in_array($item, $allowed)) { return true; } } return false; }
/** * Selects all the users with a given role and returns an array of the users' IDs. * * @param $role string The role to get the users for * @return $users array Array of user IDs for those users with the given role. */ function msum_get_users_with_role($role) { global $wpdb; if ($role != 'none') { $sql = $wpdb->prepare("SELECT DISTINCT({$wpdb->users}.ID) FROM {$wpdb->users} \n\t\t\t\t\t\tINNER JOIN {$wpdb->usermeta} ON {$wpdb->users}.ID = {$wpdb->usermeta}.user_id\n\t\t\t\t\t\tWHERE {$wpdb->usermeta}.meta_key = '{$wpdb->prefix}capabilities' \n\t\t\t\t\t\tAND {$wpdb->usermeta}.meta_value LIKE %s", '%' . $role . '%'); } else { // get users without a role for current site $sql = "SELECT DISTINCT({$wpdb->users}.ID) FROM {$wpdb->users}\n\t\t\t\t WHERE {$wpdb->users}.ID NOT IN (\n\t\t\t\t\tSELECT {$wpdb->usermeta}.user_id FROM {$wpdb->usermeta}\n\t\t\t\t\tWHERE {$wpdb->usermeta}.meta_key = '{$wpdb->prefix}capabilities' \n\t\t\t\t\t)"; } $users = $wpdb->get_col($sql); if ($role == 'none') { // if we got all users without a capability for the site, that includes super admins $super_users = get_super_admins(); foreach ($users as $key => $user) { //never modify caps for super admins if (is_super_admin($user)) { unset($users[$key]); } } } return $users; }
function icl_enable_capabilities() { global $wp_roles; if (!isset($wp_roles) || !is_object($wp_roles)) { $wp_roles = new WP_Roles(); } $iclsettings = get_option('icl_sitepress_settings'); $icl_capabilities = icl_sitepress_get_capabilities(); //Set WPML capabilities to all roles with cap:"". $roles = $wp_roles->get_names(); foreach ($roles as $current_role => $role_name) { if (isset($wp_roles->roles[$current_role]['capabilities']['manage_options'])) { $role = get_role($current_role); if (isset($role) && is_object($role)) { for ($i = 0, $caps_limit = count($icl_capabilities); $i < $caps_limit; $i++) { if (!isset($wp_roles->roles[$current_role]['capabilities'][$icl_capabilities[$i]])) { $role->add_cap($icl_capabilities[$i]); } } } } } //Set new caps for all Super Admins $super_admins = get_super_admins(); foreach ($super_admins as $admin) { $user = new WP_User($admin); for ($i = 0, $caps_limit = count($icl_capabilities); $i < $caps_limit; $i++) { $user->add_cap($icl_capabilities[$i]); } } $iclsettings['icl_capabilities_verified'] = true; update_option('icl_sitepress_settings', $iclsettings); }
if ( !empty( $val ) ) { switch ( $doaction ) { case 'delete': $title = __( 'Users' ); $parent_file = 'ms-admin.php'; require_once( 'admin-header.php' ); echo '<div class="wrap">'; confirm_delete_users( $_POST['allusers'] ); echo '</div>'; require_once( 'admin-footer.php' ); exit(); break; case 'spam': $user = new WP_User( $val ); if ( in_array( $user->user_login, get_super_admins() ) ) wp_die( sprintf( __( 'Warning! User cannot be modified. The user %s is a network administrator.' ), esc_html( $user->user_login ) ) ); $userfunction = 'all_spam'; $blogs = get_blogs_of_user( $val, true ); foreach ( (array) $blogs as $key => $details ) { if ( $details->userblog_id != $current_site->blog_id ) // main blog not a spam ! update_blog_status( $details->userblog_id, 'spam', '1' ); } update_user_status( $val, 'spam', '1', 1 ); break; case 'notspam': $userfunction = 'all_notspam'; $blogs = get_blogs_of_user( $val, true ); foreach ( (array) $blogs as $key => $details )
/** * Duplicate a site in a multisite install. * * ## OPTIONS * * --slug=<slug> * : Path for the new site. Subdomain on subdomain installs, directory on subdirectory installs. * * --source=<site_id> * : ID of the site to duplicate. * * [--title=<title>] * : Title of the new site. Default: prettified slug. * * [--email=<email>] * : Email for Admin user. User will be created if none exists. Assignement to Super Admin if not included. * * [--network_id=<network-id>] * : Network to associate new site with. Defaults to current network (typically 1). * * [--private] * : If set, the new site will be non-public (not indexed) * * [--porcelain] * : If set, only the site id will be output on success. * * [--v] * : If set, print more details about the new site (Verbose mode). Do not work if --procelain is set. * * [--do_not_copy_files] * : If set, files of the duplicated site will not be copied. * * [--keep_users] * : If set, the new site will have the same users as the duplicated site. * * [--log=<dir_path>] * : If set, a log will be written in this directory (please check this directory is writable). * * @alias clone * * @synopsis --slug=<slug> --source=<site_id> [--title=<title>] [--email=<email>] [--network_id=<network-id>] [--private] [--porcelain] [--v] [--do_not_copy_files] [--keep_users] [--log=<dir_path>] */ public function __invoke($_, $assoc_args) { if (!is_multisite()) { WP_CLI::error('This is not a multisite install.'); } global $wpdb, $current_site; $base = $assoc_args['slug']; $title = isset($assoc_args['title']) ? $assoc_args['title'] : ucfirst($base); $email = empty($assoc_args['email']) ? '' : $assoc_args['email']; // Network if (!empty($assoc_args['network_id'])) { $network = MUCD_Functions::get_network($assoc_args['network_id']); if ($network === false) { WP_CLI::error(sprintf('Network with id %d does not exist.', $assoc_args['network_id'])); } } else { $network = $current_site; } $network_id = $network->id; $public = !isset($assoc_args['private']); // Sanitize if (preg_match('|^([a-zA-Z0-9-])+$|', $base)) { $base = strtolower($base); } // If not a subdomain install, make sure the domain isn't a reserved word if (!is_subdomain_install()) { $subdirectory_reserved_names = apply_filters('subdirectory_reserved_names', array('page', 'comments', 'blog', 'files', 'feed')); if (in_array($base, $subdirectory_reserved_names)) { WP_CLI::error('The following words are reserved and cannot be used as blog names: ' . implode(', ', $subdirectory_reserved_names)); } } // Check for valid email, if not, use the first Super Admin found // Probably a more efficient way to do this so we dont query for the // User twice if super admin $email = sanitize_email($email); if (empty($email) || !is_email($email)) { $super_admins = get_super_admins(); $email = ''; if (!empty($super_admins) && is_array($super_admins)) { // Just get the first one $super_login = $super_admins[0]; $super_user = get_user_by('login', $super_login); if ($super_user) { $email = $super_user->user_email; } } } if (is_subdomain_install()) { $newdomain = $base . '.' . preg_replace('|^www\\.|', '', $network->domain); $path = $network->path; } else { $newdomain = $network->domain; $path = $network->path . $base . '/'; } // Source ? $source = $assoc_args['source']; if (!intval($source) != 0) { WP_CLI::error($source . ' is not a valid site ID.'); } if (!MUCD_Functions::site_exists($source)) { WP_CLI::error('There is no site with ID=' . $source . '. The site to duplicate must be an existing site of the network.'); } // Copy files ? $copy_files = isset($assoc_args['do_not_copy_files']) ? 'no' : 'yes'; // Keep users ? $keep_users = isset($assoc_args['keep_users']) ? 'yes' : 'no'; // Write log if (isset($assoc_args['log'])) { $log = 'yes'; $log_path = $assoc_args['log']; } else { $log = 'no'; $log_path = ''; } $data = array('source' => $source, 'domain' => $base, 'title' => $title, 'email' => $email, 'copy_files' => $copy_files, 'keep_users' => $keep_users, 'log' => $log, 'log-path' => $log_path, 'from_site_id' => $source, 'newdomain' => $newdomain, 'path' => $path, 'public' => $public, 'network_id' => $network_id); $wpdb->hide_errors(); $form_message = MUCD_Duplicate::duplicate_site($data); $wpdb->show_errors(); if (isset($form_message['error'])) { WP_CLI::error($form_message['error']); } else { if (isset($assoc_args['porcelain'])) { WP_CLI::line($form_message['site_id']); } else { switch_to_blog($form_message['site_id']); if (!isset($assoc_args['v'])) { WP_CLI::success('Site ' . $form_message['site_id'] . ' created: ' . get_site_url()); } else { // Verbose mode WP_CLI::success($form_message['msg']); $user = get_current_user_id(); WP_CLI::line("ID : " . $form_message['site_id']); WP_CLI::line("Title : " . get_bloginfo('name')); WP_CLI::line("Front : " . get_site_url()); WP_CLI::line("Dashboard : " . admin_url()); WP_CLI::line("Customize : " . admin_url('customize.php')); } restore_current_blog(); } } }
/** * Returns access tokens for a particular action. * @param string $action Type of action. * @return string[] List of tokens (usernames, roles etc). */ public function GetAccessTokens($action) { $allowed = array(); switch ($action) { case 'view': $allowed = $this->GetAllowedPluginViewers(); $allowed = array_merge($allowed, $this->GetAllowedPluginEditors()); if (!$this->IsRestrictAdmins()) { $allowed = array_merge($allowed, $this->GetSuperAdmins()); $allowed = array_merge($allowed, $this->GetAdmins()); } break; case 'edit': $allowed = $this->GetAllowedPluginEditors(); if (!$this->IsRestrictAdmins()) { $allowed = array_merge($allowed, $this->_plugin->IsMultisite() ? $this->GetSuperAdmins() : $this->GetAdmins()); } break; default: throw new Exception('Unknown action "' . $action . '".'); } if (!$this->IsRestrictAdmins()) { if (is_multisite()) { $allowed = array_merge($allowed, get_super_admins()); } else { $allowed[] = 'administrator'; } } return array_unique($allowed); }
/** * Determine if user is a site admin. * * @since 3.0.0 * * @param int $user_id (Optional) The ID of a user. Defaults to the current user. * @return bool True if the user is a site admin. */ function is_super_admin($user_id = false) { if (!$user_id || $user_id == get_current_user_id()) { $user = wp_get_current_user(); } else { $user = get_userdata($user_id); } if (!$user || !$user->exists()) { return false; } if (is_multisite()) { $super_admins = get_super_admins(); if (is_array($super_admins) && in_array($user->user_login, $super_admins)) { return true; } } else { if ($user->has_cap('delete_users')) { return true; } } return false; }
public function disable_all_caps() { global $wp_roles; if (!isset($wp_roles) || !is_object($wp_roles)) { $wp_roles = new WP_Roles(); } $wpcf_capabilities = array_keys(self::wpcf_get_capabilities()); foreach ($wpcf_capabilities as $cap) { foreach (array_keys($wp_roles->roles) as $role) { $wp_roles->remove_cap($role, $cap); } } //Remove caps for all Super Admins $super_admins = get_super_admins(); foreach ($super_admins as $admin) { $user = new WP_User($admin); for ($i = 0, $caps_limit = count($wpcf_capabilities); $i < $caps_limit; $i++) { $user->remove_cap($wpcf_capabilities[$i]); } } }
public function display_rows() { global $mode; $alt = ''; $super_admins = get_super_admins(); foreach ($this->items as $user) { $alt = 'alternate' == $alt ? '' : 'alternate'; $status_list = array('spam' => 'site-spammed', 'deleted' => 'site-deleted'); foreach ($status_list as $status => $col) { if ($user->{$status}) { $alt .= " {$col}"; } } ?> <tr class="<?php echo $alt; ?> "> <?php list($columns, $hidden) = $this->get_column_info(); foreach ($columns as $column_name => $column_display_name) { $class = "class='{$column_name} column-{$column_name}'"; $style = ''; if (in_array($column_name, $hidden)) { $style = ' style="display:none;"'; } $attributes = "{$class}{$style}"; switch ($column_name) { case 'cb': ?> <th scope="row" class="check-column"> <label class="screen-reader-text" for="blog_<?php echo $user->ID; ?> "><?php echo sprintf(__('Select %s'), $user->user_login); ?> </label> <input type="checkbox" id="blog_<?php echo $user->ID; ?> " name="allusers[]" value="<?php echo esc_attr($user->ID); ?> " /> </th> <?php break; case 'username': $avatar = get_avatar($user->user_email, 32); $edit_link = esc_url(add_query_arg('wp_http_referer', urlencode(wp_unslash($_SERVER['REQUEST_URI'])), get_edit_user_link($user->ID))); echo "<td {$attributes}>"; ?> <?php echo $avatar; ?> <strong><a href="<?php echo $edit_link; ?> " class="edit"><?php echo $user->user_login; ?> </a><?php if (in_array($user->user_login, $super_admins)) { echo ' - ' . __('Super Admin'); } ?> </strong> <br/> <?php $actions = array(); $actions['edit'] = '<a href="' . $edit_link . '">' . __('Edit') . '</a>'; if (current_user_can('delete_user', $user->ID) && !in_array($user->user_login, $super_admins)) { $actions['delete'] = '<a href="' . ($delete = esc_url(network_admin_url(add_query_arg('_wp_http_referer', urlencode(wp_unslash($_SERVER['REQUEST_URI'])), wp_nonce_url('users.php', 'deleteuser') . '&action=deleteuser&id=' . $user->ID))) . '" class="delete">' . __('Delete') . '</a>'); } /** * Filter the action links displayed under each user * in the Network Admin Users list table. * * @since 3.2.0 * * @param array $actions An array of action links to be displayed. * Default 'Edit', 'Delete'. * @param WP_User $user WP_User object. */ $actions = apply_filters('ms_user_row_actions', $actions, $user); echo $this->row_actions($actions); ?> </td> <?php break; case 'name': echo "<td {$attributes}>{$user->first_name} {$user->last_name}</td>"; break; case 'email': echo "<td {$attributes}><a href='" . esc_url("mailto:{$user->user_email}") . "'>{$user->user_email}</a></td>"; break; case 'registered': if ('list' == $mode) { $date = 'Y/m/d'; } else { $date = 'Y/m/d \\<\\b\\r \\/\\> g:i:s a'; } echo "<td {$attributes}>" . mysql2date($date, $user->user_registered) . "</td>"; break; case 'blogs': $blogs = get_blogs_of_user($user->ID, true); echo "<td {$attributes}>"; if (is_array($blogs)) { foreach ((array) $blogs as $key => $val) { if (!can_edit_network($val->site_id)) { continue; } $path = $val->path == '/' ? '' : $val->path; echo '<span class="site-' . $val->site_id . '" >'; echo '<a href="' . esc_url(network_admin_url('site-info.php?id=' . $val->userblog_id)) . '">' . str_replace('.' . get_current_site()->domain, '', $val->domain . $path) . '</a>'; echo ' <small class="row-actions">'; $actions = array(); $actions['edit'] = '<a href="' . esc_url(network_admin_url('site-info.php?id=' . $val->userblog_id)) . '">' . __('Edit') . '</a>'; $class = ''; if (get_blog_status($val->userblog_id, 'spam') == 1) { $class .= 'site-spammed '; } if (get_blog_status($val->userblog_id, 'mature') == 1) { $class .= 'site-mature '; } if (get_blog_status($val->userblog_id, 'deleted') == 1) { $class .= 'site-deleted '; } if (get_blog_status($val->userblog_id, 'archived') == 1) { $class .= 'site-archived '; } $actions['view'] = '<a class="' . $class . '" href="' . esc_url(get_home_url($val->userblog_id)) . '">' . __('View') . '</a>'; /** * Filter the action links displayed next the sites a user belongs to * in the Network Admin Users list table. * * @since 3.1.0 * * @param array $actions An array of action links to be displayed. * Default 'Edit', 'View'. * @param int $userblog_id The site ID. */ $actions = apply_filters('ms_user_list_site_actions', $actions, $val->userblog_id); $i = 0; $action_count = count($actions); foreach ($actions as $action => $link) { ++$i; $i == $action_count ? $sep = '' : ($sep = ' | '); echo "<span class='{$action}'>{$link}{$sep}</span>"; } echo '</small></span><br/>'; } } ?> </td> <?php break; default: echo "<td {$attributes}>"; /** This filter is documented in wp-admin/includes/class-wp-users-list-table.php */ echo apply_filters('manage_users_custom_column', '', $column_name, $user->ID); echo "</td>"; break; } } ?> </tr> <?php } }
/** * @return array */ public function getCurrentAdmins() { require_once ABSPATH . WPINC . '/user.php'; if (is_multisite()) { $sites = wp_get_sites(array('network_id' => null)); } else { $sites = array(array('blog_id' => get_current_blog_id())); } // not very efficient, but the WordPress API doesn't provide a good way to do this. $admins = array(); foreach ($sites as $siteRow) { $user_query = new WP_User_Query(array('blog_id' => $siteRow['blog_id'], 'role' => 'administrator')); $users = $user_query->get_results(); if (is_array($users)) { /** @var WP_User $user */ foreach ($users as $user) { $admins[$user->ID] = 1; } } } // Add any super admins that aren't also admins on a network $superAdmins = get_super_admins(); foreach ($superAdmins as $userLogin) { $user = get_user_by('login', $userLogin); if ($user) { $admins[$user->ID] = 1; } } return $admins; }
/** * Generic function to merge two albums * * @param type $primary_album_id * @param type $secondary_album_id * * @return type */ function merge($primary_album_id, $secondary_album_id) { add_filter('rt_db_model_per_page', array($this, 'set_queries_per_page'), 10, 2); $page = 1; /** * Transfer all the media from secondary album to primary album */ while ($media = $this->media->model->get_by_album_id($secondary_album_id, $page)) { $media_id = $media['result'][0]['media_id']; $this->media->move($media_id, $primary_album_id); $page++; } $author = $this->get_current_author(); $admins = get_super_admins(); $global_albums = self::get_globals(); if (in_array($secondary_album_id, $global_albums)) { if (in_array($author, $admins)) { $this->delete_global($secondary_album_id); } else { return false; } } else { $this->delete($secondary_album_id); } return $primary_album_id; }
public function EventAdminInit() { if ($this->IsMultisite()) { $this->old_superadmins = get_super_admins(); } }
/** * Render the primary metabox for user profile screen * * @since 0.1.0 * * @param WP_User $user The WP_User object to be edited. */ function wp_user_profiles_status_metabox($user = null) { // Bail if no user id or if the user has not activated their account yet if (empty($user->ID)) { return; } ?> <div class="submitbox"> <div id="minor-publishing"> <div id="misc-publishing-actions"> <?php // Get the spam status once here to compare against below if (apply_filters('wp_user_profiles_show_status', true) && (current_user_can('edit_user', $user->ID) && !IS_PROFILE_PAGE && !is_user_admin() && !in_array($user->user_login, get_super_admins()))) { ?> <div class="misc-pub-section" id="comment-status-radio"> <label class="approved"><input type="radio" name="user_status" value="ham" <?php checked($user->user_status, 0); ?> ><?php esc_html_e('Active', 'wp-user-profiles'); ?> </label><br> <label><input type="radio" name="user_status" value="inactive" <?php checked($user->user_status, 2); ?> ><?php esc_html_e('Inactive', 'wp-user-profiles'); ?> </label><br> <label class="spam"><input type="radio" name="user_status" value="spam" <?php checked($user->user_status, 1); ?> ><?php esc_html_e('Spammer', 'wp-user-profiles'); ?> </label> </div> <?php } ?> <div class="misc-pub-section curtime misc-pub-section-last"> <?php $datef = get_option('date_format') . ' ' . get_option('time_format'); $date = date_i18n($datef, strtotime($user->user_registered)); ?> <span id="timestamp"><?php printf(esc_html__('Registered on: %1$s', 'wp-user-profiles'), '<strong>' . $date . '</strong>'); ?> </span> </div> </div> <div class="clear"></div> </div> <div id="major-publishing-actions"> <div id="publishing-action"> <a class="button" href="<?php echo esc_url(get_author_posts_url($user->ID)); ?> " target="_blank"><?php esc_html_e('View User', 'wp-user-profiles'); ?> </a> <?php submit_button(esc_html__('Update', 'wp-user-profiles'), 'primary', 'save', false); ?> <input type="hidden" name="action" value="update" /> <input type="hidden" name="user_id" id="user_id" value="<?php echo esc_attr($user->ID); ?> " /> </div> <div class="clear"></div> </div> </div> <?php }
public function disable_all_caps() { global $wp_roles; if (!isset($wp_roles) || !is_object($wp_roles)) { $wp_roles = new WP_Roles(); } $ddl_capabilities = array_keys(self::ddl_get_capabilities()); foreach ($ddl_capabilities as $cap) { foreach (array_keys($wp_roles->roles) as $role) { $wp_roles->remove_cap($role, $cap); } } //Remove caps for all Super Admins $super_admins = get_super_admins(); foreach ($super_admins as $admin) { $user = new WP_User($admin); for ($i = 0, $caps_limit = count($ddl_capabilities); $i < $caps_limit; $i++) { $user->remove_cap($ddl_capabilities[$i]); } } $this->ddl_users_settings->update_options('updated_profiles', false, true); }