Magento Admin Tool to remove ALL product images - magento

Is there an admin tool in Magento which will remove all images from all products? I know you can go product-by-product and remove all images, but I'm wondering if there's an admin tool which will do all products at once?
Thanks in advance.

I am not sure why you would like to do this but here is a way to do it directly from the Database.
Backup then truncate these 2 tables:
catalog_product_entity_media_gallery
catalog_product_entity_media_gallery_value
then delete '/media/catalog/product'
clear all caches.
I haven't tested it but it should do the job. If it doesnt work then restore those 2 tables

This method is tested and does work. One reason you might want to do this is when you're testing Dataflow Import for products. When you specify images in the upload, Magento only adds images - it doesn't replace or remove them.
The net result is that several runs of a profile will accumulate a number of images that are superfluous.
mysql> **truncate catalog_product_entity_media_gallery;**
mysql> **truncate catalog_product_entity_media_gallery_value;**
Then, from the command prompt of your Magento media/catalog folder:
media/catalog$ **rm -rf ./product/**

It is a bad idea to do this via the DB, but if you must:
ALTER TABLE `catalog_product_entity_media_gallery_value`
DROP FOREIGN KEY `FK_CAT_PRD_ENTT_MDA_GLR_VAL_STORE_ID_CORE_STORE_STORE_ID`,
DROP FOREIGN KEY `FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID`;
TRUNCATE `catalog_product_entity_media_gallery_value`;
TRUNCATE `catalog_product_entity_media_gallery`;
ALTER TABLE `catalog_product_entity_media_gallery_value`
ADD CONSTRAINT `FK_CAT_PRD_ENTT_MDA_GLR_VAL_STORE_ID_CORE_STORE_STORE_ID` FOREIGN KEY (`store_id`) REFERENCES `core_store` (`store_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID` FOREIGN KEY (`value_id`) REFERENCES `catalog_product_entity_media_gallery` (`value_id`) ON DELETE CASCADE ON UPDATE CASCADE;
Then you can delete the product folders with:
cd media/catalog/product
rm -rf *

That's how I fixed it:
public function __construct(
\Magento\Catalog\Model\Product $product,
\Magento\Framework\App\ResourceConnection $resource,
\Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
\Magento\Catalog\Model\Product\Gallery\Processor $processor
) {
$this->productRepository = $productRepository;
$this->product = $product;
$this->resource = $resource;
$this->processor = $processor;
}
protected function removeImageGallery($product)
{
try {
$gallery = $this->resource->getTableName('catalog_product_entity_media_gallery');
$galleryValue = $this->resource->getTableName('catalog_product_entity_media_gallery_value');
$sql = <<<EOT
DELETE FROM {$gallery}
WHERE value_id IN (SELECT value_id FROM {$galleryValue} WHERE entity_id = {$product->getId()})
EOT;
$response = $this->resource->getConnection()->query($sql);
echo '(' . $product->getTypeId() . '): ' . $product->getSku() . " - No. Images: " . $response->rowCount() . "\n";
// // Or if you want to try the Magento way
//
// $images = $product->getMediaGalleryImages();
// foreach($images as $child){
// echo '(' . $product->getTypeId() . '): ' . $product->getSku() . ' - ' . $child->getFile() . "\n";
// $this->processor->removeImage($product, $child->getFile());
// }
//
// $this->productRepository->save($product);
} catch (\Exception $e) {
echo $e->getMessage() . "\n";
}
}

Related

Magento - Script to copy attributes from SKU and add suffix

i work on Magento 1.8.1CE
But now i need to replace a lot of values ....
Everything from attributes
SKU must be copied to Artikelnummer
And all vakues from Barcode (when not empty) should be copied to SKU with a suffix -kd
Could any help me writting a script for this?
This should do the trick. Be sure to run on a testing environment first. When it is finished check the file var/log/system.log for any errors.
<?php
require_once 'abstract.php';
class Upgrade extends Mage_Shell_Abstract
{
public function run()
{
echo 'Starting upgrade script...' . PHP_EOL;
$products = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('Artikelnummer')
->addAttributeToSelect('Barcode');
foreach ($products as $product)
{
$artikelnummer = $product->getArtikelnummer();
$barcode = $product->getBarcode();
if (!$artikelnummer || !$barcode)
{
Mage::log('Unable to update product. Skipped. SKU = ' . $product->getSku());
continue;
}
// set Artikelnummer value = SKU
$product->setArtikelnummer($product->getSku());
// set SKU = barcode + -kd suffix
$newBarcode = $barcode . '-kd';
$product->setSku($newBarcode);
$product->save();
}
echo 'Finished' . PHP_EOL;
}
}
$shell = new Upgrade;
$shell->run();

How to update data in database with CodeIgniter?

When I update the data in the database using the form below, the error following error is shown. How can I solve this error?
Cannot add or update a child row: a foreign key constraint fails
(`nov-cms`.`faqs_cat`, CONSTRAINT `faqs_cat_ibfk_20` FOREIGN KEY (`id`)
REFERENCES `tblfaqs` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)'
Form:
function editpage_($editid) {
$conn = Doctrine_Manager::connection();
$data['headingtop'] = "FAQ'S > FAQ'S > Edit FAQ'S";
$data['title_faqs'] = "Edit FAQ's";
$data['errormess'] = '';
$title_faqs = addslashes($this->input->post('title_faqs'));
$content = addslashes($this->input->post('editor1'));
$seo_description = addslashes($this->input->post('seo_description'));
$category = $this->input->post('category'); //print_r($category['cate']); exit;
$isActive = $this->input->post('isactive');
$position = $this->input->post('position');
$qryDel2 = $conn->prepare("DELETE from faqs_cat where id='$editid'");
$qryDel2->execute();
$query = $conn->prepare("UPDATE tblfaqs SET title_faqs='$title_faqs',content='$content',isActive='$isActive',position='$position',seo_description='$seo_description' WHERE id='$editid' ");
$query->execute();
$id = $conn->lastInsertId();
//when we add a page this insert a record to table, and this is id of record inserted.. this is a function default of mysql, we use to get last insert id to insert this to orther table...
foreach ($category as $data) {
$query = $conn->prepare("insert into faqs_cat (fc_id, id, category_id) values ('','$id','$data')"); //in this.
$query->execute();
}
$url = 'admin/faqs/';
echo'
<script>
window.location.href = "' . base_url() . $url . '";
</script>
';
The error is in this line:
$id = $conn->lastInsertId();
Specifically, $id remains empty because lastInsertId() is not returning a value. This causes the constraint to fail because when inserting into faqs_cat an ID is required.
If you're trying to get an auto-generated key from the database, you may need to specify a sequence name to lastInsertId depending on what type of database you're connecting to (for example, Postgres requires a sequence name). Try creating a sequence called 'mySequence' and using this instead:
$id = $conn->lastInsertId('mySequence');

Need to display catalog image not found rather than placeholder in magento

I have been stuck in a problem. I am using another server for image uploading. Let me elaborate on the issue first.
When I delete an image manually from the media folder, now placeholder image is getting showed up.
Initially
catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/c/o/controlbar-white-small.jpg
After Deleting image manually
catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/images/catalog/product/placeholder/image.jpg
My requirement is my store should still fetch the same image Url as was before deletion as image path in the database is still there.
Please help.
This is a core magento behavior so that product without image will show the placeholder instead of a broken image, so unless you make a lot of changes to core image/helper in app/code/core/Mage/Catalog/Model/Product/Image.php the only other way is to change placeholder.
Have you think about just change the placeholder image?
In admin, under System > Configuration > Catalog > Product Image Placeholders, you can upload new file.
core_config_data table
I have resolve my issue . I am mentioning the solution.
go to OnePica_ImageCDN-1.0.9\OnePica\ImageCdn\Model\Adapter\Amazons3.php
Replace this
public function getUrl($filename)
{
$type = Mage::app()->getStore()->isCurrentlySecure() ? 'url_base_secure' : 'url_base';
$base_url = Mage::getStoreConfig('imagecdn/amazons3/' . $type);
$filename = $base_url . $this->getRelative($filename);
return str_replace('\\', '/', $filename);
}
by
public function getUrl($filename)
{
$type = Mage::app()->getStore()->isCurrentlySecure() ? 'url_base_secure' : 'url_base';
$base_url = Mage::getStoreConfig('imagecdn/amazons3/' . $type);
$product = Mage::registry('current_product');
$productId = $product->getId();
$resource = Mage::getSingleton('core/resource')->getConnection('core_write');
$imageName = $resource->fetchOne("select value from catalog_product_entity_varchar where attribute_id=86 && entity_id = ".$productId);
$filename = $base_url . $this->getRelative($filename);
$filename = substr($filename, 0, -22);
$filename = $filename.$imageName;
return str_replace('\\', '/', $filename);
}

Print All Users - Joomla 2.5

I am new to Joomla. I have created website using Joomla 2.5. I have login page which is default Joomla user management system.
What I want is display all user data in a tabular format. How could I do the same?
Edit 1
I can see the users with below steps.
Go to administrator page as www.site.com/administrator.
Login as admin
Click Users >> User Manager menu and then I can see the list of users.
I want to print same list, however on the website and not on administrator site at backend.
you can do this run the query on your page where you want to show user list. you can fetch all users table field with $row object.
$db =& JFactory::getDBO();
$query = "SELECT * FROM #__users" ;
$db->setQuery($query);
$rows = $db->loadObjectList();
foreach ($rows as $row) {
echo $row->id.'|'.$row->username.'|'.$row->email;
}
Edit 1
Below is what I used.
Installed extension Flexi Custom Code.
Create module using this, add above code in it and appear that menu on the menu where you want to display.
You'll need some sort of component for this. This user profile component for example (N.B. Using this as my example as a work colleague once used it - not as customizable as I would have liked - but probably OK for what your after. I'm sure there are more as there's an entire member list category.)
Just install one of them and choose what you want to show. Add it to a menu like any other component and off you go!
Two possible solutions
Use the User Profile Component available in JED
Enable "User - Contact Creator" plugin to create a Contact profile for each new user and then use the Joomla built-in Menu Item to list all contacts
// my example with opt-groups, preselected user and better user-ids
function getUserList ($user_id) {
$db = JFactory::getDBO ();
$db->setQuery ("SELECT id, username, usertype FROM ' . $db->quoteName ('#__users') . ' ORDER BY usertype,username ASC");
$rows = $db->loadAssocList ();
static $opt_tag;
$list = '<option value="0">' . JText::_ ('SELECTION') . '</option>';
foreach ($rows as $row) {
if (empty ($opt_tag) || $opt_tag != $row['usertype']) {
$list .= '<optgroup label="' . $row['usertype'] . '">';
$opt_tag = $row['usertype'];
}
if ($row['id'] < 10) {
$id = '000' . $row['id'];
}
elseif ($row['id'] < 100) {
$id = '00' . $row['id'];
}
elseif ($row['id'] < 1000) {
$id = '0' . $row['id'];
}
$list .= '<option value="' . $row['id'] . '"' . (((int) $user_id == $row['id']) ? ' selected="SELECTED"' : '') . '>' . $id . ' - ' . $row['username'] . '</option>';
if (empty ($opt_tag) || $opt_tag != $row['usertype']) {
$list .= '</optgroup>';
}
}
return $list;
}

Magento programmatically remove product images

This must be a such a simple programming task that I absolutely cannot find any information about it on the net. Basically, I'm trying to DELETE product images. I want to delete all images from a product's media gallery. Can I do this without wading through a million lines of code for such a simple task?
Please note that I've already tried this:
$attributes = $product->getTypeInstance()->getSetAttributes();
if (isset($attributes['media_gallery'])) {
$gallery = $attributes['media_gallery'];
$galleryData = $product->getMediaGallery();//this returns NULL
foreach($galleryData['images'] as $image){
if ($gallery->getBackend()->getImage($product, $image['file'])) {
$gallery->getBackend()->removeImage($product, $image['file']);
}
}
}
This absolutely does not work. I'm trying to delete images during an import so that I do not keep accruing duplicates. Any help would be greatly appreciated.
Okay, this is how I finally fixed my problem.
if ($product->getId()){
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
foreach($items as $item)
$mediaApi->remove($product->getId(), $item['file']);
}
This is the link that finally set my head straight: http://www.magentocommerce.com/wiki/doc/webservices-api/api/catalog_product_attribute_media
Too bad it's not as simple as $product->getImages(), eh?
In Magento 1.7.0.2 I use this code for remove all images from a product gallery:
//deleting
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
With code from Davids Tay answer, I got the error:
Fatal error: Uncaught exception ‘Mage_Eav_Model_Entity_Attribute_Exception’ with message ‘SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (base_xxx.catalog_product_entity_media_gallery_value, CONSTRAINT FK_CAT_PRD_ENTT_MDA_GLR_VAL_VAL_ID_CAT_PRD_ENTT_MDA_GLR_VAL_ID FOREIGN KEY (value_id) REFERENCES `catalog_prod)’
To remove all images from a product gallery:
$product = Mage::getModel('catalog/product')->load($id);
$mediaGalleryAttribute = Mage::getModel('catalog/resource_eav_attribute')->loadByCode($entityTypeId, 'media_gallery');
$gallery = $product->getMediaGalleryImages();
foreach ($gallery as $image)
$mediaGalleryAttribute->getBackend()->removeImage($product, $image->getFile());
$product->save();
During deleting of images I found one interesting thing. When you try this code:
$galleryData = $product->getMediaGallery(); //this returns NULL
Media gallery object depends on how your product was created, if:
$product = Mage::getModel('catalog/product')->loadByAttr('sku', $sku);
then media gallery will be empty, if:
$product = Mage::getModel('catalog/product')->load($id);
then media gallery is object and you can use this object to delete images from db.
To delete images from file system you have to add such code:
#unlink(Mage::getBaseDir('media') . '\catalog\product\' . $image['file']);
but if you want to change image and name it like previous image (image1.png replace with image1.png) in this case you will have browser caching issue.
Also you can try to load media gallery for product:
$product->getResource()->getAttribute('media_gallery')->getBackend()->afterLoad($product);
This is the code I finally decided to use for this task.
protected function _removeMediaGalleryImages(Mage_Catalog_Model_Product $product)
{
$mediaGalleryData = $product->getMediaGallery();
if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {
return;
}
$toDelete = array();
foreach ($mediaGalleryData['images'] as $image) {
$toDelete[] = $image['value_id'];
}
Mage::getResourceModel('catalog/product_attribute_backend_media')->deleteGallery($toDelete);
}
Hopefully this answer isn't unwelcome, as it's technically not a solution achieved via Magento programming as you ask, but I have successfully purged all gallery images myself for the same purpose simply by truncating the relevant tables in Magento 1.4.2.0 (I believe it's the same table structure in 1.5 as well).
TRUNCATE TABLE `catalog_product_entity_media_gallery`
TRUNCATE TABLE `catalog_product_entity_media_gallery_value`
Then follow up by removing all the image files within the /media/catalog/product directory.
I did look for a way to do this programmatically myself, but found this much more efficient and have experienced no negative side effects.
Just use this code to create .php file and place it to root folder of magento.
<?php
require_once 'app/Mage.php';
Mage::app();
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$products = Mage::getModel('catalog/product')->getCollection();
//->addAttributeToFilter('entity_id', array('gt' => 14000));
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
foreach($products as $product) {
$prodID = $product->getId();
$_product = Mage::getModel('catalog/product')->load($prodID);
$items = $mediaApi->items($_product->getId());
foreach($items as $item) {
$mediaApi->remove($_product->getId(), $item['file']);
}
}
?>
What About this
Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
$mediaApi = Mage::getModel("catalog/product_attribute_media_api");
$items = $mediaApi->items($product->getId());
$attributes = $product->getTypeInstance()->getSetAttributes();
$gallery = $attributes['media_gallery'];
foreach($items as $item){
if ($gallery->getBackend()->getImage($product, $item['file'])) {
$gallery->getBackend()->removeImage($product, $item['file']);
}
}
$product->save();
Fastest way to remove image,then follow below steps:
delete all records from
catalog_product_entity_media_gallery
catalog_product_entity_media_gallery_value'
table because magento is save all product image data at those table.
Then index from Index management from admin for set image black.
Then remove image from dir then goto Your magento dir at media/catalog/product and from this folder delete all file.
Another Process:
Andy Simpson,you need a script which is delete all product from your system which will delete from DB and file system.
Step1: Create a php at root direct of magento system which include Mage.php at first code.
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Step2: set current store is admin and set Developer mode
Mage::app('admin');
Mage::setIsDeveloperMode(true);
Step3: Get Product Collection and create a loop for get one product by one by one
$productCollection=Mage::getResourceModel('catalog/product_collection');
Step4: fetch product image by one and remove image one using below code:
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
FULL CODE:
<?php
require_once "YOURMAGENTODIR/app/Mage.php";
umask(0);
Mage::app('admin');
Mage::setIsDeveloperMode(true);
$productCollection=Mage::getResourceModel('catalog/product_collection');
foreach($productCollection as $product){
echo $product->getId();
echo "<br/>";
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
echo $MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
echo "<br/>";
$MediaGallery=Mage::getModel('catalog/product_attribute_media_api')->items($product->getId());
echo "<pre>";
print_r($MediaGallery);
echo "</pre>";
foreach($MediaGallery as $eachImge){
$MediaDir=Mage::getConfig()->getOptions()->getMediaDir();
$MediaCatalogDir=$MediaDir .DS . 'catalog' . DS . 'product';
$DirImagePath=str_replace("/",DS,$eachImge['file']);
$DirImagePath=$DirImagePath;
// remove file from Dir
$io = new Varien_Io_File();
$io->rm($MediaCatalogDir.$DirImagePath);
$remove=Mage::getModel('catalog/product_attribute_media_api')->remove($product->getId(),$eachImge['file']);
}
}
If you want to remove more products like 1000 or 5000 then use bottom one with direct query.
Before try this one take backup of your database
<?php
require_once 'app/Mage.php';
umask(0);
Mage::app();
set_time_limit(0);
ini_set('display_error','1');
$resource = Mage::getSingleton('core/resource');
$connection = $resource->getConnection('core_write');
$id = 101;
$product = Mage::getModel('catalog/product')->load($id);
$q = "DELETE FROM `catalog_product_entity_media_gallery` where entity_id = '".$product->getId()."'";
$connection->query($q);
?>
Accessing the Database for such things is a bad idea.
You can delete images ( or reorder them by changing the 'position' value ) using the following snippet in a custom module ( for the sake of simplicity i'm using ObjectManager, but you should place ProductFactory and ProductRepositoryInterface in the constructor )
$objectManager = ObjectManager::getInstance();
//Get ProductFactory in order to instatiate the Product Object
$productFactory = $objectManager->get('\Magento\Catalog\Model\ProductFactory');
//We have to use ProductRepositoryInterface in order to save the changes bellow to the product
$productRepository = $objectManager->get('\Magento\Catalog\Api\ProductRepositoryInterface');
//Load a Product by ID in this case 1
$product = $productFactory->create()->load(1);
//Gets an array containing arrays representing each image in the gallery
$mediaGalleryEntries = $product->getMediaGalleryEntries();
//Here we delete every image, you can use conditions in foreach
foreach ($mediaGalleryEntries as $key => $imageEntry) {
unset($mediaGalleryEntries[$key]);
}
//Finally set the altered entries and save using productRepository
$product->setMediaGalleryEntries($mediaGalleryEntries);
$productRepository->save($product);
The code above tested in Magento 2.3 and it also removes images from the filesystem. You can use it to either delete or alter an entry ( change position, image roles etc )
To view each imageEntry you can access its data using $imageEntry->getData()
I had to do something similar not too long ago - needed to replace all product images during an import.
This link helped a lot: http://www.sharpdotinc.com/mdost/2010/03/02/magento-import-multiple-images-or-remove-images-durring-batch-import/
Hopefully it will give you a nudge in the right direction.
DELETE FROM catalog_product_entity_media_gallery WHERE value_id NOT IN (SELECT * FROM (SELECT MIN(value_id) FROM `catalog_product_entity_media_gallery` GROUP BY LEFT(value,17), entity_id having count(*) > 1) x)
why 17 ?
The expamle you have duplicate like this:
/0/0/000116810609_1.jpg
/0/0/000116810609_2.jpg
/0/0/000116810609_3.jpg
/0/0/000116810609_4.jpg
LEFT(value,17)
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
/0/0/000116810609
No they are duplicates ;)
Place the below script in magento root and execute
<?php
require_once("app/Mage.php");
umask(0);
Mage::app();
$ob = new Clean();
$ob->removemedia();
Class Clean {
function removemedia() {
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$select = $read->select()
->from('catalog_product_entity_media_gallery', '*')
->group(array('value_id'));
$flushImages = $read->fetchAll($select);
echo count($flushImages);
$array = array();
foreach ($flushImages as $item1) {
$array[] = $item1['value'];
}
$valores = $array;
$pepe = 'media' . DS . 'catalog' . DS . 'product';
$leer = $this->listDirectories($pepe);
foreach ($leer as $item) {
try {
$item = strtr($item, '\\', '/');
if (!in_array($item, $valores)) {
$valdir[]['filename'] = $item;
unlink('media/catalog/product' . $item);
}
} catch (Zend_Db_Exception $e) {
} catch (Exception $e) {
//Mage::log($e->getMessage());
}
}
}
function listDirectories($path) {
if (is_dir($path)) {
if ($dir = opendir($path)) {
while (($entry = readdir($dir)) !== false) {
if (preg_match('/^\./', $entry) != 1) {
if (is_dir($path . DS . $entry) && !in_array($entry, array('cache', 'watermark'))) {
$this->listDirectories($path . DS . $entry);
} elseif (!in_array($entry, array('cache', 'watermark')) && (strpos($entry, '.') != 0)) {
$this->result[] = substr($path . DS . $entry, 21);
}
}
}
closedir($dir);
}
}
return $this->result;
}
}

Resources