/** * Generate users * * @param array $args * @param array $assoc_args **/ public function users($args, $assoc_args) { global $blog_id; $defaults = array('count' => 100, 'role' => get_option('default_role')); extract(wp_parse_args($assoc_args, $defaults), EXTR_SKIP); if ('none' == $role) { $role = false; } elseif (is_null(get_role($role))) { WP_CLI::warning("invalid role."); exit; } $user_count = count_users(); $total = $user_count['total_users']; $limit = $count + $total; $notify = new \cli\progress\Bar('Generating users', $count); for ($i = $total; $i < $limit; $i++) { $login = sprintf('user_%d_%d', $blog_id, $i); $name = "User {$i}"; $user_id = wp_insert_user(array('user_login' => $login, 'user_pass' => $login, 'nickname' => $name, 'display_name' => $name, 'role' => $role)); if (false === $role) { delete_user_option($user_id, 'capabilities'); delete_user_option($user_id, 'user_level'); } $notify->tick(); } $notify->finish(); }
/** * Convert the NextGen Gallery Shortcodes in posts in this site into WordPress gallery shortcodes. * * ## OPTIONS * * ## EXAMPLES * * wp escape-ngg convert * */ public function convert() { $count = Escape_NextGen_Gallery::init()->count(); WP_CLI::log(sprintf('Processing %d posts with NextGen Gallery shortcodes', $count)); set_time_limit(0); $uploads = wp_upload_dir(); $baseurl = $uploads['baseurl']; $post_ids = Escape_NextGen_Gallery::init()->get_post_ids(); $progress = new \cli\progress\Bar('Progress', $count); foreach ($post_ids as $post_id) { $progress->tick(); Escape_NextGen_Gallery::init()->process_post($post_id); } $progress->finish(); foreach (Escape_NextGen_Gallery::init()->infos as $info) { WP_CLI::log($info); } foreach (Escape_NextGen_Gallery::init()->warnings as $warning) { WP_CLI::warning($warning); } $lines = array((object) array('Converted' => 'posts converted', 'Count' => Escape_NextGen_Gallery::init()->posts_count), (object) array('Converted' => 'images converted', 'Count' => Escape_NextGen_Gallery::init()->images_count)); $fields = array('Converted', 'Count'); \WP_CLI\Utils\format_items('table', $lines, $fields); }
/** * Export function as it is defined in the original code of export_wp defined in wp-admin/includes/export.php */ private function export_wp($args = array()) { require_once ABSPATH . 'wp-admin/includes/export.php'; global $wpdb; /** * This is mostly the original code of export_wp defined in wp-admin/includes/export.php */ $defaults = array('post_type' => 'all', 'post__in' => false, 'author' => false, 'category' => false, 'start_date' => false, 'end_date' => false, 'status' => false, 'skip_comments' => false, 'file_item_count' => 1000); $args = wp_parse_args($args, $defaults); WP_CLI::line("Exporting with export_wp with arguments: " . var_export($args, true)); do_action('export_wp'); $sitename = sanitize_key(get_bloginfo('name')); if (!empty($sitename)) { $sitename .= '.'; } $append = array(date('Y-m-d')); foreach (array_keys($args) as $arg_key) { if ($defaults[$arg_key] != $args[$arg_key] && 'post__in' != $arg_key) { $append[] = "{$arg_key}-" . (string) $args[$arg_key]; } } $file_name_base = sanitize_file_name($sitename . 'wordpress.' . implode(".", $append)); if ('all' != $args['post_type'] && post_type_exists($args['post_type'])) { $ptype = get_post_type_object($args['post_type']); if (!$ptype->can_export) { $args['post_type'] = 'post'; } $where = $wpdb->prepare("{$wpdb->posts}.post_type = %s", $args['post_type']); } else { $post_types = get_post_types(array('can_export' => true)); $esses = array_fill(0, count($post_types), '%s'); $where = $wpdb->prepare("{$wpdb->posts}.post_type IN (" . implode(',', $esses) . ')', $post_types); } if ($args['status'] && ('post' == $args['post_type'] || 'page' == $args['post_type'])) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_status = %s", $args['status']); } else { $where .= " AND {$wpdb->posts}.post_status != 'auto-draft'"; } $join = ''; if ($args['category'] && 'post' == $args['post_type']) { if ($term = term_exists($args['category'], 'category')) { $join = "INNER JOIN {$wpdb->term_relationships} ON ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id)"; $where .= $wpdb->prepare(" AND {$wpdb->term_relationships}.term_taxonomy_id = %d", $term['term_taxonomy_id']); } } if ($args['author']) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_author = %d", $args['author']); } if ($args['start_date']) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_date >= %s", date('Y-m-d 00:00:00', strtotime($args['start_date']))); } if ($args['end_date']) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_date <= %s", date('Y-m-d 23:59:59', strtotime($args['end_date']))); } // grab a snapshot of post IDs, just in case it changes during the export if (empty($args['post__in'])) { $all_the_post_ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} {$join} WHERE {$where} ORDER BY post_date ASC, post_parent ASC"); } else { $all_the_post_ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE ID IN ({$args['post__in']}) ORDER BY post_date ASC, post_parent ASC"); } // Make sure we're getting all of the attachments for these posts too if ('all' != $args['post_type'] || !empty($args['post__in'])) { $all_post_ids_with_attachments = array(); while ($post_ids = array_splice($all_the_post_ids, 0, 100)) { $attachment_ids = $wpdb->get_col("SELECT ID FROM {$wpdb->posts} WHERE post_type = 'attachment' AND post_parent IN (" . implode(",", array_map('intval', $post_ids)) . ")"); $all_post_ids_with_attachments = array_merge($all_post_ids_with_attachments, $post_ids, (array) $attachment_ids); } $all_the_post_ids = $all_post_ids_with_attachments; } // get the requested terms ready, empty unless posts filtered by category or all content $cats = $tags = $terms = array(); if (isset($term) && $term) { $cat = get_term($term['term_id'], 'category'); $cats = array($cat->term_id => $cat); unset($term, $cat); } else { if ('all' == $args['post_type']) { $categories = (array) get_categories(array('get' => 'all')); $tags = (array) get_tags(array('get' => 'all')); $custom_taxonomies = get_taxonomies(array('_builtin' => false)); $custom_terms = (array) get_terms($custom_taxonomies, array('get' => 'all')); // put categories in order with no child going before its parent while ($cat = array_shift($categories)) { if ($cat->parent == 0 || isset($cats[$cat->parent])) { $cats[$cat->term_id] = $cat; } else { $categories[] = $cat; } } // put terms in order with no child going before its parent while ($t = array_shift($custom_terms)) { if ($t->parent == 0 || isset($terms[$t->parent])) { $terms[$t->term_id] = $t; } else { $custom_terms[] = $t; } } unset($categories, $custom_taxonomies, $custom_terms); } } // Load the functions available in wp-admin/includes/export.php ob_start(); export_wp(array('content' => 'page', 'start_date' => '1971-01-01', 'end_date' => '1971-01-02')); ob_end_clean(); WP_CLI::line('Exporting ' . count($all_the_post_ids) . ' items to be broken into ' . ceil(count($all_the_post_ids) / $args['file_item_count']) . ' files'); WP_CLI::line('Exporting ' . count($cats) . ' cateogries'); WP_CLI::line('Exporting ' . count($tags) . ' tags'); WP_CLI::line('Exporting ' . count($terms) . ' terms'); WP_CLI::line(); $file_count = 1; while ($post_ids = array_splice($all_the_post_ids, 0, $args['file_item_count'])) { $full_path = $this->wxr_path . $file_name_base . '.' . str_pad($file_count, 3, '0', STR_PAD_LEFT) . '.xml'; // Create the file if it doesn't exist if (!file_exists($full_path)) { touch($full_path); } if (!file_exists($full_path)) { WP_CLI::error("Failed to create file " . $full_path); exit; } else { WP_CLI::line('Writing to file ' . $full_path); } $progress = new \cli\progress\Bar('Exporting', count($post_ids)); $this->start_export(); echo '<?xml version="1.0" encoding="' . get_bloginfo('charset') . "\" ?>\n"; ?> <!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your site. --> <!-- It contains information about your site's posts, pages, comments, categories, and other content. --> <!-- You may use this file to transfer that content from one site to another. --> <!-- This file is not intended to serve as a complete backup of your site. --> <!-- To import this information into a WordPress site follow these steps: --> <!-- 1. Log in to that site as an administrator. --> <!-- 2. Go to Tools: Import in the WordPress admin panel. --> <!-- 3. Install the "WordPress" importer from the list. --> <!-- 4. Activate & Run Importer. --> <!-- 5. Upload this file using the form provided on that page. --> <!-- 6. You will first be asked to map the authors in this export file to users --> <!-- on the site. For each author, you may choose to map to an --> <!-- existing user on the site or to create a new user. --> <!-- 7. WordPress will then import each of the posts, pages, comments, categories, etc. --> <!-- contained in this file into your site. --> <?php the_generator('export'); ?> <rss version="2.0" xmlns:excerpt="http://wordpress.org/export/<?php echo WXR_VERSION; ?> /excerpt/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:wp="http://wordpress.org/export/<?php echo WXR_VERSION; ?> /" > <channel> <title><?php bloginfo_rss('name'); ?> </title> <link><?php bloginfo_rss('url'); ?> </link> <description><?php bloginfo_rss('description'); ?> </description> <pubDate><?php echo date('D, d M Y H:i:s +0000'); ?> </pubDate> <language><?php echo get_option('rss_language'); ?> </language> <wp:wxr_version><?php echo WXR_VERSION; ?> </wp:wxr_version> <wp:base_site_url><?php echo wxr_site_url(); ?> </wp:base_site_url> <wp:base_blog_url><?php bloginfo_rss('url'); ?> </wp:base_blog_url> <?php wxr_authors_list(); ?> <?php foreach ($cats as $c) { ?> <wp:category><wp:term_id><?php echo $c->term_id; ?> </wp:term_id><wp:category_nicename><?php echo $c->slug; ?> </wp:category_nicename><wp:category_parent><?php echo $c->parent ? $cats[$c->parent]->slug : ''; ?> </wp:category_parent><?php wxr_cat_name($c); wxr_category_description($c); ?> </wp:category> <?php } foreach ($tags as $t) { ?> <wp:tag><wp:term_id><?php echo $t->term_id; ?> </wp:term_id><wp:tag_slug><?php echo $t->slug; ?> </wp:tag_slug><?php wxr_tag_name($t); wxr_tag_description($t); ?> </wp:tag> <?php } foreach ($terms as $t) { ?> <wp:term><wp:term_id><?php echo $t->term_id; ?> </wp:term_id><wp:term_taxonomy><?php echo $t->taxonomy; ?> </wp:term_taxonomy><wp:term_slug><?php echo $t->slug; ?> </wp:term_slug><wp:term_parent><?php echo $t->parent ? $terms[$t->parent]->slug : ''; ?> </wp:term_parent><?php wxr_term_name($t); wxr_term_description($t); ?> </wp:term> <?php } if ('all' == $args['post_type']) { wxr_nav_menu_terms(); } ?> <?php do_action('rss2_head'); ?> <?php $this->flush_export($full_path, false); ?> <?php if ($post_ids) { global $wp_query, $post; $wp_query->in_the_loop = true; // Fake being in the loop. // fetch 20 posts at a time rather than loading the entire table into memory while ($next_posts = array_splice($post_ids, 0, 20)) { $where = 'WHERE ID IN (' . join(',', $next_posts) . ')'; $posts = $wpdb->get_results("SELECT * FROM {$wpdb->posts} {$where}"); // Begin Loop foreach ($posts as $post) { $progress->tick(); setup_postdata($post); $is_sticky = is_sticky($post->ID) ? 1 : 0; ?> <item> <title><?php echo apply_filters('the_title_rss', $post->post_title); ?> </title> <link><?php the_permalink_rss(); ?> </link> <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?> </pubDate> <dc:creator><?php echo get_the_author_meta('login'); ?> </dc:creator> <guid isPermaLink="false"><?php esc_url(the_guid()); ?> </guid> <description></description> <content:encoded><?php echo wxr_cdata(apply_filters('the_content_export', $post->post_content)); ?> </content:encoded> <excerpt:encoded><?php echo wxr_cdata(apply_filters('the_excerpt_export', $post->post_excerpt)); ?> </excerpt:encoded> <wp:post_id><?php echo $post->ID; ?> </wp:post_id> <wp:post_date><?php echo $post->post_date; ?> </wp:post_date> <wp:post_date_gmt><?php echo $post->post_date_gmt; ?> </wp:post_date_gmt> <wp:comment_status><?php echo $post->comment_status; ?> </wp:comment_status> <wp:ping_status><?php echo $post->ping_status; ?> </wp:ping_status> <wp:post_name><?php echo $post->post_name; ?> </wp:post_name> <wp:status><?php echo $post->post_status; ?> </wp:status> <wp:post_parent><?php echo $post->post_parent; ?> </wp:post_parent> <wp:menu_order><?php echo $post->menu_order; ?> </wp:menu_order> <wp:post_type><?php echo $post->post_type; ?> </wp:post_type> <wp:post_password><?php echo $post->post_password; ?> </wp:post_password> <wp:is_sticky><?php echo $is_sticky; ?> </wp:is_sticky> <?php if ($post->post_type == 'attachment') { ?> <wp:attachment_url><?php echo wp_get_attachment_url($post->ID); ?> </wp:attachment_url> <?php } wxr_post_taxonomy(); $postmeta = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->postmeta} WHERE post_id = %d", $post->ID)); foreach ($postmeta as $meta) { if (apply_filters('wxr_export_skip_postmeta', false, $meta->meta_key, $meta)) { continue; } ?> <wp:postmeta> <wp:meta_key><?php echo $meta->meta_key; ?> </wp:meta_key> <wp:meta_value><?php echo wxr_cdata($meta->meta_value); ?> </wp:meta_value> </wp:postmeta> <?php } if (false === $args['skip_comments']) { $comments = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->comments} WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID)); foreach ($comments as $c) { ?> <wp:comment> <wp:comment_id><?php echo $c->comment_ID; ?> </wp:comment_id> <wp:comment_author><?php echo wxr_cdata($c->comment_author); ?> </wp:comment_author> <wp:comment_author_email><?php echo $c->comment_author_email; ?> </wp:comment_author_email> <wp:comment_author_url><?php echo esc_url_raw($c->comment_author_url); ?> </wp:comment_author_url> <wp:comment_author_IP><?php echo $c->comment_author_IP; ?> </wp:comment_author_IP> <wp:comment_date><?php echo $c->comment_date; ?> </wp:comment_date> <wp:comment_date_gmt><?php echo $c->comment_date_gmt; ?> </wp:comment_date_gmt> <wp:comment_content><?php echo wxr_cdata($c->comment_content); ?> </wp:comment_content> <wp:comment_approved><?php echo $c->comment_approved; ?> </wp:comment_approved> <wp:comment_type><?php echo $c->comment_type; ?> </wp:comment_type> <wp:comment_parent><?php echo $c->comment_parent; ?> </wp:comment_parent> <wp:comment_user_id><?php echo $c->user_id; ?> </wp:comment_user_id> <?php $c_meta = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->commentmeta} WHERE comment_id = %d", $c->comment_ID)); foreach ($c_meta as $meta) { ?> <wp:commentmeta> <wp:meta_key><?php echo $meta->meta_key; ?> </wp:meta_key> <wp:meta_value><?php echo wxr_cdata($meta->meta_value); ?> </wp:meta_value> </wp:commentmeta> <?php } ?> </wp:comment> <?php } } ?> </item> <?php $this->flush_export($full_path); } } } ?> </channel> </rss> <?php $this->flush_export($full_path); $this->end_export(); $this->stop_the_insanity(); $progress->finish(); $file_count++; } WP_CLI::success("All done with export"); }
/** * Generate some posts. * * @synopsis [--count=100] [--post_type=post] [--post_status=publish] [--post_author=<login>] [--post_date=<date>] [--max_depth=1] */ public function generate($args, $assoc_args) { global $wpdb; $defaults = array('count' => 100, 'max_depth' => 1, 'post_type' => 'post', 'post_status' => 'publish', 'post_author' => false, 'post_date' => current_time('mysql')); extract(wp_parse_args($assoc_args, $defaults), EXTR_SKIP); if (!post_type_exists($post_type)) { WP_CLI::error(sprintf("'%s' is not a registered post type.", $post_type)); } if ($post_author) { $post_author = get_user_by('login', $post_author); if ($post_author) { $post_author = $post_author->ID; } } // Get the total number of posts $total = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = %s", $post_type)); $label = get_post_type_object($post_type)->labels->singular_name; $hierarchical = get_post_type_object($post_type)->hierarchical; $limit = $count + $total; $notify = new \cli\progress\Bar('Generating posts', $count); $current_depth = 1; $current_parent = 0; for ($i = $total; $i < $limit; $i++) { if ($hierarchical) { if ($this->maybe_make_child() && $current_depth < $max_depth) { $current_parent = $post_ids[$i - 1]; $current_depth++; } else { if ($this->maybe_reset_depth()) { $current_depth = 1; $current_parent = 0; } } } $args = array('post_type' => $post_type, 'post_title' => "{$label} {$i}", 'post_status' => $post_status, 'post_author' => $post_author, 'post_parent' => $current_parent, 'post_name' => "post-{$i}", 'post_date' => $post_date); // Not using wp_insert_post() because it's slow $wpdb->insert($wpdb->posts, $args); $notify->tick(); } $notify->finish(); }
*/ if (cli\choose("Are you sure", 'yn', 'n') == 'n') { exit; } require_once $cmds['cache-clear']->name(); $schema = new \Doctrine\ORM\Tools\SchemaTool($app->em->value()); cli\line('Calculating changes..'); $stmts = $schema->getUpdateSchemaSql($app->em->getMetadataFactory()->getAllMetadata(), false); if (!count($stmts)) { cli\line("Nothing to update"); exit; } cli\line("The following statements will be executed:\n " . implode("\n ", $stmts)); if (cli\choose("Execute these statements", 'yn', 'n') == 'n') { exit; } $app->em->beginTransaction(); try { $bar = new cli\progress\Bar("Executing statements..", count($stmts), 1); $conn = $app->em->getConnection(); foreach ($stmts as $stmt) { $conn->exec($stmt); $bar->tick(); } $bar->finish(); $app->em->commit(); } catch (Exception $e) { $app->em->rollback(); cli\err('Error: ' . $e->getMessage()); } require_once $cmds['proxy-generate']->name();
/** * Restore media attachments with WP CLI. * * ### Config * * Example of `~/.wp-cli/config.yml`: * * media: * restore: * generate: false * uploads_url: http://www.bedrock.com/app/uploads/ * * ### Options * * #### `[--generate=false]` * Set this optional parameter if you want to (re)generate all the different image sizes. Defaults to not generating thumbnails. * * #### `[--uploads-url]` * The URL to the uploads directory, not including any date based folder structure. * * ### Examples * * wp media restore --uploads_url=http://www.bedrock.com/app/uploads/ * * @param array $args * @param array $assoc_args */ public function __invoke(array $args = [], array $assoc_args = []) { require_once ABSPATH . 'wp-admin/includes/media.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/image.php'; // Merge default arguments. $assoc_args = array_merge($this->default_assoc_args, $assoc_args); // Get generate thumbnails value from WP CLI config or cmd argument. $generate = $assoc_args['generate'] === false ? $this->get_config_value('generate') : $assoc_args['generate']; $generate = is_string($generate) ? $generate === 'true' : (bool) $generate; // Get url base value from WP CLI config or cmd argument. $url_base = empty($assoc_args['uploads-url']) ? $this->get_config_value('uploads_url') : $assoc_args['uploads-url']; // Don't continue without a url. if (empty($url_base)) { WP_CLI::error('Missing url'); } $warnings = []; $attachments = $this->get_attachments(); $content_dir = CONTENT_DIR; $url_base = trailingslashit($url_base); $dir = wp_upload_dir(); $base_dir = trailingslashit($dir['basedir']); $results = ['attachments' => count($attachments), 'exists' => 0, 'downloaded' => 0, 'failed' => 0, 'generated' => 0]; // Output information about what the CLI command is doing. WP_CLI::line(sprintf('Downloading %d attachments%s', $results['attachments'], $generate ? ' and generating thumbnails.' : '.')); // Create a progress bar. $progress = new \cli\progress\Bar('Progress', $results['attachments']); try { foreach ($attachments as $id) { $progress->tick(); $attachment = get_post($id); $attached_file = get_post_meta($id, '_wp_attached_file', true); if (!empty($attached_file)) { $guid = $attachment->guid; $scheme = parse_url($url_base, PHP_URL_SCHEME); $domain = $scheme . '://' . parse_url($url_base, PHP_URL_HOST); $remote_url = $domain . parse_url($guid, PHP_URL_PATH); $response = wp_remote_head($remote_url); if (is_wp_error($response)) { $warnings[] = sprintf('Could not retrieve remote file for attachment ID %d, HTTP error "%s"', $id, $response->get_error_message()); } else { if (200 != wp_remote_retrieve_response_code($response)) { $warnings[] = sprintf('Could not retrieve remote file for attachment ID %d, HTTP response code %d', $id, wp_remote_retrieve_response_code($response)); continue; } } if (strpos($attached_file, $domain . '/uploads') !== false) { $attached_file = ltrim(str_replace($domain . '/uploads', '', $attached_file), '/'); } else { $attached_file = ltrim(str_replace($url_base, '', $attached_file), '/'); } $local_path = str_replace('/' . $content_dir . '/uploads/', '', $base_dir) . $attached_file; update_post_meta($id, '_wp_attached_file', $attached_file); } else { $remote_url = $url_base . $attached_file; $local_path = $base_dir . $attached_file; } // Check if the file already exists if (file_exists($local_path)) { $results['exists']++; continue; } // Create directory if it don't exists. wp_mkdir_p(dirname($local_path)); // Download attachment. $response = wp_safe_remote_get($remote_url, ['timeout' => 300, 'stream' => true, 'filename' => $local_path]); // If'ts a error, add a warning and a failed file. if (is_wp_error($response)) { if (file_exists($local_path)) { unlink($local_path); } $warnings[] = sprintf('Could not download %s, got error: %s', $remote_url, $response->get_error_message()); $results['failed']++; continue; } else { if (200 != wp_remote_retrieve_response_code($response)) { $warnings[] = sprintf('Could not retrieve remote file for attachment ID %d, HTTP response code %d', $id, wp_remote_retrieve_response_code($response)); continue; } } // Generate thumbnails if enabled and the attachment is a image. if ($generate && $attachment && 'attachment' === $attachment->post_type && strpos($attachment->post_mime_type, 'image/') !== false) { @set_time_limit(900); $metadata = wp_generate_attachment_metadata($id, $local_path); update_post_meta($id, '_wp_attachment_metadata', $metadata); if (is_wp_error($metadata)) { $warnings[] = sprintf('Error generating image thumbnails for attachment ID %d: %s', $id, $metadata->get_error_message()); } else { if (empty($metadata)) { $warnings[] = sprintf('Unknown error generating image thumbnails for attachment ID %d', $id); } else { $results['generated']++; } } } $results['downloaded']++; } } catch (Exception $e) { WP_CLI::error($e->getMessage()); } $progress->finish(); foreach ($warnings as $warning) { WP_CLI::warning($warning); } $lines = []; foreach ($results as $name => $count) { $lines[] = (object) ['Item' => $name, 'Count' => $count]; } \WP_CLI\Utils\format_items('table', $lines, ['Item', 'Count']); }
/** * Run the media migration from the CLI * * @param $outcome * @param $profile * @param $verify_connection_response * @param $initiate_migration_response * * @return bool */ function cli_migration($outcome, $profile, $verify_connection_response, $initiate_migration_response) { global $wpmdbpro, $wpmdbpro_cli; if (true !== $outcome) { return $outcome; } if (!isset($profile['media_files']) || '1' !== $profile['media_files']) { return $outcome; } if (!isset($verify_connection_response['media_files_max_file_uploads'])) { return $wpmdbpro_cli->cli_error(__('WP Migrate DB Pro Media Files does not seem to be installed/active on the remote website.', 'wp-migrate-db-pro-media-files')); } WP_CLI::log(__('Initiating media migration...', 'wp-migrate-db-pro-media-files')); $this->set_time_limit(); $wpmdbpro->set_cli_migration(); $this->set_cli_migration(); $connection_info = preg_split('/\\s+/', $profile['connection_info']); $_POST['intent'] = $intent = $profile['action']; $_POST['url'] = trim($connection_info[0]); $_POST['key'] = trim($connection_info[1]); $_POST['temp_prefix'] = $verify_connection_response['temp_prefix']; $media_type = isset($profile['media_migration_option']) ? $profile['media_migration_option'] : 'compare'; $copy_entire_media = 'compare' == $media_type ? 0 : 1; $remove_local_media = 'compare' == $media_type && isset($profile['remove_local_media']) ? $profile['remove_local_media'] : 0; // seems like this value needs to be different depending on pull/push? $bottleneck = $wpmdbpro->get_bottleneck(); // if skipping comparison delete all files before migration if ('compare' != $media_type) { do_action('wpmdb_cli_before_remove_files_recursive', $profile, $verify_connection_response, $initiate_migration_response); WP_CLI::log($this->get_string('removing_all_files_' . $intent) . '...'); $compare = 0; $offset = 0; $remove_files = 1; while (1 == $remove_files) { $_POST['compare'] = $compare; $_POST['offset'] = $offset; $response = $this->ajax_remove_files_recursive(); if (is_wp_error($remove_files_recursive_response = $wpmdbpro_cli->verify_cli_response($response, 'ajax_remove_files_recursive()'))) { return $remove_files_recursive_response; } $remove_files = $remove_files_recursive_response['remove_files']; $compare = $remove_files_recursive_response['compare']; $offset = $remove_files_recursive_response['offset']; } // END recursive removal of files } // start the recursive determine do_action('wpmdb_cli_before_determine_media_to_migrate', $profile, $verify_connection_response, $initiate_migration_response); $response = $this->ajax_prepare_determine_media(); if (is_wp_error($prepare_media_to_migrate_response = $wpmdbpro_cli->verify_cli_response($response, 'ajax_prepare_determine_media()'))) { return $prepare_media_to_migrate_response; } $attachment_batch_limit = $this->media_diff_batch_limit; $remote_uploads_url = $prepare_media_to_migrate_response['remote_uploads_url']; $attachment_count = $prepare_media_to_migrate_response['attachment_count']; $prefix = $prepare_media_to_migrate_response['prefix']; $blogs = $prepare_media_to_migrate_response['blogs']; $determine_progress = 0; $determined = 0; // determine the media to migrate in batches while ($determine_progress < $attachment_count) { $_POST['attachment_batch_limit'] = $attachment_batch_limit; $_POST['remote_uploads_url'] = $remote_uploads_url; $_POST['attachment_count'] = $attachment_count; $_POST['prefix'] = $prefix; $_POST['blogs'] = $blogs; $_POST['determine_progress'] = $determine_progress; $_POST['copy_entire_media'] = $copy_entire_media; $_POST['remove_local_media'] = $remove_local_media; $response = $this->ajax_determine_media_to_migrate_recursive(); if (is_wp_error($determine_media_to_migrate_recursive_response = $wpmdbpro_cli->verify_cli_response($response, 'ajax_determine_media_to_migrate_recursive_response()'))) { return $determine_media_to_migrate_recursive_response; } $blogs = $determine_media_to_migrate_recursive_response['blogs']; $determine_progress = $determine_media_to_migrate_recursive_response['determine_progress']; $total_size = $determine_media_to_migrate_recursive_response['total_size']; $files_to_migrate = $determine_media_to_migrate_recursive_response['files_to_migrate']; $percent = $determine_progress / $attachment_count * 100; WP_CLI::log(sprintf($this->get_string('determining_progress'), $determine_progress, $attachment_count, round($percent))); $total_files = count($files_to_migrate); if ($total_files > 0) { $migrate_bar = new \cli\progress\Bar($this->get_string('migrate_media_files_' . $intent), 0); $migrate_bar->setTotal($total_size); } // start the recursive migration of the files we have just determined while (!empty($files_to_migrate)) { $file_chunk_to_migrate = array(); $file_chunk_size = 0; $number_of_files_to_migrate = 0; foreach ($files_to_migrate as $file_to_migrate => $file_size) { if (empty($file_chunk_to_migrate)) { $file_chunk_to_migrate[] = $file_to_migrate; $file_chunk_size += $file_size; unset($files_to_migrate[$file_to_migrate]); ++$number_of_files_to_migrate; } else { if ($file_chunk_size + $file_size > $bottleneck || $number_of_files_to_migrate >= $verify_connection_response['media_files_max_file_uploads']) { break; } else { $file_chunk_to_migrate[] = $file_to_migrate; $file_chunk_size += $file_size; unset($files_to_migrate[$file_to_migrate]); ++$number_of_files_to_migrate; } } } $_POST['file_chunk'] = $file_chunk_to_migrate; $_POST['remote_uploads_url'] = $remote_uploads_url; $response = $this->ajax_migrate_media(); if (is_wp_error($migrate_media_response = $wpmdbpro_cli->verify_cli_response($response, 'ajax_migrate_media()'))) { return $migrate_media_response; } $migrate_bar->tick($file_chunk_size); } // END recursive media migration } // END recursive media determine // if removing local media not found on remote after comparison if (1 == $remove_local_media) { // start recursive batch delete of local files not found on remote do_action('wpmdb_cli_before_remove_files_not_found_recursive', $profile, $verify_connection_response, $initiate_migration_response); WP_CLI::log($this->get_string('removing_files_' . $intent) . '...'); $compare = 1; $offset = ''; $remove_files = 1; while (1 == $remove_files) { $_POST['compare'] = $compare; $_POST['offset'] = $offset; $response = $this->ajax_remove_files_recursive(); if (is_wp_error($remove_files_recursive_response = $wpmdbpro_cli->verify_cli_response($response, 'ajax_remove_files_recursive()'))) { return $remove_files_recursive_response; } $remove_files = $remove_files_recursive_response['remove_files']; $compare = $remove_files_recursive_response['compare']; $offset = $remove_files_recursive_response['offset']; } // END recursive removal of files } return true; }
/** * Bulk PDF import * * ## OPTIONS * * <source-dir> * : required, source directory to import PDF files * * <jpeg-compression-quality> * : optional, jpeg compression quality, default 60 * * <jpeg-resolution> * : optional, jpeg resolution, default 300 * * <post-status> * : optional, PDF post status, default "draft" * * <import-pdf-file> * : flag, if set then import PDF file to Wordpress media library * * ## EXAMPLES * * wp pdf-light-viewer bulk-import --source-dir="/path/to/pdfs" * wp pdf-light-viewer bulk-import --source-dir="/path/to/pdfs" --jpeg-compression-quality=60 --jpeg-resolution=300 --post-status=publish --import-pdf-file * * @synopsis --source-dir=<source-dir> [--jpeg-compression-quality=<jpeg-compression-quality>] [--jpeg-resolution=<jpeg-resolution>] [--post-status=<post-status>] [--import-pdf-file] * @subcommand bulk-import */ public function bulk_import($args, $assoc_args) { // options $source_dir = $assoc_args['source-dir']; $jpeg_compression_quality = isset($assoc_args['jpeg-compression-quality']) ? (int) $assoc_args['jpeg-compression-quality'] : 60; $jpeg_resolution = isset($assoc_args['jpeg-resolution']) ? (int) $assoc_args['jpeg-resolution'] : 300; $post_status = isset($assoc_args['post-status']) ? $assoc_args['post-status'] : 'draft'; $import_pdf_file = isset($assoc_args['import-pdf-file']); // check requirements $plugin_title = PdfLightViewer_Plugin::getData('Title'); $requirements_met = PdfLightViewer_Plugin::requirements(true); if (!$requirements_met) { $message = $plugin_title . ': ' . __('requirements not met, please check plugin settings page for more information.', PDF_LIGHT_VIEWER_PLUGIN); WP_ClI::error($message, true); } else { WP_CLI::log($plugin_title . ': ' . __("requirements are met, happy using!", PDF_LIGHT_VIEWER_PLUGIN)); } // check dir if (!is_readable($source_dir) || !is_dir($source_dir)) { WP_CLI::error(__("Source dir doesn't exist or it's not readable", PDF_LIGHT_VIEWER_PLUGIN), true); } else { WP_CLI::log(sprintf(__("Searching PDF files in %s", PDF_LIGHT_VIEWER_PLUGIN), $source_dir)); } // check PDF files $pdf_files = glob($source_dir . '/*.pdf', GLOB_NOSORT); if (empty($pdf_files)) { WP_CLI::error(__("Source dir doesn't contain PDF files", PDF_LIGHT_VIEWER_PLUGIN), true); } else { WP_CLI::log(sprintf(__("%d PDF files found", PDF_LIGHT_VIEWER_PLUGIN), count($pdf_files))); } // start import $pdf_files_count = count($pdf_files); $all_pdfs_progress = new \cli\progress\Bar(__("Processing PDF files", PDF_LIGHT_VIEWER_PLUGIN), $pdf_files_count); foreach ($pdf_files as $pdf_file_path) { // get number of pages $im = new Imagick(); $im->readImage($pdf_file_path); $pdf_pages_number = $im->getNumberImages(); foreach ($im as $_img) { $geometry = $_img->getImageGeometry(); $width = $geometry['width']; $height = $geometry['height']; break; } $im->destroy(); unset($im); $current_pdf_progress = new \cli\progress\Bar(sprintf(__("Processing PDF file %s", PDF_LIGHT_VIEWER_PLUGIN), $pdf_file_path), $pdf_pages_number); // create PDF post $post_id = wp_insert_post(['post_type' => PdfLightViewer_PdfController::$type, 'post_status' => $post_status, 'post_name' => sanitize_title(pathinfo($pdf_file_path, PATHINFO_FILENAME)), 'post_title' => pathinfo($pdf_file_path, PATHINFO_FILENAME)]); if (is_wp_error($post_id)) { WP_CLI::error(sprintf(__("Could not create PDF post: %s", PDF_LIGHT_VIEWER_PLUGIN), $post_id->get_error_message()), false); } else { // save pdf to media library if ($import_pdf_file) { $image_data = file_get_contents($pdf_file_path); $attach_id = PdfLightViewer_Plugin::create_media_from_data(pathinfo($pdf_file_path, PATHINFO_BASENAME), $image_data); update_post_meta($post_id, 'pdf_file_id', $attach_id); } $pdf_upload_dir = PdfLightViewer_Plugin::createUploadDirectory($post_id); $current_page = 1; $ratio = $width / $height; do_action(PDF_LIGHT_VIEWER_PLUGIN . ':before_import', $post_id, $pdf_file_path); update_post_meta($post_id, '_pdf-light-viewer-import-status', PdfLightViewer_PdfController::STATUS_CLI_PROCESSING); update_post_meta($post_id, '_pdf-light-viewer-import-progress', 0); update_post_meta($post_id, '_pdf-light-viewer-import-current-page', $current_page); update_post_meta($post_id, 'pdf-pages-number', $pdf_pages_number); update_post_meta($post_id, 'pdf-page-width', $width); update_post_meta($post_id, 'pdf-page-height', $height); // process pages for ($current_page; $current_page <= $pdf_pages_number; $current_page++) { $page_number = sprintf('%1$05d', $current_page); if (!file_exists($pdf_upload_dir . '/page-' . $page_number . '.jpg')) { try { PdfLightViewer_PdfController::process_pdf_page($post_id, $current_page, $page_number, $pdf_pages_number, $pdf_file_path, $pdf_upload_dir, $jpeg_resolution, $jpeg_compression_quality, $ratio); } catch (Exception $e) { PdfLightViewer_Plugin::log('Import exception: ' . $e->getMessage(), print_r($e, true)); $error = $e->getMessage(); update_post_meta($post_id, '_pdf-light-viewer-import-status', PdfLightViewer_PdfController::STATUS_FAILED); WP_CLI::warning(sprintf(__('Import of PDF %s failed: %s', PDF_LIGHT_VIEWER_PLUGIN), $pdf_file_path, $error), false); } } $current_pdf_progress->tick(); } do_action(PDF_LIGHT_VIEWER_PLUGIN . ':after_import', $post_id, $pdf_file_path); do_action(PDF_LIGHT_VIEWER_PLUGIN . ':finished_import', $post_id, $pdf_file_path); update_post_meta($post_id, '_pdf-light-viewer-import-status', PdfLightViewer_PdfController::STATUS_FINISHED); WP_CLI::success(sprintf(__('Import of PDF %s finished', PDF_LIGHT_VIEWER_PLUGIN), $pdf_file_path)); } $all_pdfs_progress->tick(); } WP_CLI::success(__('Import finished', PDF_LIGHT_VIEWER_PLUGIN)); }
/** * Generate Hash for current/specified WordPress. * *## OPTIONS * * [<wordpress-path>] * : WordPress Directory Path to generate hash for * * ## EXAMPLES * * wp exploit-scanner generate <dir-name> * * @synopsis */ function generate($args, $assoc_args) { if (count($args) > 0) { $path = $args[0]; } else { $path = ABSPATH; } $path = trailingslashit(realpath($path)); WP_CLI::warning('Scan Path : ' . $path); //Detect Version if (!file_exists($path . 'wp-includes/version.php')) { WP_CLI::error('Not able to determine WordPress Version: Please check if it is valid WordPress directory'); return; } preg_match_all("/wp_version([^\\']+)\\'([^\\']+)'/im", file_get_contents($path . 'wp-includes/version.php'), $version_matches); $wordpress_version = $version_matches[2][0]; WP_CLI::warning('WordPress Version : ' . $wordpress_version); $directory_it = new RecursiveDirectoryIterator($path); $file_name = 'hashes-' . $wordpress_version . '.php'; $full_hash_file_path = trailingslashit(dirname(__FILE__)) . 'hashes/' . $file_name; if (file_exists($full_hash_file_path)) { WP_CLI::confirm(sprintf('%s already exist, Are you sure you want to regenerate it again ?', $file_name)); } $hash_file = fopen($full_hash_file_path, "w"); fwrite($hash_file, '<?php' . PHP_EOL . '$filehashes = array('); $file_progress = new \cli\progress\Bar('Progress', 1100); foreach (new RecursiveIteratorIterator($directory_it) as $file) { fwrite($hash_file, "'" . str_replace($path, '', $file) . "' => '" . md5_file($file) . "'," . PHP_EOL); $file_progress->tick(); } fwrite($hash_file, ');' . PHP_EOL); fclose($file); WP_CLI::success(sprintf("File created: %s", $file_name)); }
/** * Loop through all posts, setting the first attached image as the featured images * * ## OPTIONS * * ## EXAMPLES * * wp auto-thumbnail * */ public function __invoke($args, $assoc_args) { set_time_limit(0); // Get all public post types $get_post_types = get_post_types(array('public' => true)); // Post types array that will be used by default $post_types = array(); foreach ($get_post_types as $post_type) { // Only add post types that support if (post_type_supports($post_type, 'thumbnail')) { $post_types[] = $post_type; } } // Default values for wp query $defaults = array('post_type' => $post_types, 'posts_per_page' => -1, 'post_status' => 'any'); // Merge user args with defaults $assoc_args = wp_parse_args($assoc_args, $defaults); // The Query $the_query = new WP_Query($assoc_args); // Number of posts returned by query $found_posts = $the_query->found_posts; // Generate progess bar $progress = new \cli\progress\Bar('Progress', $found_posts); // Counter for number of post successfully processed $counter_success = 0; // Counter for number of post processed $counter_processed = 0; // The Loop while ($the_query->have_posts()) { $the_query->the_post(); // Move the processbar on $progress->tick(); $has_thumb = has_post_thumbnail(get_the_ID()); if (!$has_thumb) { $attached_image = get_children("post_parent=" . get_the_ID() . "&post_type=attachment&post_mime_type=image&numberposts=1"); if ($attached_image) { foreach ($attached_image as $attachment_id => $attachment) { set_post_thumbnail(get_the_ID(), $attachment_id); $counter_success++; } } $counter_processed++; } } $progress->finish(); /* Restore original Post Data * NB: Because we are using new WP_Query we aren't stomping on the * original $wp_query and it does not need to be reset. */ wp_reset_postdata(); if ($found_posts == 0) { WP_CLI::error("No posts found"); } elseif ($counter_processed == 0) { WP_CLI::error("No posts processed"); } elseif ($counter_success == 0) { WP_CLI::success("Unable to processed any posts"); } else { WP_CLI::success("Processing compelete. {$counter_success} of {$counter_processed} where processed successfully."); } }