diff --git a/wpfools/wpfools.sh b/wpfools/wpfools.sh index 857cdee..aa63b9f 100644 --- a/wpfools/wpfools.sh +++ b/wpfools/wpfools.sh @@ -6,6 +6,8 @@ # # This is a rewrite for wptool. Original source: https://code.google.com/p/wptool/ # Original code by https://code.google.com/p/wptool/people/list +# The idea is to replace as much as possible of the backend for this tool with wpcli +# (https://github.com/wp-cli/wp-cli) # # # As with the original, wptool is suite of bash functions to administer Wordpress installs. @@ -23,735 +25,949 @@ # Differences in functionality # ---------------------------- # -# >'wp-content_stock' won't be kept if there's already a wp-content present, under 'wpcore' -# >old Wordpress files are no longer in 'core_$timestamp', they'll now be in 'oldwp_$timestamp' +# > 'wp-content_stock' won't be kept if there's already a wp-content present, under 'wpcore' +# > old Wordpress files are no longer in 'core_$timestamp', they'll now be in 'oldwp_$timestamp' +# > 'wpstats' does not run tests on index.php or wp-admin/index.php +# > wpuser -u does not work for reasons. +# > wpver() does not get db version, and therefore wpcore() can't download db version #note, you can get db version with wpcli core version --extra, possibly implement db version later +# > more things # # +### + +### +# +# Things to fix +# ---------------------------- # +# > wpht() should be fixed once the feature gets implemented # # # ### -version_regex="^([[:digit:]]\.[[:digit:]]{1,2}|[[:digit:]]\.[[:digit:]]\.[[:digit:]]{1,2})$" -sha1_regex="\b[[:xdigit:]]{40}\b" -now() +#set appropriate wp binary env +wpenv() { - date -u +"%Y%m%d-%H%M%S" + #set wp_version if possible + wpver &> /dev/null + + if [[ "$wp_version" =~ $version_regex ]]; then + #non-intuitive, but this checks if the version is less than 3.5.2 + if [[ "$( echo -e "3.5.2\n$wp_version" | sort -V | head -n 1 )" != "3.5.2" ]]; then + #less than 3.5.2 + wpcli() + { + /usr/php/54/usr/bin/php-cli /usr/php/54/usr/bin/wp-compat "$@" + } + return $? + elif [[ "$( echo -e "4.4\n$wp_version" | sort -V | head -n 1 )" == "4.4" ]]; then + #greater than or equal to 4.4 + wpcli() + { + /usr/php/54/usr/bin/php-cli /usr/local/bin/wp "$@" --skip-plugins --skip-themes + } + return $? + fi + else + #assume new + echo "Unable to detect Wordpress version, assuming > 3.5.2." + fi + + #greater than or equal to 3.5.2, less than 4.4 + if [[ -f /usr/php/54/usr/bin/php-cli ]]; then + wpcli() + { + /usr/php/54/usr/bin/php-cli -c /etc/wp-cli/php.ini /usr/php/54/usr/bin/wp "$@" --skip-plugins --skip-themes + } + elif [[ -f /usr/bin/php-cli ]]; then + wpcli() + { + /usr/bin/php-cli /usr/php/54/usr/bin/wp "$@" --skip-plugins #--skip-themes + } + else + wpcli() + { + php-cli /usr/php/54/usr/bin/wp "$@" --skip-plugins --skip-themes + } + fi +} + +now() +{ + date -u +"%Y%m%d-%H%M%S" } wpcore() { arg="$1" + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 + fi + + #clean up cache, this is required because there's a bug that causes update to fail when it tries using a cached file + rm -rf ~/.wp-cli/cache/core/* + #Display help information helpText() { - echo -e " -This tool downloads the latest core, a new core of the current version, or a -specified version. - -Usage: - + echo " + This tool downloads the latest core, a new core of the current version, or a + specified version. + + Usage: wpcore [VERSION] - + download the latest stable version of the Wordpress core - #.#.# + #.#.# download version VERSION of the Wordpress core - cur + cur download new set of files matching current file version - db - download set of files matching current database version - -h + db + download new set of files matching current database version + -h display this help output -" + + Additional features: + ==================== + check-update Check for update via Version Check API. Returns latest version if there's an update, or empty if no update available. + config [--rebuild] Generate or attempt to rebuild a wp-config.php file. + download Download core WordPress files. + install Create the WordPress tables in the database. + is-installed Determine if the WordPress tables are installed. + language Modify or activate languages. + multisite-convert Transform a single-site install into a multi-site install. + multisite-install Install multisite from scratch. + update Update WordPress. + update-db Update the WordPress database. + verify-checksums Verify WordPress files against WordPress.org's checksums. + version Display the WordPress version. + " } ##TODO: fix the version stuff, sanitize #Download new set of files matching current file version fileVersion() { - version="$(wpver -q | awk '{print $1}')" - wpfile="wordpress-$version.tar.gz" + version="$( wpver -q )" } #Download new set of files matching current database version databaseVersion() { - version="$(wpver -q | awk '{print $3}')" - wpfile="wordpress-$version.tar.gz" + dbVersion="$( wpver --extra | sed -n "/Database revision/ s/.* //p" )" + if [[ -n "$dbVersion" ]]; then + version="$( curl -Ss https://codex.wordpress.org/WordPress_Versions | grep "$dbVersion" -B 4 | egrep -o -m 1 "title=\"Version .*\"" | egrep -o "$version_regex" )" + if [[ "$version" =~ $version_regex ]]; then + return 0 + fi + fi + + echo "Unable to determine file version based on database version." + return 9 } #Download new set of files matching user specified version selectedVersion() { #Sanitize user input if [[ ! "$arg" =~ $version_regex ]]; then - echo "Version specified is not valid!" + echo 'Version specified is not valid!' return 9 fi version="$arg" - wpfile="wordpress-$version.tar.gz" } #Download new set of files matching current file version latestVersion() { version="latest" - wpfile="latest.tar.gz" } - #Download Wordpress package - getFile() + updateWordpress() { - #verifies the file with an sha1 checksum - checkSha1() + #update if we're currently in a wordpress directory, download otherwise + if [[ -d ./wp-admin/ ]] && [[ -d ./wp-includes/ ]]; then + operation="update" + else + operation="download" + fi + + go() { - if [[ -f "./$wpfile" ]]; then - sha1_remote="$( curl -sS "https://wordpress.org/$wpfile.sha1" | egrep -o "$sha1_regex" )" - if [[ "$sha1_remote" =~ $sha1_regex ]]; then - #successfully got remote sha1 checksum - sha1_local="$( sha1sum "./$wpfile" | egrep -o "$sha1_regex" )" - if [[ "$sha1_local" =~ $sha1_regex ]]; then - #successfully got local sha1 checksum - if [[ "$sha1_local" == "$sha1_remote" ]]; then - #checksum match - return 0 - else - #checksum mismatch - echo -en '\nChecksum mismatch!' - rm -f "./$wpfile" - ((i++)) - return 9 - fi - else - echo -en "\nError: Unable to get local sha1 checksum" - rm -f "./$wpfile" - return 9 - fi - else - echo -en "\nError: Unable to get remote sha1 checksum" - return 9 - fi + if [[ "$version" == "latest" ]]; then + wpcli core "$operation" --force + elif [[ "$version" == "$( wpver -q )" ]]; then + ColorOff=$'\e[0m' # Text Reset + BGreen=$'\e[1;32m' # Bold Green + wpcli core "$operation" --version="$version" --force | sed -e 's|Updating to|Replacing files for|g' -e 's|Downloading update|Downloading package|g' -e 's|the update...|WordPress...|g' -e "s/Success:/${BGreen}Success:${ColorOff}/g" else - #file does not exist - echo -n "Error: Download failed" - ((i++)) - return 9 + wpcli core "$operation" --version="$version" --force fi } - if [[ "$version" == "latest" ]]; then - echo -n "Downloading latest Wordpress..." - else - echo -n "Downloading Wordpress $version..." - fi + go - if [[ ! -f "./$wpfile" ]]; then - wget -q "https://wordpress.org/$wpfile" + if (( $? != 0 )) && [[ "$operation" == update ]]; then + echo "Trying another method..." + operation="download" + go fi - - TRIES=3 - - i=0 - checkSha1 - #try a few times if it fails - while (( $? != 0 && "$i" < "$TRIES" )); do - echo -en "\nRetrying..." - wget -q "https://wordpress.org/$wpfile" - checkSha1 - done - - #too many retries - if (( "$i" >= "$TRIES" )); then - echo -e "\nFatal Error: Could not download Wordpress." - return 9 - fi - - echo "done." - return 0 } - #Extract Wordpress - extractWordpress() + #Rebuild / generate config + buildConfig() { - ##build list of Wordpress files in pwd - #build list of possible wp files - possible_files=( $( tar -ztf "./$wpfile" | sed -e "s|^wordpress/||g" -e "s|/.*|/|g" -e "/^[[:space:]]*$/d" | sort -u ) ) - possible_files=( "${possible_files[@]}" "wp-config.php" ) - #build list of actual files - for file in "${possible_files[@]}"; do - if [[ -e "./$file" ]]; then - actual_files=( "${actual_files[@]}" "$file" ) + if [[ "$1" == "--rebuild" ]]; then + if [[ ! -f ./wp-config.php ]]; then + echo 'No wp-config.php file available to rebuild!' + echo "Try: wpcore config" + return 9 fi - done - - old_wp="oldwp_$( now )" - - #rebuild a temp array without index.php - actual_files_temp=( ${actual_files[@]/index.php/} ) - - #if there's old stuff that isn't index.php - if (( "${#actual_files_temp[@]}" > 0 )); then - echo -n "Moving old Wordpress files..." - - #create old Wordpress folder - if [[ ! -d "./$old_wp/" ]]; then - mkdir "./$old_wp/" + #harmless fix so we can use cut in a sec even if their quotes are jacked up + sed -e "s/[‘’]/'/g" -e "s/[“”]/\"/g" -i ./wp-config.php + + #TODO: grep -m 1 "[^//]" + dbuser="$( grep "DB_USER" ./wp-config.php | cut -d \' -f 4 )" + dbpass="$( grep "DB_PASSWORD" ./wp-config.php | cut -d \' -f 4 )" + dbhost="$( grep "DB_HOST" ./wp-config.php | cut -d \' -f 4 )" + dbname="$( grep "DB_NAME" ./wp-config.php | cut -d \' -f 4 )" + dbprefix="$( grep "table_prefix" ./wp-config.php | cut -d \' -f 2 )" + + temp="wp-config_$( now )" + mv ./wp-config.php ./"$temp".php + + wpcli core config --dbname="$dbname" --dbuser="$dbuser" --dbpass="$dbpass" --dbhost="$dbhost" --dbprefix="$dbprefix" + if (( $? != 0 )); then + mv ./"$temp".php ./wp-config.php + echo 'Rebuild failed!' fi - - #move old Wordpress files down into a new subdir - for file in "${actual_files[@]}"; do - if [[ -e "./$file" ]]; then - rsync -aq "./$file" "./$old_wp/$file" - if [[ $? == 0 && -e "./$old_wp/$file" ]]; then - rm -rf "./$file" - fi - fi - done - - echo "done." - fi - - echo -n "Extracting Wordpress..." - - #extract the new Wordpress files into pwd - tar -xf "./$wpfile" --strip-components=1 - - didFail="0" - #test for successful extraction - for file in ${possible_files[@]/wp-config.php/}; do - if [[ ! -e "./$file" ]]; then - ##TODO: retry extracting failed file - echo -en "\nError extracting $file"'!' - didFail="1" + else + if [[ -f ./wp-config.php ]]; then + echo 'A wp-config.php file already exists!' + echo "The existing file will be replaced if you continue." + fi + echo + echo "Enter database connection settings below:" + + default="$(whoami)_wp" + unset dbname + read -rp "Database name [$default]: " dbname + if [[ -z "$dbname" ]]; then + dbname="$default" fi - done - - if (( "$didFail" == 1 )); then - echo -e "\nFatal Error: Could not extract $file." - return 9 - fi - #remove $wpfile - rm -f "./$wpfile" + default="$dbname" + unset dbuser + read -rp "Username [$default]: " dbuser + if [[ -z "$dbuser" ]]; then + dbuser="$default" + fi - echo "done." + default="$( strings /dev/urandom | egrep -o "[[:alnum:]]" | head -n 20 | tr -d "\n" )" + unset dbpass + read -rp "Password [$default]: " dbpass + if [[ -z "$dbpass" ]]; then + dbpass="$default" + fi - #if there was a wp-content dir in the old install, copy it into pwd and burn stock wp-content - if [[ -d "./$old_wp/wp-content/" ]]; then - echo -n "Moving in old wp-content..." + default="localhost" + unset dbhost + read -rp "Hostname [$default]: " dbhost + if [[ -z "$dbhost" ]]; then + dbhost="$default" + fi - rm -rf "./wp-content/" - rsync -aq "./$old_wp/wp-content/" "./wp-content/" + default="wp_" + unset dbprefix + read -rp "Table prefix [$default]: " dbprefix + if [[ -z "$dbprefix" ]]; then + dbprefix="$default" + fi - echo "done." - fi - #move in old wp-config.php if it exists - if [[ -f "./$old_wp/wp-config.php" ]]; then - echo -n "Moving in old wp-config.php..." + if [[ -f ./wp-config.php ]]; then + mv ./wp-config.php ./wp-config_"$( now )".php + fi - if [[ -f "./wp-config.php" ]]; then - rm -f "./wp-config.php" + wpcli core config --dbname="$dbname" --dbuser="$dbuser" --dbpass="$dbpass" --dbhost="$dbhost" --dbprefix="$dbprefix" + if (( $? != 0 )); then + wpcli core config --dbname="$dbname" --dbuser="$dbuser" --dbpass="$dbpass" --dbhost="$dbhost" --dbprefix="$dbprefix" --skip-check &> /dev/null fi - rsync -aq "./$old_wp/wp-config.php" "./wp-config.php" - echo "done." - else - #otherwise, move in wp-config-sample.php - mv "./wp-config-sample.php" "./wp-config.php" fi - - return 0 + unset dbpass } #process user input - if [[ "$arg" == "--help" || "$arg" =~ -[hH] ]]; then + if [[ "$1" == "--help" || "$1" =~ ^-[hH]$ ]] || [[ "$1" == "help" && -z "$2" ]]; then helpText return 0 + elif [[ "$1" == "help" && -n "$2" ]]; then + wpcli help core ${@:2} + return $? elif [[ "$arg" == "cur" || "$arg" == "file" ]]; then - fileVersion + fileVersion || return $? elif [[ "$arg" == "db" || "$arg" == "database" ]]; then - databaseVersion + databaseVersion || return $? elif [[ "$arg" =~ $version_regex ]]; then selectedVersion - elif [[ "$arg" == "latest" || -z "$arg" ]]; then - latestVersion - else + elif [[ "$arg" =~ [[:digit:]] ]]; then echo 'Unknown Wordpress version specified!' echo "Wordpress versions can be either #.# or #.#.#" helpText return 9 + elif [[ "$arg" == "latest" || -z "$arg" ]]; then + latestVersion + elif [[ "$arg" == "config" ]]; then + buildConfig "$2" + return $? + else + wpcli core "$@" + return $? fi - getFile - if (( $? != 0 )); then - return 9 - fi - extractWordpress + updateWordpress || return $? + wpcli core update-db } +wptheme() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 + fi + if [[ "$1" == "--help" || "$1" =~ ^-[hH]$ ]] || [[ "$1" == "help" && -z "$2" ]]; then + echo " + activate Activate a theme. + delete Delete a theme. + disable Disable a theme in a multisite install. + enable Enable a theme in a multisite install. + fresh Install twentyfifteen and set as active theme. + get Get a theme. + install Install a theme. + is-installed Check if the theme is installed. + list Get a list of themes. + mod Manage theme mods. + path Get the path to a theme or to the theme directory. + search Search the wordpress.org theme repository. + status See the status of one or all themes. + -u, update [--all] Update one or more themes. + use Install and activate a theme. + + -s Set only stylesheet: wptheme -s twentyfifteen + -t Set only template: wptheme -t twentyfifteen + " + elif [[ "$1" == "help" && -n "$2" ]]; then + if [[ "$2" == "-u" ]]; then + wpcli help theme update ${@:3} + elif [[ "$2" == "use" ]]; then + echo " +Equivalent to the following: + wptheme install + wptheme activate + +It is safe to use this when the theme is already installed, as wptheme install +checks to see whether the theme is installed before attempting to install it. +This means uou can *use* this to activate themes that are already installed. + " + else + wpcli help theme ${@:2} + fi + elif [[ -z "$1" ]]; then + echo + wpcli theme status + echo " +Details: + stylesheet: $(wpcli option get stylesheet) + template: $(wpcli option get template) + " + elif [[ "$1" == "fresh" ]]; then + wpcli theme install twentyfifteen + wpcli theme activate twentyfifteen + elif [[ "$1" == "use" ]]; then + wpcli theme install "$2" + wpcli theme activate "$2" + elif [[ "$1" == "-s" ]]; then + wpcli option update stylesheet "$2" + elif [[ "$1" == "-t" ]]; then + wpcli option update template "$2" + elif [[ "$1" == "-u" ]]; then + if [[ -n "$2" ]]; then + wpcli theme update ${@:2} + else + wpcli theme update --all + fi + else + wpcli theme "$@" + fi +} +wpfix() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 + fi + if [[ "$1" == "--help" || "$1" =~ ^-[hH]$ || "$1" == "help" ]]; then + echo " + This tool runs various built-in Wordpress functions and fixes. Running this command by + by itself runs some safe fixes. There are also some unsafe fixes listed below. It is + recommended that you know what you're doing before you run these, and have a backup. + + Usage: wpfix --hard # + + Unsafe Fixes + ============ + [all] Prompt for all options + [0] Rewrite htaccess file + [1] Reset all roles to default capabilities + [2] Regenerate all thumbnail images + [3] Update all plugins + [4] Update all themes + [5] Update to latest WordPress version + [6] Delete all transients + [7] Delete all comments that have been marked as spam + [8] Delete all comments that have not been approved + " + return 0 + fi + #not built in, but solves more problems than you'd think + sed -e "s/[‘’]/'/g" -e "s/[“”]/\"/g" -i ./wp-config.php + + ColorOff=$'\e[0m' # Text Reset + BGreen=$'\e[1;32m' # Bold Green + + wpcore config --rebuild + wpcli cache flush + wpcli db repair | grep -v "OK" | sed "s/Success:/${BGreen}Success:${ColorOff}/g" + wpcli db optimize | grep -v "OK" | sed "s/Success:/${BGreen}Success:${ColorOff}/g" + wpcli core update-db + wpcli transient delete-expired + + + ###HARD FIXES### + if [[ "$1" == "--hard" ]]; then + if [[ -z "$2" ]]; then + echo + echo "No option given, prompting for all." + ans="all" + else + ans="$2" + fi + yes="^[yY][eE]?[sS]?$" + fix0() + { + read -rp "Rewrite htaccess file? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + wpht + fi + } + fix1() + { + read -rp "Reset all roles to default capabilities? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + wpcli role reset --all + fi + } + fix2() + { + wpcli media regenerate #prompts on its own + } + fix3() + { + read -rp "Update all plugins? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + wpcli plugin update --all + fi + } + fix4() + { + read -rp "Update all themes? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + wpcli theme update --all + fi + } + fix5() + { + read -rp "Update to latest WordPress version? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + wpcli core update + fi + } + fix6() + { + read -rp "Delete all transients? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + wpcli transient delete-all + fi + } + fix7() + { + read -rp "Delete all comments that have been marked as spam? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + #delete spam comments + wp comment delete $( wp comment list --status=spam --format=ids ) + fi + } + fix8() + { + read -rp "Delete all comments that have not been approved? [y/n]: " response + if [[ "$response" =~ $yes ]]; then + #delete unapproved comments + wp comment delete $( wp comment list --status=unapproved --format=ids ) + fi + } + echo + unset response + if [[ "$ans" == "all" ]]; then + echo "For the following questions, the default answer is no." + for (( i = 0; i <= 8; i++ )); do + unset response + fix"$i" + done + elif [[ "$ans" =~ ^[0-8]$ ]]; then + fix"$ans" + else + echo "Fix not listed." + fi + fi +} +wpstats() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 + fi + available_version="$( wpcli core check-update --field=version | egrep -m 1 -o $version_regex )" + wp_version="$( wpver -q 2> /dev/null )" + if [[ -n "$available_version" ]]; then + version="$wp_version ($available_version available)" + else + version="$wp_version" + fi -# -# -# -# -#Code beyond this point has not been reviewed, enter at your own risk... -# -#Commits welcome :) -# -# -# -# - - - - - - - - - - - - -wpfix() { echo - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "This tool runs various built-in Wordpress functions and fixes.\n\nUsage:\n\n\twpfix\n" - return - elif [[ ! -f wp-config.php || ! -f wp-admin/upgrade-functions.php ]]; then - echo -e "Could not find one or more of the necessary files (wp-config.php or wp-admin/upgrade-functions.php)!\n" - return 9 - fi - php -q <<"EOF" && echo "Ran fix..." || echo Error running fix! -flush_rules(); - echo "Rewrite rules flushed...\n"; - wp_cache_flush(); - echo "Object cache flushed...\n"; -?> -EOF + echo " WP version: $version" + echo " user: $( wpcli user list --fields=id,user_login | sort -n | sed -n "2p" | cut -f 2 2> /dev/null )" + echo " home: $( wpcli option get home 2> /dev/null )" + echo " siteurl: $( wpcli option get siteurl 2> /dev/null )" + echo " stylesheet: $( wpcli option get stylesheet 2> /dev/null )" + echo " template: $( wpcli option get template 2> /dev/null )" echo -} - -wpht() { - echo - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "This tool generates a new .htaccess file.\n\nUsage:\n\n\twpht\n" - return - elif [[ ! -f wp-config.php || ! -f wp-admin/includes/misc.php ]]; then - echo -e "Could not find one or more of the necessary files:\n" - echo -e "\twp-config.php\n\twp-admin/includes/misc.php\n" - return 9 + + #harmless fix so we can use cut in a sec even if their quotes are jacked up + sed -e "s/[‘’]/'/g" -e "s/[“”]/\"/g" -i ./wp-config.php 2> /dev/null + + dbprefix="$( grep "table_prefix" ./wp-config.php 2> /dev/null | cut -d \' -f 2 )" + wpcli core is-installed || echo + wpcli db query "SHOW STATUS WHERE variable_name = 'Threads_running';" | grep "Threads_running" | sed "s|Threads_running|Active Connections:|g" + if [[ -z "$dbprefix" ]] && (( $( wpcli db tables 2> /dev/null | egrep -c "^$dbprefix" ) < 1 )); then + echo 'Connected with no errors, but no tables that match specified prefix!' fi - temp=$(now) - [[ -f .htaccess ]] && cp .htaccess .htaccess_$temp - php -q <<"EOF" && echo "Generated .htaccess rules..." || echo Error writing to .htaccess! -mod_rewrite_rules() ); - insert_with_markers( '.htaccess', 'WordPress', $rules ); -?> -EOF - echo + wpcli core verify-checksums 1> /dev/null } -wpconn() { - [[ -z $1 || $1 != wp* ]] && return - if [[ ! -f wp-config.php ]]; then - echo -e "\nCould not find wp-config.php!\n" - return 9 - fi - myconn="" - read -r dbhost dbname dbpass dbuser dbprefix <<< $(cat wp-config.php | egrep "^[^/].*[\"']DB_(NAME|USER|PASSWORD|HOST[^_])|table_prefix" | sort -d | sed "s/.*[\"']\(.*\)[\"'].*;.*/\1/" ) - #[[ -z $dbprefix ]] && dbprefix=$junk #sometimes there isn't a junk entry - q="USE $dbname; " - if [[ $1 == "wpdbimport" ]]; then - echo "Starting import..." - mysql -h "$dbhost" -u "$dbuser" -p"$dbpass" "$dbname" < "$2" && echo -e "Imported file '$2' to database '$dbname'.\n" || echo -e "Failed to import file '$2' to database '$dbname'!\n" - return - elif [[ $1 == "wpdbimportgz" ]]; then - echo "Starting import..." - gunzip < "$2" | mysql -h "$dbhost" -u "$dbuser" -p"$dbpass" "$dbname" && echo -e "Imported gzipped file '$2' to database '$dbname'.\n" || echo -e "Failed to import file '$2' to database '$dbname'!\n" - return - elif [[ $1 == "wpdbexport" ]]; then - echo "Starting export..." - file="$2" - [[ -z "$file" ]] && file="$dbname"_$(now).sql - mysqldump -h "$dbhost" -u "$dbuser" -p"$dbpass" "$dbname" > "$file" && echo -e "Exported database '$dbname' to file '$file'.\n" || echo -e "Failed to export database '$dbname' to file '$file'!\n" - return - elif [[ $1 == "wpdbexportgz" ]]; then - echo "Starting export..." - file="$2" - [[ -z "$file" ]] && file="$dbname"_$(now).sql.gz - mysqldump -h "$dbhost" -u "$dbuser" -p"$dbpass" "$dbname" | gzip > "$file" && echo -e "Exported gzipped database '$dbname' to file '$file'.\n" || echo -e "Failed to export database '$dbname' to file '$file'!\n" - return - elif [[ $1 == "wpdbdrop" ]]; then q='DROP database '$dbname'; CREATE DATABASE '$dbname';'; - elif [[ $1 == "wpdb" ]]; then q=$q'SHOW tables like "'$dbprefix'%";'; - elif [[ $1 == "wpdbver" ]]; then q=$q'SELECT option_value FROM '$dbprefix'options WHERE option_name = "db_version";' - elif [[ $1 == "wpurl" ]]; then q=$q'SELECT option_id, option_name, option_value FROM '$dbprefix'options WHERE option_name = "siteurl" OR option_name = "home";' - elif [[ $1 == "wpurlmod" ]]; then - [[ -z $2 ]] && echo No URL specified! && return 9 - q=$q'UPDATE '$dbprefix'options SET option_value="'$2'" WHERE option_name="siteurl" OR option_name="home";' - elif [[ $1 == "wpplug" ]]; then q=$q'SELECT option_value FROM '$dbprefix'options WHERE option_name = "active_plugins";' - elif [[ $1 == "wptheme" ]]; then q=$q'SELECT option_id, option_name, option_value FROM '$dbprefix'options WHERE option_name = "stylesheet" OR option_name = "template";' - elif [[ $1 == "wpthememod"* ]]; then - [[ -z $2 ]] && echo No theme specified! && return 9 - if [[ $1 == "wpthememod" ]]; then q=$q'UPDATE '$dbprefix'options SET option_value="'$2'" WHERE option_name="stylesheet" OR option_name="template" OR option_name="current_theme";' - elif [[ $1 == "wpthememods" ]]; then q=$q'UPDATE '$dbprefix'options SET option_value="'$2'" WHERE option_name="stylesheet";' - elif [[ $1 == "wpthememodt" ]]; then q=$q'UPDATE '$dbprefix'options SET option_value="'$2'" WHERE option_name="template" OR option_name="current_theme";' - else echo -e "\tInvalid query"! && return 1 - fi - elif [[ $1 == "wpuser" ]]; then q=$q'SELECT * FROM '$dbprefix'users LIMIT 23;' - elif [[ $1 == "wpuser1" ]]; then q=$q'SELECT user_login FROM '$dbprefix'users WHERE ID=1;' - elif [[ $1 == "wpuserinfo" ]]; then q=$q'SELECT ID, user_login, user_email, user_status, umeta_id, meta_key, meta_value FROM '$dbprefix'users JOIN '$dbprefix'usermeta ON ('$dbprefix'users.ID = '$dbprefix'usermeta.user_id) WHERE ID='$2';' - elif [[ $1 == "wpusera" ]]; then q=$q'DELETE FROM '$dbprefix'usermeta WHERE user_id='$2' AND (meta_key="'$dbprefix'capabilities" OR meta_key="'$dbprefix'user_level"); INSERT INTO '$dbprefix'usermeta (user_id,meta_key,meta_value) VALUES ('$2', "'$dbprefix'capabilities", '"'a:1:{s:13:\"administrator\";b:1;}'"'); INSERT INTO '$dbprefix'usermeta (user_id,meta_key,meta_value) VALUES ('$2', "'$dbprefix'user_level", 10); SELECT user_login FROM '$dbprefix'users WHERE ID='$2';' - elif [[ $1 == "wpuserp" ]]; then q=$q'UPDATE '$dbprefix'users SET user_pass=MD5("'$3'") WHERE ID='$2'; SELECT user_login FROM '$dbprefix'users WHERE ID='$2';' - elif [[ $1 == "wpuseru" ]]; then q=$q'SELECT user_login FROM '$dbprefix'users WHERE ID='$2'; UPDATE '$dbprefix'users SET user_login="'$3'" WHERE ID='$2';' - elif [[ $1 == "wpuserd" ]]; then q=$q'SELECT user_login FROM '$dbprefix'users WHERE ID='$2'; DELETE FROM '$dbprefix'users WHERE ID='$2'; DELETE FROM '$dbprefix'usermeta WHERE user_id='$2';' - elif [[ $1 == "wpusernew" ]]; then q=$q'INSERT INTO '$dbprefix'users (user_login, user_pass, user_email) VALUES ("deleteme", MD5("deleteme"), "deleteme@example.com"); SET @new_id=LAST_INSERT_ID(); INSERT INTO '$dbprefix'usermeta (user_id,meta_key,meta_value) VALUES (@new_id, "'$dbprefix'capabilities", '"'a:1:{s:13:\"administrator\";b:1;}'"'); INSERT INTO '$dbprefix'usermeta (user_id,meta_key,meta_value) VALUES (@new_id, "'$dbprefix'user_level", 10); SELECT @new_id;' - else echo -e "\tInvalid query"! && return 1 - fi - myconn=$(mysql -u "$dbuser" -p"$dbpass" -h "$dbhost" -e "$q" 2>&1) - if [[ 1 -eq 0 ]]; then #Debug - echo -e "\nConnected to the database..." - echo -e "Query:\n\n\t$q" - echo -e "$myconn". - elif [[ $myconn == "ERROR"* ]]; then return 9 +wpurl() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 fi -} -wpdb() { - #Need to include a optimize/fix option - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "\nThis tool tests the database connectivity based on settings in the wp-config.php file, and can import/export a database based on its settings.\n" - echo -e "Usage:\n" - echo -e "\twpdb [option [param]]\n" - echo -e "\t-i FILE\n\t\texport current database to file FILE. The specified FILE must end in .sql" - echo -e "\t-e [FILE]\n\t\texport current database to optional file FILE. If a FILE is specified, it must end in .sql\n" - return - elif [[ ! -f wp-config.php ]]; then echo Could not find wp-config.php! && return 9 - fi - wpconn "wpdb" - [[ $1 != "-q" ]] && echo -e "\n\tDB user:\t$dbuser\n\tDB pass:\t$dbpass\n\tDB host:\t$dbhost\n\tDB name:\t$dbname\n\tDB prefix:\t$dbprefix\n" - if [[ -z $myconn ]]; then - [[ $1 == "-q" ]] && echo -e "\tDatabase:\tPrefix?" || echo -e "Connected with no errors, but no tables that match specified prefix"!"\n" - elif [[ $myconn == "ERROR"* ]]; then - [[ $1 == "-q" ]] && echo -e "\tDatabase:\tError"! || echo -e "$myconn\n" - return 9 + if [[ -z "$1" ]]; then + echo " + home: $( wpcli option get home ) + siteurl: $( wpcli option get siteurl ) + " + elif [[ "$1" == "--help" || "$1" =~ ^-[hH]$ || "$1" == "help" ]]; then + echo "This tool returns the current URL settings in the database, or updates them to a specified URL. + + wpurl [URL] + " else - [[ $1 == "-q" ]] && echo -e "\tDatabase:\tOK" || echo -e "Database connection settings appear to be fine.\n" - fi - if [[ $1 == "-i" ]]; then - if [[ -z "$2" ]]; then echo -e "No import file specified!\n" - elif [[ ! -f "$2" ]]; then echo -e "File '$2' does not exist!\n" - elif [[ "$2" == *sql ]]; then wpconn "wpdbimport" "$2" - elif [[ "$2" == *sql.gz ]]; then wpconn "wpdbimportgz" "$2" - else echo -e "'$2' is not a valid file!\n" - fi - elif [[ $1 == "-e" ]]; then - if [[ -n "$2" ]]; then - if [[ -f "$2" ]]; then echo -e "File '$2' already exists!\n" - elif [[ "$2" == *sql ]]; then wpconn "wpdbexport" "$2" - elif [[ "$2" == *sql.gz ]]; then wpconn "wpdbexportgz" "$2" - else echo -e "'$2' is not a valid filename!\n" && return - fi + if [[ "$1" =~ (^http[s]?://.*) ]]; then + url="$1" else - wpconn "wpdbexport" - fi - elif [[ $1 == "drop" ]]; then - read -p "$(echo $'\t')Delete database? " -n 1 -r - if [[ $REPLY =~ ^[Yy]$ ]]; then - echo -e "\nDropping database..." - wpconn "wpdbdrop" - [[ $myconn != "ERROR"* ]] && echo -e "Dropped database!\n" || echo -e "Failed to drop database!\n" - else echo -e "\tDeletion of database '$1' cancelled"!"\n" + url="http://$1" + echo "Using: $url" fi + wpcli option update siteurl "$url" + wpcli option update home "$url" fi } -wpurl() { - [[ $1 == "-q" ]] && wpconn "wpurl" && echo "$myconn" | tail -n +2 && return - echo - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "This tool returns the current URL settings in the database, or updates them to a specified URL.\n" - echo -e "Usage:\n" - echo -e "\twpurl [URL]\n" - echo -e "\tURL\n\t\tspecify a URL to change the site to. If the URL does not start with 'http://' or 'https://' it will automatically append 'http://'.\n" - return - elif [[ ! -f wp-config.php ]]; then echo Could not find wp-config.php! && return 9 +#FIX +#hopefully this will be replaced by a feature I have requested, quick and dirty until then +wpht() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 fi - if [[ -n $1 ]]; then - newurl=$1 - [[ ! $newurl =~ https?://* ]] && newurl="http://"$newurl && echo "No 'http://' or 'https://' in provided URL"! && echo "Using '$newurl' instead..." - wpconn "wpurlmod" $newurl && echo "Updated URLs to $newurl..." + +# if [[ -f ./.htaccess ]]; then +# cp ./.htaccess ./.htaccess_"$( now )" +# fi + + #double check this + struct="$( wpcli option get permalink_structure )" + if [[ -n "$struct" ]]; then + wpcli rewrite structure "$struct" --hard else - wpconn "wpurl" - [[ -z $myconn ]] && echo -e "\thome:\tnot found\n\tsiteurl:\tnot found\n" && return - echo -e "$myconn" | tail -n +2 | awk '{print "\t"$2"("$1"):\t"$3}' + ##remove everything between BEGIN and END + #sed -i '/# BEGIN WordPress/,/# END WordPress/ d' ./.htaccess + sleep 0 fi - echo } -wptheme() { - [[ $1 != "-q" ]] && echo - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "This tool returns the current theme, as well as listing any available ones found in the wp-content/themes folder. It also can change to a specified stylesheet, template, both, or to a new copy of twentytwelve.\n" - echo -e "Usage:\n" - echo -e "\twptheme [THEME [option]]\n" - echo -e "\tTHEME\n\t\tspecify a THEME for both the stylesheet and template. If 'fresh' is specified as the theme, it will download and install the 'twentytwelve' theme." - echo -e "\tTHEME -s\n\t\tchange only the WP stylesheet" - echo -e "\tTHEME -t\n\t\tchange only the WP template\n" - return - elif [[ ! -f wp-config.php ]]; then echo Could not find wp-config.php! && return 9 +wpdb() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." fi - folder=wp-content/themes - if [[ $1 == "-q" || -z $1 ]]; then - wpconn "wptheme" - if [[ $myconn == "" ]]; then echo -e "\tstylesheet:\tnot found\n\ttemplate:\tnot found" - elif [[ $myconn != "ERROR"* ]]; then - echo -e "$myconn" | tail -2 | awk '{print "\t"$2"("$1"):\t"$3}' + + if [[ -z "$1" ]]; then + #get some database variables from wp-config.php + if [[ -f "./wp-config.php" ]]; then + #harmless fix so we can use cut in a sec even if their quotes are jacked up + sed -e "s/[‘’]/'/g" -e "s/[“”]/\"/g" -i ./wp-config.php + + dbuser="$( grep "DB_USER" ./wp-config.php | cut -d \' -f 4 )" + dbpass="$( grep "DB_PASSWORD" ./wp-config.php | cut -d \' -f 4 )" + dbhost="$( grep "DB_HOST" ./wp-config.php | cut -d \' -f 4 )" + dbname="$( grep "DB_NAME" ./wp-config.php | cut -d \' -f 4 )" + dbprefix="$( grep "table_prefix" ./wp-config.php | cut -d \' -f 2 )" + else + echo "Unable to locate the wp-config.php file, attempting to continue..." + fi + + echo " + DB user: $dbuser + DB pass: $dbpass + DB host: $dbhost + DB name: $dbname + DB prefix: $dbprefix + " + + wpcli core is-installed || echo + wpcli db query "SHOW STATUS WHERE variable_name = 'Threads_running';" | grep "Threads_running" | sed "s|Threads_running|Active Connections:|g" + if [[ -z "$dbprefix" ]] && (( $( wpcli db tables 2> /dev/null | egrep -c "^$dbprefix" ) < 1 )); then + echo 'Connected with no errors, but no tables that match specified prefix!' + fi + elif [[ "$1" == "--help" || "$1" =~ ^-[hH]$ ]] || [[ "$1" == "help" && -z "$2" ]]; then + echo " + cli Open a mysql console using the WordPress credentials. + create Create the database, as specified in wp-config.php + drop Delete the database. + export Exports the database to a file or to STDOUT. + import Import database from a file or from STDIN. + optimize Optimize the database. + query Execute a query against the database. + repair Repair the database. + reset Remove all tables from the database. + tables List the database tables. + update-db Update the WordPress database. + " + elif [[ "$1" == "update-db" ]]; then + wpcli core update-db + elif [[ "$1" == "help" && -n "$2" ]]; then + if [[ "$2" == "update-db" ]]; then + wpcli help core update-db ${@:3} + else + wpcli help db ${@:2} fi - fi - [[ ! -d $folder && $1 != "-q" ]] && mkdir -p $folder && echo -e "\nCreated $folder..." - if [[ $1 == "-q" ]]; then return - elif [[ -z $1 ]]; then - echo -e "\nAvailable themes:\n" - ls -F $folder |grep "/"|grep -v "^\."|sed "s|^\(.*\)/|\t\1|" #ls -A is overwritten by default $LS_OPTIONS in alias - elif [[ $1 == "fresh" ]]; then - wget -qP $folder https://wordpress.org/extend/themes/download/twentytwelve.1.1.zip && echo "Downloaded twentytwelve.1.1.zip..." || { - echo Unable to download twentytwelve.1.1.zip! - return 9 - } - temp=$(now) - [[ -d $folder/twentytwelve ]] && mv $folder/twentytwelve $folder/twentytwelve_$temp && echo "Moved old twentytwelve files to twentytwelve_$temp..." - unzip $folder/twentytwelve.1.1.zip -d $folder >/dev/null && echo "Extracted new twentytwelve files..." || { - echo "Failed to extract twentytwelve files"! - return 1 - } - wpconn "wpthememod" "twentytwelve" && echo "Changed to theme 'twentytwelve'..." - rm -f $folder/twentytwelve.1.1.zip && echo "Deleted twentytwelve.1.1.zip..." else - [[ ! -d wp-content/themes/$1 ]] && echo -e "No such theme"!"\n" && return 1 - if [[ $2 == "-s" ]]; then wpconn "wpthememods" $1 && echo "Changed to stylesheet '$1'..." - elif [[ $2 == "-t" ]]; then wpconn "wpthememodt" $1 && echo "Changed to template '$1'..." - elif [[ -n $2 ]]; then echo "Invalid option"! - else wpconn "wpthememod" $1 && echo "Changed to theme '$1'..."; fi + wpcli db "$@" fi - echo } -wpver() { - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e " -This tool returns the current install's file and database versions. +wpver() +{ + unset wp_version + version_regex="\b([[:digit:]]\.[[:digit:]]{1,2}|[[:digit:]]\.[[:digit:]]\.[[:digit:]]{1,2})\b" - Usage: -\twpver [option] + if [[ "$1" == "--help" || "$1" =~ ^-[hH]$ || "$1" == "help" ]]; then + /usr/php/54/usr/bin/php-cli -c /etc/wp-cli/php.ini /usr/php/54/usr/bin/wp help core version --skip-plugins --skip-themes + return 0 + fi -\t -q\n\t\tdisplay abbreviated version output -\t -h\n\t\tdisplay this help output -" - return + if [[ -f ./wp-includes/version.php ]]; then + wp_version="$( egrep -m 1 -o "$version_regex" ./wp-includes/version.php )" fi - local filever="Unknown" - local dbver="Unknown" - local dbver_files="Unknown" - [[ -f wp-includes/version.php ]] && filever=$(cat wp-includes/version.php | grep "wp_version " | sed "s/.*'\(.*\)'.*/\1/") - wpconn "wpdbver" - if [[ $? == 0 && $myconn != "ERROR"* ]]; then - dbver=$(echo -e "$myconn" | tail -1) - dbver_files=$(curl -Ss https://codex.wordpress.org/FAQ_Installation | grep "= $dbver" | head -1 | awk '{print $1}') + if [[ ! "$wp_version" =~ $version_regex ]]; then + #have to call directly because we don't call wpenv in this function; if we do, we get a mean recursive case + wp_version="$( /usr/php/54/usr/bin/php-cli -c /etc/wp-cli/php.ini /usr/php/54/usr/bin/wp core version --skip-plugins --skip-themes )" fi - if [[ "$1" == "-q" ]]; then echo -e "$filever $dbver $dbver_files" - else echo -e "\n\tWP version:\t$filever\n\tDB version:\t$dbver (up to $dbver_files)\n" + + if [[ -z "$1" ]]; then + echo " + WP version: $wp_version + " + elif [[ "$1" == "-q" ]]; then + echo "$wp_version" + else + /usr/php/54/usr/bin/php-cli -c /etc/wp-cli/php.ini /usr/php/54/usr/bin/wp core version "$@" --skip-plugins --skip-themes fi } -wpuser() { - [[ $1 != "-q" ]] && echo - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "This tool performs various user functions, including returning info for a specified user, changing usernames, passwords, changing a user to an admin, creating new admin users, and deleting users.\n" - echo -e "Usage:\n" - echo -e "\twpuser [param [option [param]]]\n" - echo -e "\tUSERID\n\t\tReturns details about specified user USERID" - echo -e "\tUSERID -u NAME\n\t\tchange username of user USERID to NAME" - echo -e "\tUSERID -p PASS\n\t\tchange password of user USERID to PASS" - echo -e "\tUSERID -a\n\t\tpromote user USERID to admin" - echo -e "\tUSERID -d\n\t\tdelete user USERID" - echo -e "\t-n, new\n\t\tcreate new admin user\n" - return - elif [[ ! -f wp-config.php ]]; then echo Could not find wp-config.php! && return 9 +wpuser() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 fi - if [[ -z $1 ]]; then wpconn "wpuser" #list users - elif [[ $1 == "-q" ]]; then wpconn "wpuser1" #list first user - elif [[ $1 =~ ^[0-9]+$ ]]; then #if a number... - if [[ $2 == "-p" ]]; then #change password... - if [[ -n $3 ]]; then wpconn "wpuserp" $1 "$3" #...if one is specified... - else echo -e "\tNo password specified"!"\n" && return 1; fi #...otherwise, end. - elif [[ $2 == "-u" ]]; then #change username... - if [[ -n $3 ]]; then wpconn "wpuseru" $1 "$3" #...if one is specified... - else echo -e "\tNo username specified"!"\n" && return 1; fi #...otherwise, end. - elif [[ $2 == "-a" ]]; then wpconn "wpusera" $1 #change to admin - elif [[ $2 == "-d" ]]; then read -p "$(echo $'\t')Delete user '$1'? " -n 1 -r && echo && [[ ! $REPLY =~ ^[Yy]$ ]] && echo -e "\tDeletion of user '$1' cancelled"!"\n" && return 1 || wpconn "wpuserd" $1 #delete user - elif [[ -z $2 ]]; then wpconn "wpuserinfo" $1 #show user info - else echo -e "\tInvalid option"!"\n" && return 1; fi #Otherwise, end. - elif [[ $1 == "new" || $1 == "-n" ]]; then wpconn "wpusernew" #create new admin... - else echo -e "\tInvalid option"!"\n" && return 1; fi #Otherwise, end. - if [[ $myconn == "" ]]; then echo -e "\tUser not found"! - elif [[ $myconn != "ERROR"* ]]; then - if [[ -z $1 ]]; then echo -e "$myconn" | tail -n +2 | awk '{print "\t"$1":\t"$2}' - elif [[ $1 == "-q" ]]; then echo $(echo -e "$myconn" | tail -1) - elif [[ $2 == "-p" ]]; then echo -e "Updated password for user $1 ('$(echo -e "$myconn" | tail -1)') to '$3'..." - elif [[ $2 == "-u" ]]; then echo -e "Updated username for user $1 from '$(echo -e "$myconn" | tail -1)' to '$3'..." - elif [[ $2 == "-a" ]]; then echo -e "Promoted user $1 to admin..." - elif [[ $2 == "-d" ]]; then echo -e "\nDeleted user $1 ('$(echo -e "$myconn" | tail -1)')..." - elif [[ $1 == "new" || $1 == "-n" ]]; then echo -e "Created new admin (user '$(echo -e "$myconn" | tail -1)') with username 'deleteme' and password 'deleteme'...\n\nMake sure to delete or rename this user"! - elif [[ -z $2 ]]; then echo -e "$myconn" | tail -n +2 + + functions=" add-cap add-role create delete generate get import-csv list list-caps meta remove-cap remove-role set-role update " + + if [[ -z "$1" ]]; then + echo + wpcli user list + echo + elif [[ "$1" == "--help" || "$1" =~ ^-[hH]$ ]] || [[ "$1" == "help" && -z "$2" ]]; then + echo " + This tool performs various user functions, including returning info for a specified + user, changing usernames, passwords, changing a user to an admin, creating new admin + users, and deleting users. + USERID can be the user login, user email, or actual user ID of the user(s) to update. + + Usage: + wpuser [param [option [param]]] + + USERID + Returns details about specified user USERID + USERID -p PASS + change password of user USERID to PASS + USERID -a + promote user USERID to admin + USERID -d [USERID2] + delete user USERID + USERID2 is the (optional) user to reassign posts to. + -n, new + create new admin user + + Additional features: + ==================== + add-cap Add a capability for a user. + add-role Add a role for a user. + create Create a user. + delete Delete one or more users from the current site. + generate Generate users. + get Get a single user. + import-csv Import users from a CSV file. + list List users. + list-caps List all user's capabilities. + meta Manage user custom fields. + remove-cap Remove a user's capability. + remove-role Remove a user's role. + set-role Set the user role (for a particular blog). + update Update a user. + " + elif [[ "$1" == "help" && -n "$2" ]]; then + wpcli help user ${@:2} + elif [[ "$1" == "-u" || "$2" == "-u" ]]; then + #Yes, I know this gives a warning and does not work. I'm assuming there's a reason for that warning, + #and not implementing a workaround because I'm also assuming that the reason is a good one. Rather + #than not implementing this feature at all, I'm including the command that should work instead to + #show users that it's not a good idea to update the username. This option is not in the help text + #and should be considered deprecated; it is included only for legacy purposes. + if [[ "$1" == "-u" ]]; then + login="$2" + username="$3" + elif [[ "$2" == "-u" ]]; then + login="$3" + username="$1" + fi + wpcli user update "$username" --user_login="$login" + elif [[ "$1" == "-p" || "$2" == "-p" ]]; then + if [[ -n "$3" ]]; then + if [[ "$1" == "-p" ]]; then + password="$2" + username="$3" + elif [[ "$2" == "-p" ]]; then + password="$3" + username="$1" + fi + else + if [[ "$1" == "-p" ]]; then + username="$2" + elif [[ "$2" == "-p" ]]; then + username="$1" + fi + read -rp "Password: " password + fi + wpcli user update "$username" --user_pass="$password" + elif [[ "$1" == "-a" || "$2" == "-a" ]]; then + if [[ "$1" == "-a" ]]; then + username="$2" + elif [[ "$2" == "-a" ]]; then + username="$1" + fi + wpcli user add-role "$username" administrator + elif [[ "$1" == "-d" || "$2" == "-d" ]]; then + if [[ "$1" == "-d" ]]; then + username="$2" + elif [[ "$2" == "-d" ]]; then + username="$1" fi - else echo "$myconn" - fi - [[ $1 != "-q" ]] && echo -} -wpplug() { - echo - folder=wp-content/plugins - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "This tool does basic plugin functions, such as displaying active and available plugins, or disabling them all.\n" - echo -e "Usage:\n" - echo -e "\twpplug [option]\n" - echo -e "\t-d\n\t\tdisable all plugins by renaming the plugins folder\n" - return - elif [[ ! -d $folder ]]; then echo "The $folder folder was not found"! && return 9 - elif [[ ! -f wp-config.php ]]; then echo Could not find wp-config.php! && return 9 - fi - if [[ $1 == "-d" ]]; then - temp=$(now) - mv $folder "$folder"_$temp && echo "Moved plugins to $folder"_$temp... - elif [[ -z $1 ]]; then - echo -e "Active plugins:\n" - wpconn "wpplug" - active=$(echo "$myconn" | tail -n +2) - php-cli -r "print_r(unserialize('$active'));" | grep "=>" | sed "s|.*=> \(.*\)|\t\1|" + if [[ -n "$3" ]]; then + wpcli user delete "$username" --reassign="$3" + else + wpcli user delete "$username" + fi + elif [[ "$1" == "-n" || "$1" == "new" ]]; then echo - echo -e "Available plugins:\n" - ls -F $folder |grep "/"|grep -v "^\."|sed "s|^\(.*\)/|\t\1|" #ls -A is overwritten by default $LS_OPTIONS in alias - fi - echo -} -wptests() { - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "This tool does basic tests on the install.\n" - echo -e "Usage:\n" - echo -e "\twptests [param [option param]]\n" - echo -e "\tall\n\t\ttests each item in wp-content/plugins on the server\n" - echo -e "\tall --url URL\n\t\ttests HTTP status code for each item in wp-content/plugins at specified url URL\n" - return - elif [[ ! -f wp-config.php ]]; then echo Could not find wp-config.php! && return 9 + default="techsupport" + unset username + read -rp "Username [$default]: " username + if [[ -z "$username" ]]; then + username="$default" + fi + + default="support@example.com" + unset email + read -rp "Email [$default]: " email + if [[ -z "$email" ]]; then + email="$default" + fi + + unset default + unset password + read -rp "Password [randomly generated]: " password + + if [[ -z "$password" ]]; then + wpcli user create "$username" "$email" --role=administrator + else + wpcli user create "$username" "$email" --role=administrator --user_pass="$password" + fi + + echo + elif [[ ! "$functions" =~ " $1 " ]]; then + #if an argument is passed and it is not one of the functions + wpcli user get "$1" + else + wpcli user "$@" fi - if [[ $2 == "--url" && -n $3 ]]; then status=$(curl -sIL -o /dev/null -w "%{http_code}\n" $3) - else status=$(php index.php >/dev/null && php wp-admin/index.php >/dev/null; echo $?); fi - [[ $1 == "-q" ]] && echo $status && return - echo - [[ $status != "255" && $status != "500" ]] && echo -e "No errors detected..." || echo -e "500 error on page"! - echo - [[ -z $1 ]] && return - [[ $1 == "all" ]] && folders="wp-content/plugins" || folders=$(echo $1|sed "s|/$||g") - temp=$(now) - if [[ $2 == "--url" && -n $3 ]]; then echo -e "*** NOTE: This test doesn't confirm items are fully functional; it simply checks the status code on '$3'. DO NOT INTERRUPT! ***\n" - else echo -e "*** NOTE: This test doesn't confirm items are fully functional; it simply tries to run index.php and wp-admin/index.php in the local shell. DO NOT INTERRUPT! ***\n"; fi - temp=$(now) - for f in $folders; do - [[ ! -d $f ]] && echo "The folder '$f' was not found"! && continue - echo "Testing $f..." - mv $f "$f"_$temp && echo "Moved $f to $f"_$temp... - mkdir $f && echo "Created new $f folder..." - status=$(wptests -q --url $3); [[ $status == "255" || $status == "500" ]] && echo "Renaming the $f folder results in a 500 error...errors below MAY be safe to ignore"! || echo "Renaming the $f folder appears to result in no error..." - for i in "$f"_$temp/*; do - [[ -f $i ]] && continue - plugin=${i##*/} - mv "$f"_$temp/$plugin $f && echo -e "\tTesting ${f%?} '$plugin'..." $( - status=$(wptests -q --url $3) - if [[ $status == "200" || $status == "0" ]]; then echo "OK" - elif [[ $status == 255 ]]; then echo "500" - else echo $status; fi - ) && mv $f/$plugin "$f"_$temp - done - mv "$f"_$temp/* $f && echo "Moved $f back to original folder..." && rm -rf "$f"_$temp && echo "Removed $f"_$temp... - done - echo + unset password } -wpstats() { - if [[ $1 == "--help" || $1 == "-h" ]]; then - echo -e "\nThis tool returns a basic overview of the Wordpress install.\n\nUsage:\n\n\twpstats\n" && return - elif [[ -n $1 ]]; then return +wpplug() +{ + wpenv + if (( $? == 1 )); then + echo "Unable to set up, or locate, a proper wp-cli environment." + return 1 fi - echo - echo -e "\tWP version:\t"$(wpver -q | awk '{print $1}') - echo -e "\tStatus code:\t"$( temp=$(wptests -q); [[ $temp != "255" ]] && echo "OK" || echo "Error"!) - if wpdb -q; then - echo -e "\tUserID 1:\t"$(wpuser -q) - wpurl -q | awk '{print "\t"$2"("$1"):\t"$3}' - wptheme -q + + if [[ -z "$1" ]]; then + echo + wpcli plugin status + echo + elif [[ "$1" == "--help" || "$1" =~ ^-[hH]$ ]] || [[ "$1" == "help" && -z "$2" ]]; then + echo " + -a, activate [--all] Activate one or more plugins. + -d, deactivate [--all] Deactivate one or more plugins. + delete Delete plugin files. + get Get a plugin. + install Install a plugin. + is-installed Check if the plugin is installed. + list Get a list of plugins. + path Get the path to a plugin or to the plugin directory. + search Search the wordpress.org plugin repository. + status See the status of one or all plugins. + toggle Toggle a plugin's activation state. + uninstall Uninstall a plugin. + -u, update [--all] Update one or more plugins. + " + elif [[ "$1" == "help" && -n "$2" ]]; then + if [[ "$2" == "-a" ]]; then + wpcli help plugin activate ${@:3} + elif [[ "$2" == "-d" ]]; then + wpcli help plugin deactivate ${@:3} + elif [[ "$2" == "-u" ]]; then + wpcli help plugin update ${@:3} + else + wpcli help plugin ${@:2} + fi + elif [[ "$1" == "-d" ]] || [[ "$1" == "deactivate" && (( "$2" == "-all" || "$2" == "--all" )) ]]; then + if [[ "$1" == "-d" && -n "$2" ]]; then + wpcli plugin deactivate ${@:2} + else + active_plugins=( $( wpcli plugin list --status=active --fields=name | sed -n "2,$ p" ) ) + if [[ -z "${active_plugins[@]}" ]]; then + echo 'No plugins active!' + else + wpcli plugin deactivate ${active_plugins[@]} + fi + fi + elif [[ "$1" == "-a" ]] || [[ "$1" == "activate" && (( "$2" == "-all" || "$2" == "--all" )) ]]; then + if [[ "$1" == "-a" && -n "$2" ]]; then + wpcli plugin activate ${@:2} + else + #The point of this is to check if someone ran a deactivate --all already, and if so, reactivate + #only the plugins that were deactivated the first time. Otherwise, activate all plugins. If you + #run this twice, it'll activate all plugins regardless. + inactive_plugins=( $( wpcli plugin list --status=inactive --fields=name | sed -n "2,$ p" ) ) + if [[ -z "${active_plugins[@]}" ]]; then + if [[ -n "${inactive_plugins[@]}" ]]; then + wpcli plugin activate ${inactive_plugins[@]} + else + echo 'All plugins active!' + fi + else + wpcli plugin activate ${active_plugins[@]} + unset active_plugins + fi + fi + elif [[ "$1" == "-u" ]] || [[ "$1" == "update" && "$2" == "-all" ]]; then + if [[ "$1" == "-u" && -n "$2" ]]; then + wpcli plugin update ${@:2} + else + wpcli plugin update --all + fi + else + wpcli plugin "$@" fi - echo } -wptool() { - echo -e " - _ ______ __ __ - | | / / __ \/ /_____ ____ / / - | | /| / / /_/ / __/ __ \/ __ \/ / - | |/ |/ / ____/ /_/ /_/ / /_/ / / - |__/|__/_/ \__/\____/\____/_/ - a toolkit production - - WPtool $wptoolv is suite of bash functions to administer Wordpress installs. - It assumes you are running said functions in the site's root folder. Each - command listed below each have a -h option for more specific information: +wphelp() +{ + echo " + The following are bash functions that call /usr/bin/wp to administer Wordpress + installs. It assumes you are running said functions in the site's root folder. + Most commands listed below have a -h option for more specific information: -\twpstats: basic overview -\twpurl: URL tools -\twptheme: theme tools -\twpdb: db tools -\twpuser: user tools -\twpplug: plugin tools -\twpht: .htaccess generator -\twpcore: core replacement tools -\twpfix: built-in WP fixes -\twpver: returns version info -" + wpstats: basic overview + wpurl: URL tools + wptheme: theme tools + wpdb: db tools + wpuser: user tools + wpplug: plugin tools + wpht: .htaccess generator + wpcore: core replacement tools + wpfix: built-in WP fixes + wpver: returns version info + " } - -#search, multisite -wptoolv="1.7.1.2" -echo -e "\n Injected WPtool $wptoolv into current session. For details, type 'wptool'.\n" -unset HISTFILE