Tag field type #141

Closed
opened 2017-10-16 01:53:19 +00:00 by mwweb · 4 comments
mwweb commented 2017-10-16 01:53:19 +00:00 (Migrated from github.com)

How exactly does the tag field type work? You can add it to an admin view, but it doesn't create a db field, so guessing that it links to the tag table. But then, if you try adding to a dynamic get, so you could filter by tag, or display tags, it doesn't work.

How exactly does the tag field type work? You can add it to an admin view, but it doesn't create a db field, so guessing that it links to the tag table. But then, if you try adding to a dynamic get, so you could filter by tag, or display tags, it doesn't work.

The option to filter by tag has not been fully developed yet. At this time you will have to custom code that.

But yet it does add it to the tag table and uses the Joomla API surrounding the tags.

The option to filter by tag has not been fully developed yet. At this time you will have to custom code that. But yet it does add it to the tag table and uses the Joomla API surrounding the tags.
sepehr09 commented 2017-10-16 19:32:02 +00:00 (Migrated from github.com)

i have question for File form field type :
https://docs.joomla.org/File_form_field_type
when user browse file & submit form nothing happened! is necessary we have to create custom code for Receiving The File With PHP ? https://docs.joomla.org/Creating_a_file_uploader_in_your_component & that should done in after save method ?
what if we have several file fields ? we have to create reciver for each fields? (foreach maybe?) .

i have question for File form field type : [https://docs.joomla.org/File_form_field_type](https://docs.joomla.org/File_form_field_type) when user browse file & submit form nothing happened! is necessary we have to create custom code for Receiving The File With PHP ? [https://docs.joomla.org/Creating_a_file_uploader_in_your_component](https://docs.joomla.org/Creating_a_file_uploader_in_your_component) & that should done in after save method ? what if we have several file fields ? we have to create reciver for each fields? (foreach maybe?) .

The uploading of files is best done with media field. If you want to do your own file up loader, yes then you would need to add the custom coding.

I did a project where I needed to upload many files and so I build an up loader (many custom scripts) that I can now use in other components. So it can be done 👍

I have not yet made those scripts available to the public.

But a few tips, use a note-field with ajax instead... look at this https://getuikit.com/v2/docs/upload.html

Then in the ajax area add some controllers to catch the post and move the files where you please.

Here is some of the script I used in my ajax "model"

// set some buckets
protected $target;
protected $targetType;
protected $formatType;

// set some defaults
protected $formats = 
	array( 
		'image_formats' => array(
			1 => 'jpg',
			2 => 'jpeg',
			3 => 'gif',
			4 => 'png'),
		'document_formats' => array(
			1 => 'doc',
			2 => 'docx',
			3 => 'odt',
			4 => 'pdf',
			5 => 'csv',
			6 => 'xls',
			7 => 'xlsx',
			8 => 'ods',
			9 => 'ppt',
			10 => 'pptx',
			11 => 'pps',
			12 => 'ppsx',
			13 => 'odp',
			14 => 'zip'),
		'media_formats' => array(
			1 => 'mp3',
			2 => 'm4a',
			3 => 'ogg',
			4 => 'wav',
			5 => 'mp4',
			6 => 'm4v',
			7 => 'mov',
			8 => 'wmv',
			9 => 'avi',
			10 => 'mpg',
			11 => 'ogv',
			12 => '3gp',
			13 => '3g2'));

// file details
protected $fileName;
protected $filePath;
protected $fullPath;
protected $fileFormat;
// return error if upload fails
protected $errorMessage;
// set uploading values
protected $use_streams = false;
protected $allow_unsafe = false;
protected $safeFileOptions = array();

public function uploadfile($target, $type)
{
	// get the view values
	$view = $this->getViewID();
	if (in_array($target, $this->targets) && isset($this->types[$type]) && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews))
	{
		$this->target = (string) $target;
		$this->targetType = (string) $type;
		$this->formatType = (string) $this->types[$type];
		if ($package = $this->_getPackageFromUpload())
		{
			// now we move the file into place
			return $this->uploadNow($package, $view);
		}
		return array('error' => $this->errorMessage);
	}
	return array('error' => JText::_('There has been an error.'));
}

protected function uploadNow($package, $view)
{
	// set the package name to file name if found
	$name = $this->formatType;
	if (isset($package['packagename']))
	{
		$name = [[[Component]]]Helper::safeString(str_replace('.'.$this->fileFormat, '', $package['packagename']), 'filename', '_', false);
	}
	$this->fileName = $this->target.'_'.$this->targetType.'_'.$this->fileFormat.'_'.[[[Component]]]Helper::randomkey(20).'VDM'.$name;
	// set the folder path
	if ($this->formatType === 'document' || $this->formatType === 'media')
	{
		// get the file path
		$this->filePath = [[[Component]]]Helper::getFilePath('path', 'hiddenfilepath');
	}
	else
	{
		// get the file path
		$this->filePath = [[[Component]]]Helper::getFilePath();
	}
	// set full path to the file
	$this->fullPath = $this->filePath . $this->fileName . '.' . $this->fileFormat;
	// move to target folder
	if (JFile::move($package['dir'], $this->fullPath))
	{
		// do crop/resize if it is an image and cropping is set
		if ($this->formatType === 'image')
		{
			[[[Component]]]Helper::resizeImage($this->fileName, $this->fileFormat, $this->target, $this->filePath, $this->fullPath);
		}
		// Get the basic encription.
		$basickey = [[[Component]]]Helper::getCryptKey('basic');
		$basic = null;
		// set link options
		$linkOptions = [[[Component]]]Helper::getLinkOptions();
		// set link options
		if ($basickey)
		{
			// Get the encryption object.
			$basic = new FOFEncryptAes($basickey, 128);
		}
		// when it is documents we need to give file name in base64
		if ($this->formatType === 'document' || $this->formatType === 'media')
		{
			// store the name
			$keyName = $this->fileName;
			if ([[[Component]]]Helper::checkObject($basic))
			{
				// Get the encryption object.
				$localFile = [[[Component]]]Helper::base64_urlencode($basic->encryptString($keyName));
			}
			else
			{
				// can not get the encryption object so only base64 encode
				$localFile = [[[Component]]]Helper::base64_urlencode($keyName, true);
			}
		}
		// check if we must update the current item
		if (isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view']))
		{
			$object = new stdClass();
			$object->id = (int) $view['a_id'];
			if ($this->targetType === 'image' || $this->targetType === 'document')
			{
				if ($linkOptions['lock'] && [[[Component]]]Helper::checkObject($basic))
				{
					// Get the encryption object.
					$object->{$this->target.'_'.$this->targetType} = $basic->encryptString($this->fileName);
				}
				else
				{
					// can not get the encryption object.
					$object->{$this->target.'_'.$this->targetType} = $this->fileName;
				}
			}
			elseif ($this->targetType === 'images' || $this->targetType === 'documents' || $this->targetType === 'media')
			{
				$this->fileName = $this->setFileNameArray('add', $basic, $view);
				if ($linkOptions['lock'] && [[[Component]]]Helper::checkObject($basic))
				{
					// Get the encryption object.
					$object->{$this->target.'_'.$this->targetType} = $basic->encryptString($this->fileName);
				}
				else
				{
					// can not get the encryption object.
					$object->{$this->target.'_'.$this->targetType} = $this->fileName;
				}
				
			}
			JFactory::getDbo()->updateObject('#__[[[component]]]_'.$view['a_view'], $object, 'id');
		}
		elseif ($this->targetType === 'images' || $this->targetType === 'documents' || $this->targetType === 'media')
		{
			$this->fileName = array($this->fileName);
			$this->fileName =  '["'.implode('", "', $this->fileName).'"]';
		}
		// set the results
		$result = array('success' =>  $this->fileName, 'fileformat' => $this->fileFormat);
		// add some more values if document format type
		if ($this->formatType === 'document' || $this->formatType === 'media')
		{
			$tokenLink = '';
			if ($linkOptions['lock'] == 0)
			{
				$localFile = [[[Component]]]Helper::base64_urlencode($keyName, true);
			}
			if ($linkOptions['session'])
			{
				$tokenLink = '&token=' . JSession::getFormToken();
			}
			// if document
			if ($this->formatType === 'document')
			{
				$result['link'] = 'index.php?option=com_[[[component]]]&task=download.document&file=' . $localFile . $tokenLink;
			}
			// if media
			elseif ($this->formatType === 'media')
			{
				$result['link'] = 'index.php?option=com_[[[component]]]&task=download.media&file=' . $localFile . $tokenLink;
			}
			$result['key'] = $keyName;
		}
		return $result;
	}
	$this->remove($package['packagename']);
	return array('error' =>  JText::_('There has been an error.'));
}

public function removeFile($oldFile, $target, $clearDB, $type)
{
	// get view values
	$view = $this->getViewID();
	if (in_array($target, $this->targets) && isset($this->types[$type]) && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews))
	{
		$this->target = (string) $target;
		$this->targetType = (string) $type;
		$this->formatType = (string) $this->types[$type];
		$this->fileName = (string) $oldFile;
		if (isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view']))
		{
			// get user to see if he has permission to upload
			$user = JFactory::getUser();
			if (!$user->authorise($view['a_view'].'.edit.'.$this->target.'_'.$this->targetType, 'com_[[[component]]]'))
			{
				return array('error' =>  JText::_('You do not have permission to remove this file.'));
			}
		}
		if ($this->formatType === 'document' || $this->formatType === 'media')
		{
			// get the file path
			$this->filePath = [[[Component]]]Helper::getFilePath('path', 'hiddenfilepath');
		}
		else
		{
			// get the file path
			$this->filePath = [[[Component]]]Helper::getFilePath();
		}
		// remove from the db if there is an id
		if ($clearDB == 1 && isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews))
		{
			$object = new stdClass();
			$object->id = (int) $view['a_id'];
			if ($this->targetType === 'image' || $this->targetType === 'document')
			{
				$object->{$this->target.'_'.$this->targetType} = '';
				JFactory::getDbo()->updateObject('#__[[[component]]]_'.$view['a_view'], $object, 'id');
			}
			elseif ($this->targetType === 'images' || $this->targetType === 'documents' || $this->targetType === 'media')
			{
				// Get the basic encription.
				$basickey = [[[Component]]]Helper::getCryptKey('basic');
				$basic = null;
				// set link options
				$linkOptions = [[[Component]]]Helper::getLinkOptions();
				if ($linkOptions['lock'] && $basickey)
				{
					// Get the encryption object.
					$basic = new FOFEncryptAes($basickey, 128);
				}
				$fileNameArray = $this->setFileNameArray('remove', $basic, $view);
				if ($linkOptions['lock'] && [[[Component]]]Helper::checkObject($basic))
				{
					// Get the encryption object.
					$object->{$this->target.'_'.$this->targetType} = $basic->encryptString($fileNameArray);
				}
				else
				{
					// can not get the encryption object.
					$object->{$this->target.'_'.$this->targetType} = $fileNameArray;
				}
				JFactory::getDbo()->updateObject('#__[[[component]]]_'.$view['a_view'], $object, 'id');
			}
		}
		// load the file class
		jimport('joomla.filesystem.file');
		// remove file with this filename
		$fileFormats = $this->formats[$this->formatType .'_formats'];
		foreach ($fileFormats as $fileFormat)
		{
			if (JFile::exists($this->filePath . $this->fileName . '.' . $fileFormat))
			{
				// remove the file
				return JFile::delete($this->filePath . $this->fileName . '.' . $fileFormat);
			}
		}
	}
	return array('error' => JText::_('There has been an error.'));
}

protected function setFileNameArray($action, $basic, $view)
{
	$curentFiles = [[[Component]]]Helper::getVar($view['a_view'], $view['a_id'], 'id', $this->target.'_'.$this->targetType);
	// unlock if needed
	if ($basic && $curentFiles === base64_encode(base64_decode($curentFiles, true)))
	{
		// basic decrypt data banner_image.
		$curentFiles = rtrim($basic->decryptString($curentFiles), "\0");
	}
	// convert to array if needed
	if ([[[Component]]]Helper::checkJson($curentFiles))
	{
		$curentFiles = json_decode($curentFiles, true);
	}
	// remove or add the file name
	if ([[[Component]]]Helper::checkArray($curentFiles))
	{
		if ('add' === $action)
		{
			$curentFiles[] = $this->fileName;
		}
		else
		{
			if(($key = array_search($this->fileName, $curentFiles)) !== false)
			{
				unset($curentFiles[$key]);
			}
		}
	}
	elseif ('add' === $action)
	{
		$curentFiles = array($this->fileName);
	}
	else
	{
		$curentFiles = '';
	}
	// convert to json
	if ([[[Component]]]Helper::checkArray($curentFiles))
	{
		return '["'.implode('", "', $curentFiles).'"]';
	}
	return '';
}

/**
 * Works out an importation file from a HTTP upload
 *
 * @return file definition or false on failure
 */
protected function _getPackageFromUpload()
{		
	// Get the uploaded file information
	$app	= JFactory::getApplication();
	$input	= $app->input;

	// See JInputFiles::get.
	$userfiles = $input->files->get('files', null, 'array');
	
	// Make sure that file uploads are enabled in php
	if (!(bool) ini_get('file_uploads'))
	{
		$this->errorMessage = JText::_('Warning, import file error.');
		return false;
	}

	// get the files from array
	$userfile = null;
	if (is_array($userfiles))
	{
		$userfile = array_values($userfiles)[0]; 
	}

	// If there is no uploaded file, we have a problem...
	if (!is_array($userfile))
	{
		$this->errorMessage = JText::_('No import file selected.');
		return false;
	}

	// Check if there was a problem uploading the file.
	if ($userfile['error'] || $userfile['size'] < 1)
	{
		$this->errorMessage = JText::_('Warning, import upload error.');
		return false;
	}

	// Build the appropriate paths
	$config		= JFactory::getConfig();
	$tmp_dest	= $config->get('tmp_path') . '/' . $userfile['name'];
	$tmp_src	= $userfile['tmp_name'];

	// Move uploaded file
	jimport('joomla.filesystem.file');
	jimport('joomla.filesystem.folder');
	$p_file = JFile::upload($tmp_src, $tmp_dest, $this->use_streams, $this->allow_unsafe, $this->safeFileOptions);

	// Was the package downloaded?
	if (!$p_file)
	{
		$session = JFactory::getSession();
		$session->clear('package');
		$session->clear('dataType');
		$session->clear('hasPackage');
		$this->errorMessage = JText::_('Could not upload the file!');
		// was not uploaded
		return false;
	}

	// check that this is a valid file
	$package = $this->check($userfile['name']);

	return $package;
}

/**
 * Check a file and verifies it as a allowed file format file
 *
 * @param   string  $archivename  The uploaded package filename or import directory
 *
 * @return  array  of elements
 *
 */
protected function check($archivename)
{
	// Clean the name
	$archivename = JPath::clean($archivename);
	// get file format
	$this->fileFormat = strtolower(pathinfo($archivename, PATHINFO_EXTENSION));
	// get fileFormat key
	$allowedFormats = array();
	if (in_array($this->fileFormat, $this->formats[$this->formatType .'_formats']))
	{
		// get allowed formats
		$allowedFormats = (array) $this->app_params->get($this->formatType.'_formats', null);
	}
	// check the extension
	if (!in_array($this->fileFormat, $allowedFormats))
	{
		// Cleanup the import files
		$this->remove($archivename);
		$this->errorMessage = JText::_('Does not have a valid file type.');
		return false;
	}

	// check permission if user
	$view = $this->getViewID();
	if (isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews))
	{
		// get user to see if he has permission to upload
		$user = JFactory::getUser();
		if (!$user->authorise($view['a_view'].'.edit.'.$this->target.'_'.$this->targetType, 'com_[[[component]]]'))
		{
			// Cleanup the import files
			$this->remove($archivename);
			$this->errorMessage = JText::_('You do not have permission to upload an '.$this->targetType);
			return false;
		}
	}
	
	$config			= JFactory::getConfig();
	// set Package Name
	$check['packagename']	= $archivename;
	
	// set directory
	$check['dir']		= $config->get('tmp_path'). '/' .$archivename;
	
	return $check;
}

/**
 * Clean up temporary uploaded file
 *
 * @param   string  $package    Name of the uploaded file
 *
 * @return  boolean  True on success
 *
 */
protected function remove($package)
{
	jimport('joomla.filesystem.file');
	
	$config		= JFactory::getConfig();
	$package	= $config->get('tmp_path'). '/' .$package;

	// Is the package file a valid file?
	if (is_file($package))
	{
		JFile::delete($package);
	}
	elseif (is_file(JPath::clean($package)))
	{
		// It might also be just a base filename
		JFile::delete(JPath::clean($package));
	}
}

You will see that these scripts will not work unless you know how to adapt it into your own project. So I am not sure if this will even help. But at least it will give you an idea of why using media field is easier.

The uploading of files is best done with media field. If you want to do your own file up loader, yes then you would need to add the custom coding. I did a project where I needed to upload many files and so I build an up loader (many custom scripts) that I can now use in other components. So it can be done :+1: I have not yet made those scripts available to the public. But a few tips, use a note-field with ajax instead... look at this https://getuikit.com/v2/docs/upload.html Then in the ajax area add some controllers to catch the post and move the files where you please. Here is some of the script I used in my ajax "model" ``` // set some buckets protected $target; protected $targetType; protected $formatType; // set some defaults protected $formats = array( 'image_formats' => array( 1 => 'jpg', 2 => 'jpeg', 3 => 'gif', 4 => 'png'), 'document_formats' => array( 1 => 'doc', 2 => 'docx', 3 => 'odt', 4 => 'pdf', 5 => 'csv', 6 => 'xls', 7 => 'xlsx', 8 => 'ods', 9 => 'ppt', 10 => 'pptx', 11 => 'pps', 12 => 'ppsx', 13 => 'odp', 14 => 'zip'), 'media_formats' => array( 1 => 'mp3', 2 => 'm4a', 3 => 'ogg', 4 => 'wav', 5 => 'mp4', 6 => 'm4v', 7 => 'mov', 8 => 'wmv', 9 => 'avi', 10 => 'mpg', 11 => 'ogv', 12 => '3gp', 13 => '3g2')); // file details protected $fileName; protected $filePath; protected $fullPath; protected $fileFormat; // return error if upload fails protected $errorMessage; // set uploading values protected $use_streams = false; protected $allow_unsafe = false; protected $safeFileOptions = array(); public function uploadfile($target, $type) { // get the view values $view = $this->getViewID(); if (in_array($target, $this->targets) && isset($this->types[$type]) && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews)) { $this->target = (string) $target; $this->targetType = (string) $type; $this->formatType = (string) $this->types[$type]; if ($package = $this->_getPackageFromUpload()) { // now we move the file into place return $this->uploadNow($package, $view); } return array('error' => $this->errorMessage); } return array('error' => JText::_('There has been an error.')); } protected function uploadNow($package, $view) { // set the package name to file name if found $name = $this->formatType; if (isset($package['packagename'])) { $name = [[[Component]]]Helper::safeString(str_replace('.'.$this->fileFormat, '', $package['packagename']), 'filename', '_', false); } $this->fileName = $this->target.'_'.$this->targetType.'_'.$this->fileFormat.'_'.[[[Component]]]Helper::randomkey(20).'VDM'.$name; // set the folder path if ($this->formatType === 'document' || $this->formatType === 'media') { // get the file path $this->filePath = [[[Component]]]Helper::getFilePath('path', 'hiddenfilepath'); } else { // get the file path $this->filePath = [[[Component]]]Helper::getFilePath(); } // set full path to the file $this->fullPath = $this->filePath . $this->fileName . '.' . $this->fileFormat; // move to target folder if (JFile::move($package['dir'], $this->fullPath)) { // do crop/resize if it is an image and cropping is set if ($this->formatType === 'image') { [[[Component]]]Helper::resizeImage($this->fileName, $this->fileFormat, $this->target, $this->filePath, $this->fullPath); } // Get the basic encription. $basickey = [[[Component]]]Helper::getCryptKey('basic'); $basic = null; // set link options $linkOptions = [[[Component]]]Helper::getLinkOptions(); // set link options if ($basickey) { // Get the encryption object. $basic = new FOFEncryptAes($basickey, 128); } // when it is documents we need to give file name in base64 if ($this->formatType === 'document' || $this->formatType === 'media') { // store the name $keyName = $this->fileName; if ([[[Component]]]Helper::checkObject($basic)) { // Get the encryption object. $localFile = [[[Component]]]Helper::base64_urlencode($basic->encryptString($keyName)); } else { // can not get the encryption object so only base64 encode $localFile = [[[Component]]]Helper::base64_urlencode($keyName, true); } } // check if we must update the current item if (isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view'])) { $object = new stdClass(); $object->id = (int) $view['a_id']; if ($this->targetType === 'image' || $this->targetType === 'document') { if ($linkOptions['lock'] && [[[Component]]]Helper::checkObject($basic)) { // Get the encryption object. $object->{$this->target.'_'.$this->targetType} = $basic->encryptString($this->fileName); } else { // can not get the encryption object. $object->{$this->target.'_'.$this->targetType} = $this->fileName; } } elseif ($this->targetType === 'images' || $this->targetType === 'documents' || $this->targetType === 'media') { $this->fileName = $this->setFileNameArray('add', $basic, $view); if ($linkOptions['lock'] && [[[Component]]]Helper::checkObject($basic)) { // Get the encryption object. $object->{$this->target.'_'.$this->targetType} = $basic->encryptString($this->fileName); } else { // can not get the encryption object. $object->{$this->target.'_'.$this->targetType} = $this->fileName; } } JFactory::getDbo()->updateObject('#__[[[component]]]_'.$view['a_view'], $object, 'id'); } elseif ($this->targetType === 'images' || $this->targetType === 'documents' || $this->targetType === 'media') { $this->fileName = array($this->fileName); $this->fileName = '["'.implode('", "', $this->fileName).'"]'; } // set the results $result = array('success' => $this->fileName, 'fileformat' => $this->fileFormat); // add some more values if document format type if ($this->formatType === 'document' || $this->formatType === 'media') { $tokenLink = ''; if ($linkOptions['lock'] == 0) { $localFile = [[[Component]]]Helper::base64_urlencode($keyName, true); } if ($linkOptions['session']) { $tokenLink = '&token=' . JSession::getFormToken(); } // if document if ($this->formatType === 'document') { $result['link'] = 'index.php?option=com_[[[component]]]&task=download.document&file=' . $localFile . $tokenLink; } // if media elseif ($this->formatType === 'media') { $result['link'] = 'index.php?option=com_[[[component]]]&task=download.media&file=' . $localFile . $tokenLink; } $result['key'] = $keyName; } return $result; } $this->remove($package['packagename']); return array('error' => JText::_('There has been an error.')); } public function removeFile($oldFile, $target, $clearDB, $type) { // get view values $view = $this->getViewID(); if (in_array($target, $this->targets) && isset($this->types[$type]) && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews)) { $this->target = (string) $target; $this->targetType = (string) $type; $this->formatType = (string) $this->types[$type]; $this->fileName = (string) $oldFile; if (isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view'])) { // get user to see if he has permission to upload $user = JFactory::getUser(); if (!$user->authorise($view['a_view'].'.edit.'.$this->target.'_'.$this->targetType, 'com_[[[component]]]')) { return array('error' => JText::_('You do not have permission to remove this file.')); } } if ($this->formatType === 'document' || $this->formatType === 'media') { // get the file path $this->filePath = [[[Component]]]Helper::getFilePath('path', 'hiddenfilepath'); } else { // get the file path $this->filePath = [[[Component]]]Helper::getFilePath(); } // remove from the db if there is an id if ($clearDB == 1 && isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews)) { $object = new stdClass(); $object->id = (int) $view['a_id']; if ($this->targetType === 'image' || $this->targetType === 'document') { $object->{$this->target.'_'.$this->targetType} = ''; JFactory::getDbo()->updateObject('#__[[[component]]]_'.$view['a_view'], $object, 'id'); } elseif ($this->targetType === 'images' || $this->targetType === 'documents' || $this->targetType === 'media') { // Get the basic encription. $basickey = [[[Component]]]Helper::getCryptKey('basic'); $basic = null; // set link options $linkOptions = [[[Component]]]Helper::getLinkOptions(); if ($linkOptions['lock'] && $basickey) { // Get the encryption object. $basic = new FOFEncryptAes($basickey, 128); } $fileNameArray = $this->setFileNameArray('remove', $basic, $view); if ($linkOptions['lock'] && [[[Component]]]Helper::checkObject($basic)) { // Get the encryption object. $object->{$this->target.'_'.$this->targetType} = $basic->encryptString($fileNameArray); } else { // can not get the encryption object. $object->{$this->target.'_'.$this->targetType} = $fileNameArray; } JFactory::getDbo()->updateObject('#__[[[component]]]_'.$view['a_view'], $object, 'id'); } } // load the file class jimport('joomla.filesystem.file'); // remove file with this filename $fileFormats = $this->formats[$this->formatType .'_formats']; foreach ($fileFormats as $fileFormat) { if (JFile::exists($this->filePath . $this->fileName . '.' . $fileFormat)) { // remove the file return JFile::delete($this->filePath . $this->fileName . '.' . $fileFormat); } } } return array('error' => JText::_('There has been an error.')); } protected function setFileNameArray($action, $basic, $view) { $curentFiles = [[[Component]]]Helper::getVar($view['a_view'], $view['a_id'], 'id', $this->target.'_'.$this->targetType); // unlock if needed if ($basic && $curentFiles === base64_encode(base64_decode($curentFiles, true))) { // basic decrypt data banner_image. $curentFiles = rtrim($basic->decryptString($curentFiles), "\0"); } // convert to array if needed if ([[[Component]]]Helper::checkJson($curentFiles)) { $curentFiles = json_decode($curentFiles, true); } // remove or add the file name if ([[[Component]]]Helper::checkArray($curentFiles)) { if ('add' === $action) { $curentFiles[] = $this->fileName; } else { if(($key = array_search($this->fileName, $curentFiles)) !== false) { unset($curentFiles[$key]); } } } elseif ('add' === $action) { $curentFiles = array($this->fileName); } else { $curentFiles = ''; } // convert to json if ([[[Component]]]Helper::checkArray($curentFiles)) { return '["'.implode('", "', $curentFiles).'"]'; } return ''; } /** * Works out an importation file from a HTTP upload * * @return file definition or false on failure */ protected function _getPackageFromUpload() { // Get the uploaded file information $app = JFactory::getApplication(); $input = $app->input; // See JInputFiles::get. $userfiles = $input->files->get('files', null, 'array'); // Make sure that file uploads are enabled in php if (!(bool) ini_get('file_uploads')) { $this->errorMessage = JText::_('Warning, import file error.'); return false; } // get the files from array $userfile = null; if (is_array($userfiles)) { $userfile = array_values($userfiles)[0]; } // If there is no uploaded file, we have a problem... if (!is_array($userfile)) { $this->errorMessage = JText::_('No import file selected.'); return false; } // Check if there was a problem uploading the file. if ($userfile['error'] || $userfile['size'] < 1) { $this->errorMessage = JText::_('Warning, import upload error.'); return false; } // Build the appropriate paths $config = JFactory::getConfig(); $tmp_dest = $config->get('tmp_path') . '/' . $userfile['name']; $tmp_src = $userfile['tmp_name']; // Move uploaded file jimport('joomla.filesystem.file'); jimport('joomla.filesystem.folder'); $p_file = JFile::upload($tmp_src, $tmp_dest, $this->use_streams, $this->allow_unsafe, $this->safeFileOptions); // Was the package downloaded? if (!$p_file) { $session = JFactory::getSession(); $session->clear('package'); $session->clear('dataType'); $session->clear('hasPackage'); $this->errorMessage = JText::_('Could not upload the file!'); // was not uploaded return false; } // check that this is a valid file $package = $this->check($userfile['name']); return $package; } /** * Check a file and verifies it as a allowed file format file * * @param string $archivename The uploaded package filename or import directory * * @return array of elements * */ protected function check($archivename) { // Clean the name $archivename = JPath::clean($archivename); // get file format $this->fileFormat = strtolower(pathinfo($archivename, PATHINFO_EXTENSION)); // get fileFormat key $allowedFormats = array(); if (in_array($this->fileFormat, $this->formats[$this->formatType .'_formats'])) { // get allowed formats $allowedFormats = (array) $this->app_params->get($this->formatType.'_formats', null); } // check the extension if (!in_array($this->fileFormat, $allowedFormats)) { // Cleanup the import files $this->remove($archivename); $this->errorMessage = JText::_('Does not have a valid file type.'); return false; } // check permission if user $view = $this->getViewID(); if (isset($view['a_id']) && $view['a_id'] > 0 && isset($view['a_view']) && in_array($view['a_view'], $this->allowedViews)) { // get user to see if he has permission to upload $user = JFactory::getUser(); if (!$user->authorise($view['a_view'].'.edit.'.$this->target.'_'.$this->targetType, 'com_[[[component]]]')) { // Cleanup the import files $this->remove($archivename); $this->errorMessage = JText::_('You do not have permission to upload an '.$this->targetType); return false; } } $config = JFactory::getConfig(); // set Package Name $check['packagename'] = $archivename; // set directory $check['dir'] = $config->get('tmp_path'). '/' .$archivename; return $check; } /** * Clean up temporary uploaded file * * @param string $package Name of the uploaded file * * @return boolean True on success * */ protected function remove($package) { jimport('joomla.filesystem.file'); $config = JFactory::getConfig(); $package = $config->get('tmp_path'). '/' .$package; // Is the package file a valid file? if (is_file($package)) { JFile::delete($package); } elseif (is_file(JPath::clean($package))) { // It might also be just a base filename JFile::delete(JPath::clean($package)); } } ``` You will see that these scripts will not work unless you know how to adapt it into your own project. So I am not sure if this will even help. But at least it will give you an idea of why using media field is easier.

@sepehr09 would you like JCB to do all of that for you? I am thinking we could in the future have that build in... if you are willing to help 👍

@sepehr09 would you like JCB to do all of that for you? I am thinking we could in the future have that build in... if you are willing to help :+1:
Sign in to join this conversation.
No Milestone
No project
No Assignees
1 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: joomla/Component-Builder#141
No description provided.