I am developing a Joomla 4 Content Slider Module and it creates thumbnails in the mysite.com/cache/mymodule/ folder. I am trying to add a delete-thumbnails button. I am using a custom form field for the first time following this tutorial (https://docs.joomla.org/Creating_a_custom_form_field_type).
I have created a modules/mod_mymodule/admin/fields/cache.php in my module and added it to the xml file like this:
<fieldset name="advanced" addfieldpath="/modules/mod_mymodule/admin/fields/">
<field name="delete_thumbs" type="Cache" label="Delete Cached Thumbnails" description="Delete Cached Thumbnails" />
Then I have added the button and everything seems okay, but while creating the delete button, I have used 2 different input types. First added a form and input, then added another one without deleting first one. It is weird, but now when I deleted first submit button and tried to use the second delete button it throws me out of module settings. When both of them are there everything is okay. What am I missing?
One more question: Might that way (using unlink command) cause a vulnerability?
Here is my cache.php. As you see at the bottom there are 2 forms to submit button. When I remove the firs one (<form id="formGoBack"), the second form button throws me out when clicked. I have hidden the first one as a solution.
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Router\Route;
jimport('joomla.form.formfield');
if(isset($_POST['delete']) && !empty($_POST['delete'])){
//find the file
$folder_path = JPATH_SITE .'/cache/mod_jt_contentslider';
// List of name of files inside
// specified folder
$files = glob($folder_path.'/*.{jpg,png,gif}', GLOB_BRACE);
foreach ( $files as $file){
if(is_file($file))
{
// Delete the given file
unlink($file);
}
}
}
class JFormFieldCache extends JFormField {
protected $type = 'Cache';
// getLabel() left out
public function getInput() {
return '
<form id="formGoBack" action="" method="post">
<input type="hidden" name="formGoBack" class="btn btn-primary" ></input>
</form>
<form method="post">
<input type="hidden" value="delete" name="delete" />
<input type="submit" value="Delete Images" /></input>
</form>';
}
}
isset($_POST['delete']) && !empty($_POST['delete'])
is a common antipattern. Why check both isset() and !empty()com_ajax
instead docs.joomla.org/Using_Joomla_Ajax_Interface.