SHARE
TWEET

magento delete unused image script

a guest Feb 11th, 2014 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/bin/bash
  2. #modified by John Louis C. Garcia on Feb. 12, 2014
  3. #original source by Pieter at http://www.rapidcommerce.eu/blog/2012/08/remove-unused-magento-product-images/#comment-14649
  4. #works with remote database hostname
  5. #works also if you have cache(memcached/apc) enabled on local.xml
  6.  
  7. #instruction: change the MAGENTO_PATH.
  8.  
  9. MAGENTO_PATH="/var/www/path/to/vhost/httpdocs/path/to/magento"
  10. LOG=${MAGENTO_PATH}/var/log/imagecleanup.log
  11. DB_USER=$(sed -n 's|<username><\!\[CDATA\[\(.*\)\]\]></username>|\1|p' ${MAGENTO_PATH}/app/etc/local.xml | tr -d ' ')
  12. DB_PASS=$(sed -n 's|<password><\!\[CDATA\[\(.*\)\]\]></password>|\1|p' ${MAGENTO_PATH}/app/etc/local.xml | tr -d ' ')
  13. DB_NAME=$(sed -n 's|<dbname><\!\[CDATA\[\(.*\)\]\]></dbname>|\1|p' ${MAGENTO_PATH}/app/etc/local.xml | tr -d ' ')
  14. DB_PREFIX=$(sed -n 's|<table_prefix><\!\[CDATA\[\(.*\)\]\]></table_prefix>|\1|p' ${MAGENTO_PATH}/app/etc/local.xml | tr -d ' ')
  15. DB_REMOTEHOST=$(sed -n 's|<host><\!\[CDATA\[\(.*\)\]\]></host>|\1|p' ${MAGENTO_PATH}/app/etc/local.xml | tr -d ' ' | awk 'END{print}')
  16. function search_db() {
  17.         COUNT=$(mysql -u ${DB_USER} -p${DB_PASS} -h ${DB_REMOTEHOST} ${DB_NAME} --execute="SELECT count(*) FROM ${DB_PREFIX}catalog_product_entity_media_gallery WHERE value = \"$1\"")
  18.         echo $(echo ${COUNT} | cut -d" " -f2)
  19. }
  20.  
  21. echo "Starting image cleanup " $(date) | tee -a ${LOG}
  22. IMG_PATH=${MAGENTO_PATH}/media/catalog/product/
  23. for IMG in $(find ${IMG_PATH} -name '*.jpg' ! -path '*cache*' ! -name 'google*'); do
  24.         REL_IMG=/${IMG:${#IMG_PATH}}
  25.         if [ $(search_db ${REL_IMG/'${MAGENTO_PATH}/media/catalog/product'/}) != 1 ]; then
  26.                 IMG=${IMG##*/}
  27.                 for CACHE_IMG in $(find ${MAGENTO_PATH}/media/catalog/product/ -name "${IMG}"); do
  28.                         echo "Found unused image ${CACHE_IMG}"
  29.                         if [ "$1" ] && [ $1 == 'cleanup' ]; then
  30.                                 echo "Removing unused image ${CACHE_IMG}" | tee -a ${LOG}
  31.                                 rm "${CACHE_IMG}"
  32.                         fi
  33.                 done
  34.         else
  35.                 echo "Not touching " ${IMG}
  36.         fi
  37. done
  38. echo "Finished image cleanup " $(date) | tee -a ${LOG}
  39.  
  40.  
  41. exit 0;
RAW Paste Data
Pastebin PRO Summer Special!
Get 40% OFF on Pastebin PRO accounts!
Top