Skip to content

Instantly share code, notes, and snippets.

@Llewellynvdm
Created April 6, 2018 07:33
Show Gist options
  • Save Llewellynvdm/b9ce6e9a1ea7435736c350557bdc6f5a to your computer and use it in GitHub Desktop.
Save Llewellynvdm/b9ce6e9a1ea7435736c350557bdc6f5a to your computer and use it in GitHub Desktop.
Drag and Drop Upload functionality in JCB
// add the style sheets
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/css/uikit.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/css/components/accordion.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/css/components/tooltip.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/css/components/notify.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/css/components/form-file.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/css/components/progress.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/css/components/placeholder.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addStyleSheet( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2//css/components/upload.gradient.min.css' , (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
// add JavaScripts
$document->addScript( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/js/uikit.min.js', (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addScript( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/js/components/accordion.min.js', (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addScript( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/js/components/tooltip.min.js', (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addScript( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/js/components/lightbox.min.js', (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addScript( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/js/components/notify.min.js', (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
$document->addScript( JURI::root(true) .'/media/com_[[[component]]]/uikit-v2/js/components/upload.min.js', (###Component###Helper::jVersion()->isCompatible('3.8.0')) ? array('version' => 'auto') : 'text/css');
[CUSTOMCODE=getViewID]
// allowed views
protected $allowedViews = array('document');
// allowed targets
protected $targets = array('main', 'doc');
// allowed types
protected $types = array('image' => 'image', 'images' => 'image', 'document' => 'document', 'documents' => 'document', 'media' => 'media');
[CUSTOMCODE=phpAjaxUploader]
// load the links on the page
$document->addScriptDeclaration("var documentsLinks = " . json_encode($this->item->links) . ";");
function getFile(filename, fileFormat, target, type){
// set the link
var link = '<?php echo [[[Component]]]Helper::getFolderPath('url'); ?>';
// build the return
if (type === 'image') {
var thePath = link+filename+'.'+fileFormat;
var thedelete = '<button onclick="removeFileCheck(\''+filename+'\', \''+target+'\', \''+type+'\')" type="button" class="uk-button uk-width-1-1 uk-button-small uk-margin-small-bottom uk-button-danger"><i class="uk-icon-trash"></i> <?php echo JText::_('Remove'); ?> '+target+' '+type+'</button></div>';
return '<img alt="'+target+' Image" src="'+thePath+'" /><br /><br />'+thedelete;
} else if (type === 'images') {
var imageNum = filename.length;
if (imageNum == 1) {
var gridClass = ' uk-grid-width-1-1';
var perRow = 1;
} else if (imageNum == 2) {
var gridClass = ' uk-grid-width-1-2';
var perRow = 2;
} else {
var gridClass = ' uk-grid-width-1-3';
var perRow = 3;
}
var counter = 1;
var imagesBox = '<div class="uk-grid'+gridClass+'">';
jQuery.each(filename, function(i, item) {
imagesBox += '<div class="uk-panel">';
var fileFormat = item.split('_')[2];
var thePath = link+item+'.'+fileFormat;
var thedelete = '<button onclick="removeFileCheck(\''+item+'\', \''+target+'\', \''+type+'\')" type="button" class="uk-button uk-width-1-1 uk-button-small uk-margin-small-bottom uk-button-danger"><i class="uk-icon-trash"></i> <?php echo JText::_('Remove'); ?> '+target+' '+type+'</button>';
imagesBox += '<img alt="'+target+' Image" src="'+thePath+'" /><br /><br />'+thedelete;
if (perRow == counter) {
counter = 0;
if (imageNum == perRow) {
imagesBox += '</div>';
} else {
imagesBox += '</div></div><div class="uk-grid'+gridClass+'">';
}
} else {
imagesBox += '</div>';
}
counter++;
});
return imagesBox + '</div></div></div>';
} else if (type === 'documents' || type === 'media') {
var fileNum = filename.length;
if (fileNum == 1) {
var gridClass = ' uk-grid-width-1-1';
var perRow = 1;
} else if (fileNum == 2) {
var gridClass = ' uk-grid-width-1-2';
var perRow = 2;
} else {
var gridClass = ' uk-grid-width-1-3';
var perRow = 3;
}
var counter = 1;
var fileBox = '<div class="uk-grid'+gridClass+'">';
jQuery.each(filename, function(i, item) {
fileBox += '<div class="uk-panel">';
var fileFormat = item.split('_')[2];
// set the file name
var fileName = item.split('VDM')[1]+'.'+fileFormat;
// set the placeholder
var theplaceholder = '<div class="uk-width-1-1"><div class="uk-panel uk-panel-box"><center><code>[DOCLINK='+fileName+']</code> <?php echo JText::_('or'); ?> <code>[DOCBUTTON='+fileName+']</code><br /><?php echo JText::_('Add one of these placeholders in text for custom download placement'); ?>.</center></div></div>';
// get the download link if set
var thedownload = '';
if (documentsLinks.hasOwnProperty(item)) {
thedownload = '<a href="'+JRouter(documentsLinks[item])+'" class="uk-button uk-width-1-1 uk-button-small uk-margin-small-bottom uk-button-success"><i class="uk-icon-download"></i> <?php echo JText::_('Download'); ?> '+fileName+'</a>';
}
var thedelete = '<button onclick="removeFileCheck(\''+item+'\', \''+target+'\', \''+type+'\')" type="button" class="uk-button uk-width-1-1 uk-button-small uk-margin-small-bottom uk-button-danger"><i class="uk-icon-trash"></i> <?php echo JText::_('Remove'); ?> '+fileName+'</button>';
fileBox += theplaceholder+thedownload+thedelete;
if (perRow == counter) {
counter = 0;
if (fileNum == perRow) {
fileBox += '</div>';
} else {
fileBox += '</div></div><div class="uk-grid'+gridClass+'">';
}
} else {
fileBox += '</div>';
}
counter++;
});
return fileBox + '</div></div></div>';
} else if (type === 'document') {
var fileFormat = filename.split('_')[2];
// set the file name
var fileName = filename.split('VDM')[1]+'.'+fileFormat;
// set the placeholder
var theplaceholder = '<div class="uk-width-1-1"><div class="uk-panel uk-panel-box"><center><code>[DOCLINK='+fileName+']</code> <?php echo JText::_('or'); ?> <code>[DOCBUTTON='+fileName+']</code><br /><?php echo JText::_('Add one of these placeholders in text for custom download placement'); ?>.</center></div></div>';
// get the download link if set
var thedownload = '';
if (documentsLinks.hasOwnProperty(filename)) {
thedownload = '<a href="'+JRouter(documentsLinks[filename])+'" class="uk-button uk-width-1-1 uk-button-small uk-margin-small-bottom uk-button-success"><i class="uk-icon-download"></i> <?php echo JText::_('Download'); ?> '+fileName+'</a>';
}
var thedelete = '<button onclick="removeFileCheck(\''+filename+'\', \''+target+'\', \''+type+'\')" type="button" class="uk-button uk-width-1-1 uk-button-small uk-margin-small-bottom uk-button-danger"><i class="uk-icon-trash"></i> <?php echo JText::_('Remove'); ?> '+fileName+'</button>';
return theplaceholder+thedownload+thedelete + '</div>';
}
}
// set links array
$item->links = array();
// link options
$linkoptions = [[[Component]]]Helper::getLinkOptions();
// add session token
$linkToken = '';
if ($linkoptions['session'])
{
$linkToken = '&token=' . JSession::getFormToken();
}
// add session token
$linkCounter = '&counter=' . $item->id;
// build document download links
if (!empty($item->main_documents) && [[[Component]]]Helper::checkJson($item->main_documents) && !is_numeric($item->main_documents))
{
$documents = json_decode($item->main_documents);
if ([[[Component]]]Helper::checkArray($documents))
{
// build links
foreach($documents as $document)
{
if ($linkoptions['lock'] && isset($basickey) && $basickey)
{
// Get the encryption object.
$localFile = [[[Component]]]Helper::base64_urlencode($basic->encryptString($document));
}
else
{
// can not get the encryption object so only base64 encode
$localFile = [[[Component]]]Helper::base64_urlencode($document, true);
}
// load links
$item->links[$document] = 'index.php?option=com_[[[component]]]&task=download.document&file=' . $localFile . $linkToken . $linkCounter;
}
}
}
// build media download links
if (!empty($item->main_media) && [[[Component]]]Helper::checkJson($item->main_media) && !is_numeric($item->main_media))
{
$media = json_decode($item->main_media);
if ([[[Component]]]Helper::checkArray($media))
{
// build links
foreach($media as $file)
{
if ($linkoptions['lock'] && isset($basickey) && $basickey)
{
// Get the encryption object.
$localFile = [[[Component]]]Helper::base64_urlencode($basic->encryptString($file));
}
else
{
// can not get the encryption object so only base64 encode
$localFile = [[[Component]]]Helper::base64_urlencode($file, true);
}
// load links
$item->links[$file] = 'index.php?option=com_[[[component]]]&task=download.media&file=' . $localFile . $linkToken . $linkCounter;
}
}
}
<field
type="hidden"
name="main_documents"
default=""
/>
<?php
$app = JFactory::getApplication();
?>
function JRouter(link) {
<?php
if ($app->isSite())
{
echo 'var url = "'.JURI::root().'";';
}
else
{
echo 'var url = "";';
}
?>
return url+link;
}
<field
type="note"
name="main_documents_uploader"
label="Documents"
description="<div id='upload-drop-main-documents' class='uk-placeholder'><br /><br /><i class='uk-icon-cloud-upload uk-icon-medium uk-text-muted uk-margin-small-right'></i> Upload Your <strong>documents</span></strong> by dropping the file here or <a class='uk-form-file'>selecting the file from your computer<input id='upload-select-main-documents' type='file'></a> (formates allowed: <span id='main-documents-formats'></span>)<br /><br /><br /></div><div id='progressbar-main-documents' class='uk-progress uk-hidden'><div class='uk-progress-bar' style='width: 0%;'>...</div></div>"
/>
[CUSTOMCODE=uikitFileUploader+document,documents,main]
// 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 $folderPath;
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 folder path
$this->folderPath = [[[Component]]]Helper::getFolderPath('path', 'hiddenfilepath');
}
else
{
// get the file path
$this->folderPath = [[[Component]]]Helper::getFolderPath();
}
// set full path to the file
$this->fullPath = $this->folderPath . $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->folderPath, $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->folderPath = [[[Component]]]Helper::getFolderPath('path', 'hiddenfilepath');
}
else
{
// get the file path
$this->folderPath = [[[Component]]]Helper::getFolderPath();
}
// 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->folderPath . $this->fileName . '.' . $fileFormat))
{
// remove the file
return JFile::delete($this->folderPath . $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));
}
}
function setFilekey(filename, fileFormat, target, type){
var currentFileName = jQuery("#jform_"+target+"_"+type).val();
if (currentFileName.length > 20 && (type === 'image' || type === 'document')){
// remove file from server
removeFile_server(currentFileName, target, 2, type);
}
// set new key
if ((filename.length > 20 && (type === 'image' || type === 'document')) || (isJsonString(filename) && (type === 'images' || type === 'documents' || type === 'media'))){
if((type === 'images' || type === 'documents' || type === 'media') && jQuery("#jform_id").val() == 0 && isJsonString(currentFileName)) {
var newA = jQuery.parseJSON(currentFileName);
var newB = jQuery.parseJSON(filename);
var filename = JSON.stringify(jQuery.merge(newA, newB));
}
jQuery("#jform_"+target+"_"+type).val(filename);
// set the FILE
return setFile(filename, fileFormat, target, type);
}
return false;
}
function setFile(filename, fileFormat, target, type){
if (type === 'image' || type === 'document') {
if (!target) {
target = filename.split('_')[0];
}
if (!type) {
type = filename.split('_')[1];
}
if (!fileFormat) {
fileFormat = filename.split('_')[2];
}
var isAre = 'is';
} else if ((type === 'images' || type === 'documents' || type === 'media') && isJsonString(filename) ) {
filename = jQuery.parseJSON(filename);
if (!target) {
target = filename[0].split('_')[0];
}
if (!type) {
type = filename[0].split('_')[1];
}
var isAre = 'are';
} else {
return false;
}
// set icon
if (type === 'images' || type === 'image') {
var icon = 'file-image-o';
} else {
var icon = 'file';
}
var thenotice = '<div class="success-'+target+'-'+type+'-8768"><div class="uk-alert uk-alert-success" data-uk-alert><p class="uk-text-center"><span class="uk-text-bold uk-text-large"><i class="uk-icon-'+icon+'"></i> Your '+target+' '+type+' '+isAre+' set </span> </p></div>';
var thefile = getFile(filename, fileFormat, target, type);
jQuery("."+target+"_"+type+"_uploader").append(thenotice+thefile);
// all is done
return true;
}
function removeFileCheck(clearServer, target, type){
UIkit.modal.confirm('Are you sure you want to delete this '+target+'?', function(){ removeFile(clearServer, target, 1, type); });
}
function removeFile(clearServer, target, flush, type){
if ((clearServer.length > 20 && (type === 'image' || type === 'document')) || (clearServer.length > 1 && (type === 'images' || type === 'documents' || type === 'media'))){
// remove file from server
removeFile_server(clearServer, target, flush, type);
}
jQuery(".success-"+target+"-"+type+"-8768").remove();
// remove locally
if (clearServer.length > 20 && (type === 'image' || type === 'document')) {
// remove the file
jQuery("#jform_"+target+"_"+type).val('');
} else if (clearServer.length > 20 && (type === 'images' || type === 'documents' || type === 'media')) {
// get the old values
var filenames = jQuery("#jform_"+target+"_"+type).val();
if (isJsonString(filenames)) {
filenames = jQuery.parseJSON(filenames);
// remove the current file from those values
filenames = jQuery.grep(filenames, function(value) {
return value != clearServer;
});
if (typeof filenames == 'object' && !jQuery.isEmptyObject(filenames)) {
// set the new values
var filename = JSON.stringify(filenames);
jQuery("#jform_"+target+"_"+type).val(filename);
setFile(filename, 0, target, type);
} else {
jQuery("#jform_"+target+"_"+type).val('');
}
} else {
jQuery("#jform_"+target+"_"+type).val('');
}
}
}
function removeFile_server(currentFileName, target, flush, type){
var getUrl = JRouter("index.php?option=com_[[[component]]]&task=ajax.removeFile&format=json&vdm="+vastDevMod);
if(token.length > 0 && target.length > 0 && type.length > 0){
var request = 'token='+token+'&filename='+currentFileName+'&target='+target+'&flush='+flush+'&type='+type;
}
return jQuery.ajax({
type: 'GET',
url: getUrl,
dataType: 'jsonp',
data: request,
jsonp: 'callback'
});
}
function isJsonString(str) {
if (typeof str != 'string') {
str = JSON.stringify(str);
}
try {
var json = jQuery.parseJSON(str);
} catch(err) {
return false;
}
if (typeof json == 'object' && isEmpty(json)) {
return false;
} else if(typeof json == 'object') {
return true;
}
return false;
}
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return true;
}
<?php if ($formats = $componentParams->get('[[[arg0]]]_formats', null)) : ?>
jQuery(function($){
var progressbar = $("#progressbar-[[[arg2]]]-[[[arg1]]]"),
bar = progressbar.find('.uk-progress-bar'),
settings = {
action: JRouter('index.php?option=com_[[[component]]]&task=ajax.uploadfile&format=json&type=[[[arg1]]]&target=[[[arg2]]]&raw=true&token='+token+'&vdm='+vastDevMod), // upload url
allow : '*.(<?php echo implode('|', $formats); ?>)', // allow uploads
loadstart: function() {
jQuery(".success-[[[arg2]]]-[[[arg1]]]-8768").remove();
bar.css("width", "0%").text("0%");
progressbar.removeClass("uk-hidden");
},
progress: function(percent) {
percent = Math.ceil(percent);
bar.css("width", percent+"%").text(percent+"%");
},
allcomplete: function(response) {
bar.css("width", "100%").text("100%");
response = JSON.parse(response);
setTimeout(function(){
progressbar.addClass("uk-hidden");
}, 250);
if (response.error){
alert(response.error);
} else if (response.success) {
// load the link to the document links object
documentsLinks[response.key] = response.link;
// set the new file name and if another is found delete it
setFilekey(response.success, response.fileformat, '[[[arg2]]]', '[[[arg1]]]');
}
}
};
var select = UIkit.uploadSelect($("#upload-select-[[[arg2]]]-[[[arg1]]]"), settings),
drop = UIkit.uploadDrop($("#upload-drop-[[[arg2]]]-[[[arg1]]]"), settings);
});
jQuery('#[[[arg2]]]-[[[arg1]]]-formats').html('<b><?php echo implode(', ', $formats); ?></b>');
<?php else: ?>
jQuery('#upload-drop-[[[arg2]]]-[[[arg1]]]').html('<b><?php echo JText::_('Allowed [[[arg0]]] formats are not set in the global settings, please notify your system administrator.'); ?></b>');
<?php endif; ?>
jQuery(document).ready(function($)
{
var image = jQuery('#jform_doc_image').val();
if (image.length > 20)
{
setFile(image, false, 'doc', 'image')
}
// set the documents
var documents = jQuery('#jform_main_documents').val();
if (isJsonString(documents))
{
setFile(documents, false, 'main', 'documents');
}
// set the media
var media = jQuery('#jform_main_media').val();
if (isJsonString(media))
{
setFile(media, false, 'main', 'media');
}
});
[CUSTOMCODE=setFileJS]
[CUSTOMCODE=jsRouter]
[CUSTOMCODE=getFileJS]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment