Media manager insert and delete files, ajax files improves

This commit is contained in:
Diego Najar 2018-04-13 23:32:29 +02:00
parent 2b2e24c84a
commit 2deedb8766
11 changed files with 203 additions and 68 deletions

View File

@ -66,6 +66,14 @@ $amountOfPages = count($listOfFilesByPage);
echo 'var preLoadFiles = '.json_encode($preLoadFiles).';'; echo 'var preLoadFiles = '.json_encode($preLoadFiles).';';
?> ?>
function openMediaManager() {
$('#jsbluditMediaModal').modal('show')
}
function closeMediaManager() {
$('#jsbluditMediaModal').modal('hide')
}
// Remove all files from the table // Remove all files from the table
function cleanFiles() { function cleanFiles() {
$('#jsbluditMediaTable').empty(); $('#jsbluditMediaTable').empty();
@ -77,13 +85,13 @@ function displayFiles(files) {
cleanFiles(); cleanFiles();
// Regenerate the table // Regenerate the table
$.each(files, function(key, filename) { $.each(files, function(key, filename) {
tableRow = '<tr>'+ tableRow = '<tr id="js'+filename+'">'+
'<td style="width:80px"><img class="img-thumbnail" alt="200x200" src="<?php echo HTML_PATH_UPLOADS_THUMBNAILS ?>'+filename+'" style="width: 50px; height: 50px;"></td>'+ '<td style="width:80px"><img class="img-thumbnail" alt="200x200" src="<?php echo HTML_PATH_UPLOADS_THUMBNAILS ?>'+filename+'" style="width: 50px; height: 50px;"></td>'+
'<td>'+ '<td class="information">'+
'<div>'+filename+'</div>'+ '<div>'+filename+'</div>'+
'<div>'+ '<div>'+
'<button type="button" class="btn btn-link p-0 mr-2">Insert</button>'+ '<button onClick="insertMedia(\''+filename+'\'); closeMediaManager();" type="button" class="btn btn-link p-0 mr-2">Insert</button>'+
'<button type="button" class="btn btn-link p-0 mr-2">Delete</button>'+ '<button onClick="deleteMedia(\''+filename+'\')" type="button" class="btn btn-link p-0 mr-2">Delete</button>'+
'</div>'+ '</div>'+
'</td>'+ '</td>'+
'</tr>'; '</tr>';
@ -93,13 +101,27 @@ function displayFiles(files) {
// Get the list of files via AJAX, filter by the page number // Get the list of files via AJAX, filter by the page number
function getFiles(pageNumber) { function getFiles(pageNumber) {
$.getJSON("<?php echo HTML_PATH_ADMIN_ROOT ?>ajax/list-files", $.post("<?php echo HTML_PATH_ADMIN_ROOT ?>ajax/list-files",
{ pageNumber: pageNumber, path: "<?php echo PATH_UPLOADS_THUMBNAILS ?>"}, { tokenCSRF: tokenCSRF,
pageNumber: pageNumber,
path: "<?php echo PATH_UPLOADS_THUMBNAILS ?>"
},
function(data) { function(data) {
displayFiles(data.files); displayFiles(data.files);
}); });
} }
// Delete the file and the thumbnail if exist
function deleteMedia(filename) {
$.post("<?php echo HTML_PATH_ADMIN_ROOT ?>ajax/delete-file",
{ tokenCSRF: tokenCSRF,
filename: filename
},
function(data) {
getFiles(1);
});
}
$(document).ready(function() { $(document).ready(function() {
// Display the files preloaded for the first time // Display the files preloaded for the first time
displayFiles(preLoadFiles); displayFiles(preLoadFiles);
@ -122,13 +144,16 @@ $(document).ready(function() {
if (xhr.upload) { if (xhr.upload) {
xhr.upload.addEventListener("progress", function(e) { xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) { if (e.lengthComputable) {
var percentComplete = e.loaded / e.total; var percentComplete = (e.loaded / e.total)*100;
$("#jsbluditProgressBar").width(percentComplete+"%"); $("#jsbluditProgressBar").width(percentComplete+"%");
} }
}, false); }, false);
} }
return xhr; return xhr;
} }
}).done(function() {
// Get the files of the first page, this include the uploaded files
getFiles(1);
}); });
}); });
}); });

View File

@ -18,6 +18,9 @@
</head> </head>
<body> <body>
<!-- Javascript variables and function -->
<?php include(PATH_JS.'functions.php') ?>
<!-- TOPBAR --> <!-- TOPBAR -->
<?php include('html/topbar.php'); ?> <?php include('html/topbar.php'); ?>
@ -36,10 +39,10 @@
<!-- TABS --> <!-- TABS -->
<ul class="nav nav-tabs" id="dynamicTab" role="tablist"> <ul class="nav nav-tabs" id="dynamicTab" role="tablist">
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" id="content-tab" data-toggle="tab" href="#content" role="tab" aria-controls="content" aria-selected="true">Content</a> <a class="nav-link active" id="content-tab" data-toggle="tab" href="#content" role="tab" aria-controls="content" aria-selected="true">Content</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link active" id="images-tab" data-toggle="tab" href="#images" role="tab" aria-controls="images" aria-selected="false">Images</a> <a class="nav-link" id="images-tab" data-toggle="tab" href="#images" role="tab" aria-controls="images" aria-selected="false">Images</a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link " id="options-tab" data-toggle="tab" href="#options" role="tab" aria-controls="options" aria-selected="false">Options</a> <a class="nav-link " id="options-tab" data-toggle="tab" href="#options" role="tab" aria-controls="options" aria-selected="false">Options</a>
@ -48,7 +51,7 @@
<form class="tab-content mt-3" id="dynamicTabContent"> <form class="tab-content mt-3" id="dynamicTabContent">
<!-- TABS CONTENT --> <!-- TABS CONTENT -->
<div class="tab-pane" id="content" role="tabpanel" aria-labelledby="content-tab"> <div class="tab-pane show active" id="content" role="tabpanel" aria-labelledby="content-tab">
<?php <?php
// Title // Title
@ -71,7 +74,13 @@
</div> </div>
<!-- TABS IMAGES --> <!-- TABS IMAGES -->
<div class="tab-pane show active" id="images" role="tabpanel" aria-labelledby="images-tab"> <div class="tab-pane" id="images" role="tabpanel" aria-labelledby="images-tab">
<?php
echo Bootstrap::formTitle(array('title'=>'Select images'));
?>
<button type="button" class="btn" data-toggle="modal" data-target="#jsbluditMediaModal">Media Manager</button>
<?php <?php
echo Bootstrap::formTitle(array('title'=>'Cover image')); echo Bootstrap::formTitle(array('title'=>'Cover image'));
@ -80,10 +89,16 @@
<img class="img-thumbnail" alt="200x200" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22200%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20200%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_1627e1b2b7e%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_1627e1b2b7e%22%3E%3Crect%20width%3D%22200%22%20height%3D%22200%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2274.4296875%22%20y%3D%22104.65%22%3E200x200%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true" style="width: 100px; height: 100px;"> <img class="img-thumbnail" alt="200x200" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22200%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20200%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_1627e1b2b7e%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A10pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_1627e1b2b7e%22%3E%3Crect%20width%3D%22200%22%20height%3D%22200%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2274.4296875%22%20y%3D%22104.65%22%3E200x200%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true" style="width: 100px; height: 100px;">
<?php <?php
echo Bootstrap::formTitle(array('title'=>'Select images')); echo Bootstrap::formTitle(array('title'=>'External Cover image'));
?> ?>
<button type="button" class="btn" data-toggle="modal" data-target="#jsbluditMediaModal">Media Manager</button> <?php
echo Bootstrap::formInputTextBlock(array(
'name'=>'externalCoverImage',
'placeholder'=>'https://',
'tip'=>'You can set a cover image from external URL, such as a CDN or some server dedicate for images.'
));
?>
</div> </div>
<!-- TABS OPTIONS --> <!-- TABS OPTIONS -->
@ -140,11 +155,16 @@
// Parent // Parent
echo Bootstrap::formInputText(array( echo Bootstrap::formInputText(array(
'name'=>'parent', 'name'=>'parentTMP',
'label'=>'Parent', 'label'=>'Parent',
'placeholder'=>'Start writing the title of the page parent' 'placeholder'=>'Start writing the title of the page parent'
)); ));
echo Bootstrap::formInputHidden(array(
'name'=>'parent',
'value'=>''
));
// Position // Position
echo Bootstrap::formInputText(array( echo Bootstrap::formInputText(array(
'name'=>'position', 'name'=>'position',
@ -175,9 +195,18 @@
</div> </div>
<script> <script>
var quill;
function insertMedia(filename) {
var Delta = Quill.import('delta');
quill.updateContents(new Delta()
.retain(quill.getSelection().index)
.insert('<img alt="'+filename+'" src="'+DOMAIN_UPLOADS+filename+'" />')
);
}
$(document).ready(function() { $(document).ready(function() {
var quill = new Quill('#editor', { quill = new Quill('#editor', {
modules: { modules: {
toolbar: [ toolbar: [
[{ header: [1, 2, false] }], [{ header: [1, 2, false] }],
@ -189,6 +218,9 @@ $(document).ready(function() {
theme: 'snow' // or 'bubble' theme: 'snow' // or 'bubble'
}); });
// Change button images event handler to open the Media Manager
quill.getModule('toolbar').addHandler('image', openMediaManager);
// Template autocomplete // Template autocomplete
$('input[name="template"]').autoComplete({ $('input[name="template"]').autoComplete({
minChars: 2, minChars: 2,
@ -203,15 +235,27 @@ $(document).ready(function() {
}); });
// Parent autocomplete // Parent autocomplete
var xhr; var parentsXHR;
$("#jsparent").autoComplete({ var parentsList; // Keep the parent list returned to get the key by the title page
$("#jsparentTMP").autoComplete({
source: function(term, response) { source: function(term, response) {
try { xhr.abort(); } catch(e){} // Prevent call inmediatly another ajax request
xhr = $.getJSON('http://localhost:8000/parents.json', { q: term }, function(data){ response(data); }); try { parentsXHR.abort(); } catch(e){}
parentsXHR = $.getJSON("<?php echo HTML_PATH_ADMIN_ROOT ?>ajax/get-parents", {query: term},
function(data) {
parentsList = data;
term = term.toLowerCase();
var matches = [];
for (var title in data) {
if (~title.toLowerCase().indexOf(term))
matches.push(title);
}
response(matches);
});
}, },
onSelect: function(e, term, item) { onSelect: function(e, term, item) {
console.log(term); var parentKey = parentsList[term];
console.log(item); $("#jsparent").attr("value", parentKey);
} }
}); });

View File

@ -146,4 +146,9 @@ class Bootstrap {
return $html; return $html;
} }
public static function formInputHidden($args)
{
return '<input type="hidden" id="js'.$args['name'].'" name="'.$args['name'].'" value="'.$args['value'].'">';
}
} }

View File

@ -2,10 +2,12 @@
header('Content-Type: application/json'); header('Content-Type: application/json');
// $_POST // $_POST
// (string) $filename: Name of file to delete, just the filename // ----------------------------------------------------------------------------
// (string) $_POST['path'] Name of file to delete, just the filename
$filename = isset($_POST['filename']) ? $_POST['filename'] : false;
// ----------------------------------------------------------------------------
$filename = isset($_POST['filename']) ? $_POST['filename'] : ''; if ($filename==false) {
if (Text::isEmpty($filename)) {
exit (json_encode(array( exit (json_encode(array(
'status'=>1, 'status'=>1,
'message'=>'The filename is empty.' 'message'=>'The filename is empty.'
@ -13,18 +15,12 @@ if (Text::isEmpty($filename)) {
} }
// Check if the filename exist // Check if the filename exist
if (!Sanitize::pathFile(PATH_UPLOADS.$filename)) { if (Sanitize::pathFile(PATH_UPLOADS.$filename)) {
exit (json_encode(array(
'status'=>1,
'message'=>'The file does not exist.'
)));
}
// Delete the file
Filesystem::rmfile(PATH_UPLOADS.$filename); Filesystem::rmfile(PATH_UPLOADS.$filename);
}
// Check if the file has a thumbnail // Check if the file has a thumbnail
if (Sanitize::pathFile(PATH_UPLOADS_THUMBNAILS.$filename)) { if (Sanitize::pathFile(PATH_UPLOADS_THUMBNAILS.$filename)) {
// Delete the file
Filesystem::rmfile(PATH_UPLOADS_THUMBNAILS.$filename); Filesystem::rmfile(PATH_UPLOADS_THUMBNAILS.$filename);
} }

View File

@ -0,0 +1,27 @@
<?php defined('BLUDIT') or die('Bludit CMS.');
header('Content-Type: application/json');
// $_GET
// ----------------------------------------------------------------------------
// (string) $_GET['query']
$query = isset($_GET['query']) ? Text::lowercase($_GET['query']) : false;
// ----------------------------------------------------------------------------
if ($query===false) {
exit (json_encode(array(
'status'=>1,
'files'=>'Invalid query.'
)));
}
$tmp = array();
$parents = buildParentPages();
foreach ($parents as $parent) {
$lowerTitle = Text::lowercase($parent->title());
if (Text::stringContains($lowerTitle, $query)) {
$tmp[$parent->title()] = $parent->key();
}
}
exit (json_encode($tmp));
?>

View File

@ -1,16 +1,23 @@
<?php defined('BLUDIT') or die('Bludit CMS.'); <?php defined('BLUDIT') or die('Bludit CMS.');
header('Content-Type: application/json'); header('Content-Type: application/json');
// $_GET // $_POST
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// (integer) $_GET['pageNumber'] // (integer) $_POST['pageNumber'] > 0
$pageNumber = isset($_GET['pageNumber']) ? (int)$_GET['pageNumber'] : '1'; $pageNumber = !empty($_POST['pageNumber']) ? (int)$_POST['pageNumber'] : 1;
$pageNumber = $pageNumber - 1; $pageNumber = $pageNumber - 1;
// (string) $_GET['path'] // (string) $_POST['path']
$path = isset($_GET['path']) ? $_GET['path'] : PATH_UPLOADS_THUMBNAILS; $path = isset($_POST['path']) ? $_POST['path'] : false;
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
if ($path==false) {
exit (json_encode(array(
'status'=>1,
'files'=>'Invalid path.'
)));
}
// Get all files from the directory $path, also split the array by numberOfItems // Get all files from the directory $path, also split the array by numberOfItems
$listOfFilesByPage = Filesystem::listFiles($path, '*', '*', $GLOBALS['BLUDIT_MEDIA_MANAGER_SORT_BY_DATE'], $GLOBALS['BLUDIT_MEDIA_MANAGER_AMOUNT_OF_FILES']); $listOfFilesByPage = Filesystem::listFiles($path, '*', '*', $GLOBALS['BLUDIT_MEDIA_MANAGER_SORT_BY_DATE'], $GLOBALS['BLUDIT_MEDIA_MANAGER_AMOUNT_OF_FILES']);

View File

@ -2,36 +2,38 @@
header('Content-Type: application/json'); header('Content-Type: application/json');
foreach ($_FILES['bluditInputFiles']['name'] as $key=>$filename) { foreach ($_FILES['bluditInputFiles']['name'] as $key=>$filename) {
// Get the next filename if already exist the file to not overwrite the original file
$nextFilename = Filesystem::nextFilename(PATH_UPLOADS, $filename);
// Clean filename and get extension // File extension
$filename = Text::lowercase($filename); $fileExtension = pathinfo($nextFilename, PATHINFO_EXTENSION);
$fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
$filename = pathinfo($filename, PATHINFO_FILENAME);
$filename = Text::replace(' ', '', $filename);
$filename = Text::replace('_', '', $filename);
// Generate the next filename if the filename already exist // Move from temporary directory to uploads folder
$tmpName = $filename.'.'.$fileExtension; rename($_FILES['bluditInputFiles']['tmp_name'][$key], PATH_UPLOADS.$nextFilename);
if (Sanitize::pathFile(PATH_UPLOADS.$tmpName)) {
$number = 0; // Generate Thumbnail
$tmpName = $filename.'_'.$number.'.'.$fileExtension;
while (Sanitize::pathFile(PATH_UPLOADS.$tmpName)) { // Exclude generate thumbnail for SVG format and generate a symlink to the svg
$number++; if ($fileExtension == 'svg') {
$tmpName = $filename.'_'.$number.'.'.$fileExtension; symlink(PATH_UPLOADS.$nextFilename, PATH_UPLOADS_THUMBNAILS.$nextFilename);
} else {
$Image = new Image();
$Image->setImage(PATH_UPLOADS.$nextFilename, $GLOBALS['THUMBNAILS_WIDTH'], $GLOBALS['THUMBNAILS_HEIGHT'], 'crop');
$Image->saveImage(PATH_UPLOADS_THUMBNAILS.$nextFilename, $GLOBALS['THUMBNAILS_QUALITY'], true);
} }
} }
// Move from temporary PHP folder to temporary Bludit folder $absoluteURL = DOMAIN_UPLOADS.$nextFilename;
$originalFile = PATH_TMP.'original'.'.'.$fileExtension; $absoluteURLThumbnail = DOMAIN_UPLOADS_THUMBNAILS.$nextFilename;
move_uploaded_file($_FILES['bluditInputFiles']['tmp_name'][$key], $originalFile); $absolutePath = PATH_UPLOADS.$nextFilename;
rename($originalFile, PATH_UPLOADS.$tmpName);
}
exit (json_encode(array( exit (json_encode(array(
'status'=>0, 'status'=>0,
'message'=>'Image uploaded success.', 'message'=>'Image uploaded success.',
'filename'=>$tmpName 'filename'=>$nextFilename,
'absoluteURL'=>$absoluteURL,
'absoluteURLThumbnail'=>$absoluteURLThumbnail,
'absolutePath'=>$absolutePath
))); )));
?> ?>

View File

@ -109,3 +109,8 @@ define('SESSION_COOKIE_LIFE_TIME', 0);
// New Global Variables // New Global Variables
$GLOBALS['BLUDIT_MEDIA_MANAGER_AMOUNT_OF_FILES'] = 5; $GLOBALS['BLUDIT_MEDIA_MANAGER_AMOUNT_OF_FILES'] = 5;
$GLOBALS['BLUDIT_MEDIA_MANAGER_SORT_BY_DATE'] = true; $GLOBALS['BLUDIT_MEDIA_MANAGER_SORT_BY_DATE'] = true;
// Thubmnails size
$GLOBALS['THUMBNAILS_WIDTH'] = 400;
$GLOBALS['THUMBNAILS_HEIGHT'] = 400;
$GLOBALS['THUMBNAILS_QUALITY'] = 100;

View File

@ -200,4 +200,26 @@ class Filesystem {
$zip->extractTo($destination); $zip->extractTo($destination);
return $zip->close(); return $zip->close();
} }
// Returns the next filename if the filename already exist
public static function nextFilename($path=PATH_UPLOADS, $filename) {
// Clean filename and get extension
$filename = Text::lowercase($filename);
$fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
$filename = pathinfo($filename, PATHINFO_FILENAME);
$filename = Text::replace(' ', '', $filename);
$filename = Text::replace('_', '', $filename);
// Search for the next filename
$tmpName = $filename.'.'.$fileExtension;
if (Sanitize::pathFile($path.$tmpName)) {
$number = 0;
$tmpName = $filename.'_'.$number.'.'.$fileExtension;
while (Sanitize::pathFile($path.$tmpName)) {
$number++;
$tmpName = $filename.'_'.$number.'.'.$fileExtension;
}
}
return $tmpName;
}
} }

View File

@ -101,7 +101,6 @@ class Text {
return( mb_substr($string, $length)===$endsString ); return( mb_substr($string, $length)===$endsString );
} }
public static function endsWithNumeric($string) public static function endsWithNumeric($string)
{ {
return( is_numeric(mb_substr($string, -1, 1)) ); return( is_numeric(mb_substr($string, -1, 1)) );
@ -269,4 +268,5 @@ class Text {
return $truncate; return $truncate;
} }
} }

View File

@ -12,6 +12,8 @@ echo 'var PARENT = "'.PARENT.'";'.PHP_EOL;
echo 'var BLUDIT_VERSION = "'.BLUDIT_VERSION.'";'.PHP_EOL; echo 'var BLUDIT_VERSION = "'.BLUDIT_VERSION.'";'.PHP_EOL;
echo 'var BLUDIT_BUILD = "'.BLUDIT_BUILD.'";'.PHP_EOL; echo 'var BLUDIT_BUILD = "'.BLUDIT_BUILD.'";'.PHP_EOL;
echo 'var DOMAIN_UPLOADS = "'.DOMAIN_UPLOADS.'";'.PHP_EOL;
echo 'var tokenCSRF = "'.$Security->getTokenCSRF().'";'.PHP_EOL; echo 'var tokenCSRF = "'.$Security->getTokenCSRF().'";'.PHP_EOL;
echo '</script>'; echo '</script>';