] * : Space id (post type). * --- * default: attachment * --- * * [--owner=] * : Tree owner (0 = shared tree). * --- * default: 0 * --- * * [--fields=] * : Fields to display. * --- * default: id,parent,name,position,color,count * --- * * [--format=] * : Output format. * --- * default: table * options: * - table * - csv * - json * - yaml * - ids * - count * --- * * ## EXAMPLES * * $ wp foldivo list --format=json * * @subcommand list * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function list_( $args, $assoc_args ) { $space = $this->space( $assoc_args ); $owner = (int) \WP_CLI\Utils\get_flag_value( $assoc_args, 'owner', 0 ); $folders = Plugin::instance()->folders()->get_tree( $space, $owner ); $format = \WP_CLI\Utils\get_flag_value( $assoc_args, 'format', 'table' ); if ( 'ids' === $format ) { WP_CLI::line( implode( ' ', wp_list_pluck( $folders, 'id' ) ) ); return; } $items = 'table' === $format ? $this->indent( $folders ) : $folders; $items = array_map( static function ( $folder ) { unset( $folder['meta'] ); return $folder; }, $items ); \WP_CLI\Utils\format_items( $format, $items, \WP_CLI\Utils\get_flag_value( $assoc_args, 'fields', 'id,parent,name,position,color,count' ) ); } /** * Creates a folder. * * ## OPTIONS * * * : Folder name. * * [--parent=] * : Parent folder id (0 = root). * --- * default: 0 * --- * * [--color=] * : Color, #rrggbb. * * [--space=] * : Space id. * --- * default: attachment * --- * * [--porcelain] * : Output only the new folder id. * * ## EXAMPLES * * $ wp foldivo create "Logos" --parent=12 --color=#2271b1 * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function create( $args, $assoc_args ) { $space = $this->space( $assoc_args ); $data = array(); if ( isset( $assoc_args['color'] ) ) { $data['color'] = (string) $assoc_args['color']; } $parent = $this->folder_arg( $space, \WP_CLI\Utils\get_flag_value( $assoc_args, 'parent', '0' ), false ); $folder = Plugin::instance()->folders()->create( $space, (string) $args[0], $parent, $data ); $this->bail( $folder ); if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'porcelain', false ) ) { WP_CLI::line( (string) $folder['id'] ); return; } /* translators: 1: folder name, 2: folder id. */ WP_CLI::success( sprintf( __( 'Created folder "%1$s" (%2$d).', 'foldivo' ), $folder['name'], $folder['id'] ) ); } /** * Renames a folder. * * ## OPTIONS * * * : Folder id. * * * : New name. * * [--space=] * : Space id. * --- * default: attachment * --- * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function rename( $args, $assoc_args ) { $space = $this->space( $assoc_args ); $folder = Plugin::instance()->folders()->update( $space, $this->folder_id_arg( $space, $args[0] ), array( 'name' => (string) $args[1] ) ); $this->bail( $folder ); /* translators: %s: folder name. */ WP_CLI::success( sprintf( __( 'Folder renamed to "%s".', 'foldivo' ), $folder['name'] ) ); } /** * Moves a folder under another parent. * * ## OPTIONS * * * : Folder id. * * --parent= * : New parent folder id (0 = root). * * [--space=] * : Space id. * --- * default: attachment * --- * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function move( $args, $assoc_args ) { $space = $this->space( $assoc_args ); $id = $this->folder_id_arg( $space, $args[0] ); $parent = $this->folder_arg( $space, isset( $assoc_args['parent'] ) ? $assoc_args['parent'] : '', false ); $folder = Plugin::instance()->folders()->update( $space, $id, array( 'parent' => $parent ) ); $this->bail( $folder ); /* translators: 1: folder id, 2: parent folder id. */ WP_CLI::success( sprintf( __( 'Folder %1$d moved under %2$d.', 'foldivo' ), $folder['id'], $folder['parent'] ) ); } /** * Deletes a folder. Media and posts are never deleted: they become uncategorized. * * ## OPTIONS * * * : Folder id. * * [--children=] * : What to do with the subfolders. * --- * default: delete * options: * - delete * - lift * --- * * [--space=] * : Space id. * --- * default: attachment * --- * * [--yes] * : Do not ask for confirmation. * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function delete( $args, $assoc_args ) { $space = $this->space( $assoc_args ); $children = (string) \WP_CLI\Utils\get_flag_value( $assoc_args, 'children', 'delete' ); $id = $this->folder_id_arg( $space, $args[0] ); /* translators: %d: folder id. */ WP_CLI::confirm( sprintf( __( 'Delete folder %d? Its items will become uncategorized.', 'foldivo' ), $id ), $assoc_args ); $result = Plugin::instance()->folders()->delete( $space, $id, $children ); $this->bail( $result ); $deleted = count( $result['deleted'] ); $released = (int) $result['released']; WP_CLI::success( sprintf( /* translators: %d: number of deleted folders. */ _n( '%d folder deleted.', '%d folders deleted.', $deleted, 'foldivo' ), $deleted ) . ' ' . sprintf( /* translators: %d: number of items moved to Uncategorized. */ _n( '%d item is now uncategorized.', '%d items are now uncategorized.', $released, 'foldivo' ), $released ) ); } /** * Moves objects into a folder. * * ## OPTIONS * * * : Folder id, or 0 / "uncategorized" to remove the objects from every folder. * * ... * : Object ids (space- or comma-separated). * * [--space=] * : Space id. * --- * default: attachment * --- * * ## EXAMPLES * * $ wp foldivo assign 12 345,346 347 * $ wp foldivo assign uncategorized 345 * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function assign( $args, $assoc_args ) { $space = $this->space( $assoc_args ); $folder = $this->folder_arg( $space, array_shift( $args ), true ); $ids = array(); foreach ( $args as $arg ) { $ids = array_merge( $ids, wp_parse_id_list( $arg ) ); } $result = Plugin::instance()->assignments()->assign( $space, $ids, $folder, array( 'check_caps' => false ) ); $this->bail( $result ); foreach ( $result['skipped'] as $skipped ) { /* translators: 1: object id, 2: reason code. */ WP_CLI::warning( sprintf( __( 'Skipped %1$d (%2$s).', 'foldivo' ), $skipped['id'], $skipped['reason'] ) ); } $moved = count( $result['assigned'] ); /* translators: %d: number of items. */ WP_CLI::success( sprintf( _n( '%d item moved.', '%d items moved.', $moved, 'foldivo' ), $moved ) ); } /** * Recomputes the folder counts and drops orphan relationships. * * ## OPTIONS * * [--space=] * : Space id. All spaces when omitted. * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function recount( $args, $assoc_args ) { $plugin = Plugin::instance(); $spaces = isset( $assoc_args['space'] ) ? array( $this->space( $assoc_args ) ) : $plugin->spaces()->all(); foreach ( $spaces as $space ) { $plugin->counts()->recount( $space ); $counts = $plugin->counts()->get( $space, 0 ); /* translators: 1: space id, 2: total items, 3: uncategorized items. */ WP_CLI::log( sprintf( __( '%1$s: %2$d items, %3$d uncategorized.', 'foldivo' ), $space->id, $counts['total'], $counts['uncategorized'] ) ); } WP_CLI::success( __( 'Counts recomputed.', 'foldivo' ) ); } /** * Shows statistics per space. * * ## OPTIONS * * [--space=] * : Space id. All spaces when omitted. * * [--format=] * : Output format. * --- * default: table * options: * - table * - csv * - json * - yaml * --- * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function stats( $args, $assoc_args ) { $plugin = Plugin::instance(); $spaces = isset( $assoc_args['space'] ) ? array( $this->space( $assoc_args ) ) : $plugin->spaces()->all(); $rows = array(); foreach ( $spaces as $space ) { $counts = $plugin->counts()->get( $space, 0 ); $rows[] = array( 'space' => $space->id, 'taxonomy' => $space->taxonomy, 'folders' => count( $counts['counts'] ), 'total' => $counts['total'], 'in_folders' => $counts['total'] - $counts['uncategorized'], 'uncategorized' => $counts['uncategorized'], ); } \WP_CLI\Utils\format_items( \WP_CLI\Utils\get_flag_value( $assoc_args, 'format', 'table' ), $rows, array( 'space', 'taxonomy', 'folders', 'total', 'in_folders', 'uncategorized' ) ); } /** * Lists the contents and site settings that use a media file. * * Found by id (featured image, blocks, `wp-image-{id}`, galleries, Elementor, ACF) or by URL. * Uses in CSS files, theme files or other sites cannot be detected. * * ## OPTIONS * * * : Attachment id. * * [--format=] * : Output format. * --- * default: table * options: * - table * - csv * - json * - yaml * --- * * ## EXAMPLES * * wp foldivo usage 123 * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function usage( $args, $assoc_args ) { $attachment_id = isset( $args[0] ) ? absint( $args[0] ) : 0; $attachment = $attachment_id ? get_post( $attachment_id ) : null; if ( ! $attachment || 'attachment' !== $attachment->post_type ) { WP_CLI::error( __( 'This media file does not exist.', 'foldivo' ) ); } $raw = Plugin::instance()->media_usage()->find( $attachment_id ); $labels = \Foldivo\Core\Media_Usage::context_labels(); $rows = array(); foreach ( $raw['posts'] as $post_id => $contexts ) { $post = get_post( (int) $post_id ); $list = array(); $by_url = true; foreach ( $contexts as $context => $match ) { $list[] = isset( $labels[ $context ] ) ? $labels[ $context ] : $context; $by_url = $by_url && 'url' === $match; } $rows[] = array( 'id' => (int) $post_id, 'title' => $post ? html_entity_decode( wp_strip_all_tags( get_the_title( $post ) ), ENT_QUOTES, get_bloginfo( 'charset' ) ) : '', 'type' => $post ? $post->post_type : '', 'status' => $post ? $post->post_status : '', 'contexts' => implode( ', ', $list ), 'match' => $by_url ? 'url' : 'id', ); } foreach ( $raw['settings'] as $context ) { $rows[] = array( 'id' => 0, 'title' => isset( $labels[ $context ] ) ? $labels[ $context ] : $context, 'type' => 'setting', 'status' => '', 'contexts' => $context, 'match' => 'id', ); } $format = \WP_CLI\Utils\get_flag_value( $assoc_args, 'format', 'table' ); if ( ! $rows && 'table' === $format ) { WP_CLI::log( __( 'No use detected in the posts, pages, templates or site settings.', 'foldivo' ) ); return; } \WP_CLI\Utils\format_items( $format, $rows, array( 'id', 'title', 'type', 'status', 'contexts', 'match' ) ); if ( $raw['truncated'] ) { WP_CLI::warning( __( 'This file is used in many places: the list may be incomplete.', 'foldivo' ) ); } } /** * Imports folders from another plugin (read-only on the source). * * ## OPTIONS * * * : Importer id (wpmtk, filebird, real-media-library, happyfiles, folders-premio, wicked-folders, * enhanced-media-library, catfolders, wp-media-folder). * * [--dry-run] * : Show the preview only; nothing is written. * * [--overwrite] * : Also move items that are already in another Foldivo folder (by default they stay where they are). * * [--yes] * : Do not ask for confirmation. * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments. * @return void */ public function import( $args, $assoc_args ) { $id = (string) $args[0]; $importer = $this->importer( $id ); $registry = Plugin::instance()->importers(); if ( \WP_CLI\Utils\get_flag_value( $assoc_args, 'dry-run', false ) ) { $preview = method_exists( $registry, 'preview' ) ? $registry->preview( $id ) : $importer->preview(); $this->bail( $this->result_error( $preview ) ); WP_CLI::print_value( $preview, array( 'format' => 'yaml' ) ); return; } /* translators: %s: importer label. */ WP_CLI::confirm( sprintf( __( 'Import the folders of %s?', 'foldivo' ), $importer->label() ), $assoc_args ); // The first cursor may carry the overwrite flag (the importer stores it in its id map). $cursor = \WP_CLI\Utils\get_flag_value( $assoc_args, 'overwrite', false ) ? array( 'overwrite' => true ) : array(); $totals = array(); $guard = 0; do { $result = method_exists( $registry, 'run' ) ? $registry->run( $id, $cursor ) : $importer->run( $cursor ); $this->bail( $this->result_error( $result ) ); foreach ( isset( $result['log'] ) ? (array) $result['log'] : array() as $line ) { WP_CLI::log( is_scalar( $line ) ? (string) $line : wp_json_encode( $line ) ); } // Per-batch stats are deltas: sum them. foreach ( isset( $result['stats'] ) ? (array) $result['stats'] : array() as $key => $value ) { $totals[ $key ] = ( isset( $totals[ $key ] ) ? $totals[ $key ] : 0 ) + (int) $value; } $cursor = isset( $result['cursor'] ) && is_array( $result['cursor'] ) ? $result['cursor'] : array(); ++$guard; } while ( empty( $result['done'] ) && $guard < 100000 ); WP_CLI::print_value( $totals, array( 'format' => 'yaml' ) ); WP_CLI::success( __( 'Import finished.', 'foldivo' ) ); } /** * Turns an importer result carrying an `error` entry (`code`, `message`, `status`) into a WP_Error. * * @param mixed $result Importer or registry result. * @return mixed The WP_Error, or the result unchanged. */ private function result_error( $result ) { if ( is_array( $result ) && ! empty( $result['error'] ) ) { $error = (array) $result['error']; return new \WP_Error( isset( $error['code'] ) ? (string) $error['code'] : 'foldivo_import_error', isset( $error['message'] ) ? (string) $error['message'] : __( 'The import failed.', 'foldivo' ) ); } return $result; } /** * Exports the folders of a space in the Foldivo JSON format. * * ## OPTIONS * * * : Space id. * * ## EXAMPLES * * # Save the media folders to a file. * $ wp foldivo export attachment > folders.json * * @param array $args Positional arguments. * @param array $assoc_args Associative arguments (unused). * @return void */ public function export( $args, $assoc_args ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed -- WP-CLI signature. $space = $this->space( array( 'space' => (string) $args[0] ) ); $document = $this->export_document( $space ); $json = wp_json_encode( $document, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); // The document goes to STDOUT only: the plugin never writes files, redirect the output instead. WP_CLI::line( (string) $json ); } /** * Builds the export document, through the import/export module when available. * * @param Space $space Space. * @return array */ private function export_document( Space $space ) { $registry = Plugin::instance()->importers(); if ( $registry && method_exists( $registry, 'export' ) ) { $document = $registry->export( $space ); $this->bail( $document ); return (array) $document; } if ( class_exists( 'Foldivo\\Importers\\Json_Transfer' ) && method_exists( 'Foldivo\\Importers\\Json_Transfer', 'export' ) ) { $transfer = new \Foldivo\Importers\Json_Transfer(); $document = $transfer->export( $space ); $this->bail( $document ); return (array) $document; } WP_CLI::error( __( 'The export module is not available.', 'foldivo' ) ); return array(); } /** * Finds an importer in the registry. * * @param string $id Importer id. * @return \Foldivo\Importers\Importer */ private function importer( $id ) { $registry = Plugin::instance()->importers(); if ( ! $registry ) { WP_CLI::error( __( 'The importers are not available.', 'foldivo' ) ); } $importer = null; if ( method_exists( $registry, 'get' ) ) { $importer = $registry->get( $id ); } elseif ( method_exists( $registry, 'all' ) ) { foreach ( (array) $registry->all() as $candidate ) { if ( is_object( $candidate ) && method_exists( $candidate, 'id' ) && $candidate->id() === $id ) { $importer = $candidate; break; } } } if ( ! is_object( $importer ) || ! method_exists( $importer, 'run' ) ) { /* translators: %s: importer id. */ WP_CLI::error( sprintf( __( 'Unknown import source "%s".', 'foldivo' ), $id ) ); } return $importer; } /** * Resolves the `--space` option. * * @param array $assoc_args Associative arguments. * @return Space */ private function space( $assoc_args ) { $id = isset( $assoc_args['space'] ) ? (string) $assoc_args['space'] : 'attachment'; $space = Plugin::instance()->spaces()->get( $id ); if ( ! $space ) { /* translators: %s: space id. */ WP_CLI::error( sprintf( __( 'Unknown space "%s". Enable it in the Foldivo settings first.', 'foldivo' ), $id ) ); } return $space; } /** * Validates a folder argument: `0` (root / no folder), `uncategorized` when allowed, or the id of * an existing folder of the current tree. Anything else stops with an error, so that a folder * name or a typo never silently means "the root" or "remove from every folder". * * @param Space $space Space. * @param mixed $value Raw argument. * @param bool $allow_uncategorized Whether `uncategorized` is accepted (as 0). * @return int Folder id, 0 for the root / uncategorized. */ private function folder_arg( Space $space, $value, bool $allow_uncategorized ): int { $raw = is_int( $value ) ? (string) $value : ( is_string( $value ) ? trim( $value ) : '' ); if ( '0' === $raw || ( $allow_uncategorized && 'uncategorized' === $raw ) ) { return 0; } if ( '' !== $raw && ctype_digit( $raw ) && Plugin::instance()->folders()->get_term_in_tree( $space, (int) $raw ) ) { return (int) $raw; } /* translators: %s: folder argument given on the command line. */ WP_CLI::error( sprintf( __( 'Unknown folder "%s". Give a folder id (see "wp foldivo list"), or 0.', 'foldivo' ), is_scalar( $value ) ? (string) $value : '' ) ); return 0; } /** * Validates the `` argument of a folder command (digits only, existing folder of the space). * * @param Space $space Space. * @param mixed $value Raw argument. * @return int Folder id. */ private function folder_id_arg( Space $space, $value ): int { $raw = is_string( $value ) ? trim( $value ) : ( is_int( $value ) ? (string) $value : '' ); if ( '' !== $raw && ctype_digit( $raw ) && (int) $raw > 0 && Plugin::instance()->folders()->get_term( $space, (int) $raw ) ) { return (int) $raw; } /* translators: %s: folder argument given on the command line. */ WP_CLI::error( sprintf( __( 'Unknown folder "%s". Give a folder id (see "wp foldivo list").', 'foldivo' ), is_scalar( $value ) ? (string) $value : '' ) ); return 0; } /** * Stops with an error when a result is a WP_Error. * * @param mixed $result Result. * @return void */ private function bail( $result ) { if ( is_wp_error( $result ) ) { WP_CLI::error( $result->get_error_message() ); } } /** * Orders folders depth-first and indents their names, for the table output. * * @param array[] $folders Folder arrays (sorted by position then name). * @return array[] */ private function indent( array $folders ) { $children = array(); $known = array(); foreach ( $folders as $folder ) { $known[ (int) $folder['id'] ] = true; } foreach ( $folders as $folder ) { $parent = isset( $known[ (int) $folder['parent'] ] ) ? (int) $folder['parent'] : 0; $children[ $parent ][] = $folder; } $output = array(); $seen = array(); $stack = array(); foreach ( array_reverse( isset( $children[0] ) ? $children[0] : array() ) as $folder ) { $stack[] = array( $folder, 0 ); } while ( $stack ) { list( $folder, $depth ) = array_pop( $stack ); $id = (int) $folder['id']; if ( isset( $seen[ $id ] ) ) { continue; } $seen[ $id ] = true; $folder['name'] = str_repeat( '— ', $depth ) . $folder['name']; $output[] = $folder; foreach ( array_reverse( isset( $children[ $id ] ) ? $children[ $id ] : array() ) as $child ) { $stack[] = array( $child, $depth + 1 ); } } return $output; } }