Update the URL of a site

@synopsis <ID> <NEW_URL> [--force]

@param array $args
@param array $assoc_args
501006
public function update( array $args = [], array $assoc_args = [] ) {

		$site_id = (int) $args[ 0 ];
		$site = get_blog_details( $site_id, TRUE );
		if ( ! $site ) {
			WP_CLI::error( "A site with ID {$site_id} does not exist" );
		}
		if ( is_main_site( $site_id ) ) {
			WP_CLI::error( "The given site is the main site of the network. This feature does not support updating the main site URL" );
		}
		$new_url = $args[ 1 ];
		if ( ! filter_var( $new_url, FILTER_VALIDATE_URL ) ) {
			WP_CLI::error( "{$new_url} is not a valid url" );
		}

		/**
		 * Parse the new URL components
		 */
		$url_components  = parse_url( $new_url );
		$existing_scheme = parse_url( $site->siteurl, PHP_URL_SCHEME );
		$scheme = isset( $url_components[ 'scheme' ] )
			? $url_components[ 'scheme' ]
			: $existing_scheme;
		$host = isset( $url_components[ 'host' ]  )
			? $url_components[ 'host' ]
			: '';
		$path = isset( $url_components[ 'path' ] )
			? trailingslashit(  $url_components[ 'path' ] )
			: '/';

		// WP core does not accept ports in the URL so we don't too
		$site_details             = get_object_vars( $site );
		$site_details[ 'domain' ] = $host;
		$site_details[ 'path' ]   = $path;

		/**
		 * Update the site details (goes to the wp_blogs table)
		 */
		update_blog_details( $site_id, $site_details );

		// update 'home' and 'siteurl' in the options table
		switch_to_blog( $site_id );
		$existing_home = trailingslashit( get_option( 'home' ) );
		$new_home      = esc_url_raw( $scheme . '://' . $host . $path );
		$new_home      = untrailingslashit( $new_home );

		// check if the actual 'home' value matches the old site URL
		if ( $site->domain === parse_url( $existing_home, PHP_URL_HOST )
		  && $site->path === parse_url( $existing_home, PHP_URL_PATH )
		) {
			update_option( 'home', $new_home );
		}

		$existing_site_url = trailingslashit( get_option( 'siteurl' ) );
		if ( $site->domain === parse_url( $existing_site_url, PHP_URL_HOST )
		  && $site->path === parse_url( $existing_site_url, PHP_URL_PATH )
		) {
			update_option( 'siteurl', $new_home );
		}

		/**
		 * WP core deletes rewrite rules during the URL updating process
		 *
		 * @see wp-admin/network/site-info.php
		 */
		delete_option( 'rewrite_rules' );

		restore_current_blog();
		$new_home = trailingslashit( $new_home ); // append trailing slash for success report to avoid confusion
		WP_CLI::success( "Update site URL to {$new_home}" );
	}
1167147
public function append($url = '', $argsOrParams = array(), $params = array())
    {
        if (strpos($url, '%s') !== false) {
            $url = vsprintf($url, (array)$argsOrParams);
        } else {
            $params = $argsOrParams;
        }
        if ($params) {
            $url .= (false === strpos($url, '?') ? '?' : '&');
        }
        return $url . (is_array($params) ? http_build_query($params) : $params);
    }
441565
public function handleUpdate(Args $args)
    {
        $flags = $args->isOptionSet('force')
            ? RepositoryManager::OVERRIDE | RepositoryManager::IGNORE_FILE_NOT_FOUND
            : RepositoryManager::OVERRIDE;
        $repositoryPath = Path::makeAbsolute($args->getArgument('path'), $this->currentPath);
        $mappingToUpdate = $this->repoManager->getRootPathMapping($repositoryPath);
        $pathReferences = array_flip($mappingToUpdate->getPathReferences());

        foreach ($args->getOption('add') as $pathReference) {
            $pathReferences[$pathReference] = true;
        }

        foreach ($args->getOption('remove') as $pathReference) {
            unset($pathReferences[$pathReference]);
        }

        if (0 === count($pathReferences)) {
            $this->repoManager->removeRootPathMapping($repositoryPath);

            return 0;
        }

        $updatedMapping = new PathMapping($repositoryPath, array_keys($pathReferences));

        if ($this->mappingsEqual($mappingToUpdate, $updatedMapping)) {
            throw new RuntimeException('Nothing to update.');
        }

        $this->repoManager->addRootPathMapping($updatedMapping, $flags);

        return 0;
    }
400814
public function execute(array $args, array $options = [])
    {
        $rootDir = null;
        if (isset($options['root-dir']) && !empty($options['root-dir'])) {
            $rootDir = $options['root-dir'];
        }
        StaticResource::createSymbolicLink($rootDir);
    }
1312491
public function updates( $args, $assoc_args ) {

    require_once dirname( __FILE__ ) . '/../modules/updates.php';
    $site_info = Seravo\Updates::seravo_admin_get_site_info();

    if ( $site_info['seravo_updates'] === true ) {
      WP_CLI::success( 'Seravo Updates: enabled' );
    } elseif ( $site_info['seravo_updates'] === true ) {
      WP_CLI::success('Seravo Updates: disabled' );
    } else {
      WP_CLI::error( 'Seravo API failed to return information about updates.' );
    }

  }
710519
public function set( $args = array(), $assoc_args = array() ) {
		list( $mod, $value ) = $args;

		set_theme_mod( $mod, $value );

		if ( get_theme_mod( $mod ) === $value ) {
			WP_CLI::success( "Theme mod {$mod} set to {$value}." );
		} else {
			WP_CLI::success( "Could not update theme mod {$mod}." );
		}
	}
1368144
public function regenerate($args, $assoc_args) {
		/** @var StorageTool $storageTool */
		$storageTool = ToolsManager::instance()->tools['storage'];

		if (!$storageTool || !$storageTool->enabled()) {
			Command::Error('Storage tool is not enabled in Media Cloud or the settings are incorrect.');
			return;
		}

		$postArgs = [
			'post_type' => 'attachment',
			'post_status' => 'inherit',
			'nopaging' => true,
			'post_mime_type' => 'image',
			'fields' => 'ids',
		];

		$query = new \WP_Query($postArgs);

		if($query->post_count > 0) {
            BatchManager::instance()->reset('thumbnails');

            BatchManager::instance()->setStatus('thumbnails', true);
            BatchManager::instance()->setTotalCount('thumbnails', $query->post_count);
            BatchManager::instance()->setCurrent('thumbnails', 1);
            BatchManager::instance()->setShouldCancel('thumbnails', false);

			Command::Info("Total posts found: %Y{$query->post_count}.", true);

			$pd = new DefaultProgressDelegate();

			for($i = 1; $i <= $query->post_count; $i++) {
				$postId = $query->posts[$i - 1];
				$upload_file = get_attached_file($postId);
				$fileName = basename($upload_file);

                BatchManager::instance()->setCurrentFile('thumbnails', $fileName);
                BatchManager::instance()->setCurrent('thumbnails', $i);

				Command::Info("%w[%C{$i}%w of %C{$query->post_count}%w] %NRegenerating thumbnails for %Y$fileName%N %w(%N$postId%w)%N ... ");
				$storageTool->regenerateFile($postId);
				Command::Info("%YDone%N.", true);
			}

            BatchManager::instance()->reset('thumbnails');
		}

	}
1094652
public function delete( $args, $assoc_args ) {

		$pod = pods( $assoc_args['pod'], $assoc_args['item'], false );

		if ( ! $pod->valid() ) {
			WP_CLI::error( sprintf( __( 'Pod "%s" does not exist.', 'pods' ), $assoc_args['pod'] ) );
		}

		if ( ! $pod->exists() ) {
			WP_CLI::error( sprintf( __( 'Pod "%1$s" item "%2$s" does not exist.', 'pods' ), $assoc_args['pod'], $assoc_args['item'] ) );
		}

		$deleted = false;

		try {
			$deleted = $pod->delete();
		} catch ( Exception $e ) {
			WP_CLI::error( sprintf( __( 'Error saving pod item: %s', 'pods' ), $e->getMessage() ) );
		}

		if ( $deleted ) {
			WP_CLI::success( __( 'Pod item deleted.', 'pods' ) );
		} else {
			WP_CLI::error( __( 'Pod item not deleted.', 'pods' ) );
		}

	}
28596
protected function _create( $args, $assoc_args, $callback ) {
		unset( $assoc_args[ $this->obj_id_key ] );

		$obj_id = $callback( $assoc_args );

		if ( is_wp_error( $obj_id ) ) {
			WP_CLI::error( $obj_id );
		}

		if ( Utils\get_flag_value( $assoc_args, 'porcelain' ) ) {
			WP_CLI::line( $obj_id );
		} else {
			WP_CLI::success( "Created {$this->obj_type} {$obj_id}." );
		}
	}
240223
public function remove( $args, $assoc_args ) {

		list( $menu, $location ) = $args;

		$menu = wp_get_nav_menu_object( $menu );
		if ( ! $menu || is_wp_error( $menu ) ) {
			WP_CLI::error( 'Invalid menu.' );
		}

		$locations = get_nav_menu_locations();
		if ( Utils\get_flag_value( $locations, $location ) !== $menu->term_id ) {
			WP_CLI::error( "Menu isn't assigned to location." );
		}

		$locations[ $location ] = 0;
		set_theme_mod( 'nav_menu_locations', $locations );

		WP_CLI::success( 'Removed location from menu.' );

	}
706982
public function regenerate($_, $assoc_args)
    {
        $this->init_args(func_get_args());

        $this->update_salts(true);

        if (! $this->env->save()) {
            WP_CLI::error('Failed to update salts.');
        }

        WP_CLI::success('Salts regenerated.');
    }
719635
private function runUpdate($args)
    {
        $cmd = new UpdateCommand($this->cwd);

        return $cmd->run(array_slice($args, 1));
    }
283457
public function update( $args, $assoc_args ) {
		$updates = $this->get_translation_updates();

		if ( empty( $updates ) ) {
			WP_CLI::success( 'Translations are up to date.' );

			return;
		}

		if ( empty( $args ) ) {
			$args = array( null ); // Used for core.
		}

		$upgrader      = 'WP_CLI\\LanguagePackUpgrader';
		$results       = array();
		$num_to_update = 0;

		foreach ( $args as $slug ) {
			// Gets a list of all languages.
			$all_languages = $this->get_all_languages( $slug );

			$updates_per_type = array();

			// Formats the updates list.
			foreach ( $updates as $update ) {
				if ( null !== $slug && $update->slug !== $slug ) {
					continue;
				}

				$name = 'WordPress'; // Core.

				if ( 'plugin' === $update->type ) {
					$plugins     = get_plugins( '/' . $update->slug );
					$plugin_data = array_shift( $plugins );
					$name        = $plugin_data['Name'];
				} elseif ( 'theme' === $update->type ) {
					$theme_data = wp_get_theme( $update->slug );
					$name       = $theme_data['Name'];
				}

				// Gets the translation data.
				$translation = wp_list_filter( $all_languages, array( 'language' => $update->language ) );
				$translation = (object) reset( $translation );

				$update->Type    = ucfirst( $update->type );
				$update->Name    = $name;
				$update->Version = $update->version;

				if ( isset( $translation->english_name ) ) {
					$update->Language = $translation->english_name;
				}

				if ( ! isset( $updates_per_type[ $update->type ] ) ) {
					$updates_per_type[ $update->type ] = array();
				}
				$updates_per_type[ $update->type ][] = $update;
			}

			$obj_type          = rtrim( $this->obj_type, 's' );
			$available_updates = isset( $updates_per_type[ $obj_type ] ) ? $updates_per_type[ $obj_type ] : null;

			if ( ! is_array( $available_updates ) ) {
				continue;
			}

			$num_to_update += count( $available_updates );

			if ( ! Utils\get_flag_value( $assoc_args, 'dry-run' ) ) {
				// Update translations.
				foreach ( $available_updates as $update ) {
					WP_CLI::line( "Updating '{$update->Language}' translation for {$update->Name} {$update->Version}..." );

					$result = Utils\get_upgrader( $upgrader )->upgrade( $update );

					$results[] = $result;
				}
			}
		}

		// Only preview which translations would be updated.
		if ( Utils\get_flag_value( $assoc_args, 'dry-run' ) ) {
			$update_count = count( $updates );

			WP_CLI::line(
				sprintf(
					'Found %d translation %s that would be processed:',
					$update_count,
					WP_CLI\Utils\pluralize( 'update', $update_count )
				)
			);

			Utils\format_items( 'table', $updates, array( 'Type', 'Name', 'Version', 'Language' ) );

			return;
		}

		$num_updated = count( array_filter( $results ) );

		$line = sprintf( "Updated $num_updated/$num_to_update %s.", WP_CLI\Utils\pluralize( 'translation', $num_updated ) );

		if ( $num_to_update === $num_updated ) {
			WP_CLI::success( $line );
		} elseif ( $num_updated > 0 ) {
			WP_CLI::warning( $line );
		} else {
			WP_CLI::error( $line );
		}
	}
1273693
public function invoke( $args, $assoc_args, $extra_args ) {

		if ( 'help' !== $this->name ) {
			static $prompted_once = false;

			if ( \WP_CLI::get_config( 'prompt' ) && ! $prompted_once ) {
				list( $_args, $assoc_args ) = $this->prompt_args( $args, $assoc_args );
				$args                       = array_merge( $args, $_args );
				$prompted_once              = true;
			}
		}

		$extra_positionals = array();
		foreach ( $extra_args as $k => $v ) {
			if ( is_numeric( $k ) ) {
				if ( ! isset( $args[ $k ] ) ) {
					$extra_positionals[ $k ] = $v;
				}
				unset( $extra_args[ $k ] );
			}
		}
		$args += $extra_positionals;

		list( $to_unset, $args, $assoc_args, $extra_args ) = $this->validate_args( $args, $assoc_args, $extra_args );

		foreach ( $to_unset as $key ) {
			unset( $assoc_args[ $key ] );
		}

		$path   = get_path( $this->get_parent() );
		$parent = implode( ' ', array_slice( $path, 1 ) );
		$cmd    = $this->name;
		if ( $parent ) {
			WP_CLI::do_hook( "before_invoke:{$parent}" );
			$cmd = $parent . ' ' . $cmd;
		}
		WP_CLI::do_hook( "before_invoke:{$cmd}" );

		call_user_func( $this->when_invoked, $args, array_merge( $extra_args, $assoc_args ) );

		if ( $parent ) {
			WP_CLI::do_hook( "after_invoke:{$parent}" );
		}
		WP_CLI::do_hook( "after_invoke:{$cmd}" );
	}
156123
public function url( array $args = []) {
		$url = get_term_link( $this->term );
		if ( $args ) {
			$url = add_query_arg( $args, $url );
		}

		return $url;
	}
1183152
public function get( $args, $assoc_args ) {
		list( $alias ) = $args;

		$aliases = WP_CLI::get_runner()->aliases;

		if ( empty( $aliases[ $alias ] ) ) {
			WP_CLI::error( "No alias found with key '{$alias}'." );
		}

		foreach ( $aliases[ $alias ] as $key => $value ) {
			WP_CLI::log( "{$key}: {$value}" );
		}
	}
708004
private function get_update_type_str( $assoc_args ) {
		$update_type = ' ';
		foreach ( array( 'major', 'minor', 'patch' ) as $type ) {
			if ( true === \WP_CLI\Utils\get_flag_value( $assoc_args, $type ) ) {
				$update_type = ' ' . $type . ' ';
				break;
			}
		}
		return $update_type;
	}