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).';';
?>
function openMediaManager() {
$('#jsbluditMediaModal').modal('show')
}
function closeMediaManager() {
$('#jsbluditMediaModal').modal('hide')
}
// Remove all files from the table
function cleanFiles() {
$('#jsbluditMediaTable').empty();
@ -77,13 +85,13 @@ function displayFiles(files) {
cleanFiles();
// Regenerate the table
$.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>'+
'<td class="information">'+
'<div>'+filename+'</div>'+
'<div>'+
'<button 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="insertMedia(\''+filename+'\'); closeMediaManager();" type="button" class="btn btn-link p-0 mr-2">Insert</button>'+
'<button onClick="deleteMedia(\''+filename+'\')" type="button" class="btn btn-link p-0 mr-2">Delete</button>'+
'</div>'+
'</td>'+
'</tr>';
@ -93,13 +101,27 @@ function displayFiles(files) {
// Get the list of files via AJAX, filter by the page number
function getFiles(pageNumber) {
$.getJSON("<?php echo HTML_PATH_ADMIN_ROOT ?>ajax/list-files",
{ pageNumber: pageNumber, path: "<?php echo PATH_UPLOADS_THUMBNAILS ?>"},
$.post("<?php echo HTML_PATH_ADMIN_ROOT ?>ajax/list-files",
{ tokenCSRF: tokenCSRF,
pageNumber: pageNumber,
path: "<?php echo PATH_UPLOADS_THUMBNAILS ?>"
},
function(data) {
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() {
// Display the files preloaded for the first time
displayFiles(preLoadFiles);
@ -122,13 +144,16 @@ $(document).ready(function() {
if (xhr.upload) {
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentComplete = e.loaded / e.total;
var percentComplete = (e.loaded / e.total)*100;
$("#jsbluditProgressBar").width(percentComplete+"%");
}
}, false);
}
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>
<body>
<!-- Javascript variables and function -->
<?php include(PATH_JS.'functions.php') ?>
<!-- TOPBAR -->
<?php include('html/topbar.php'); ?>
@ -36,10 +39,10 @@
<!-- TABS -->
<ul class="nav nav-tabs" id="dynamicTab" role="tablist">
<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 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 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>
@ -48,7 +51,7 @@
<form class="tab-content mt-3" id="dynamicTabContent">
<!-- 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
// Title
@ -71,7 +74,13 @@
</div>
<!-- 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
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;">
<?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>
<!-- TABS OPTIONS -->
@ -140,11 +155,16 @@
// Parent
echo Bootstrap::formInputText(array(
'name'=>'parent',
'name'=>'parentTMP',
'label'=>'Parent',
'placeholder'=>'Start writing the title of the page parent'
));
echo Bootstrap::formInputHidden(array(
'name'=>'parent',
'value'=>''
));
// Position
echo Bootstrap::formInputText(array(
'name'=>'position',
@ -175,20 +195,32 @@
</div>
<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() {
var quill = new Quill('#editor', {
quill = new Quill('#editor', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
},
placeholder: 'Content, support Markdown and HTML.',
theme: 'snow' // or 'bubble'
});
// Change button images event handler to open the Media Manager
quill.getModule('toolbar').addHandler('image', openMediaManager);
// Template autocomplete
$('input[name="template"]').autoComplete({
minChars: 2,
@ -203,15 +235,27 @@ $(document).ready(function() {
});
// Parent autocomplete
var xhr;
$("#jsparent").autoComplete({
source: function(term, response){
try { xhr.abort(); } catch(e){}
xhr = $.getJSON('http://localhost:8000/parents.json', { q: term }, function(data){ response(data); });
var parentsXHR;
var parentsList; // Keep the parent list returned to get the key by the title page
$("#jsparentTMP").autoComplete({
source: function(term, response) {
// Prevent call inmediatly another ajax request
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){
console.log(term);
console.log(item);
onSelect: function(e, term, item) {
var parentKey = parentsList[term];
$("#jsparent").attr("value", parentKey);
}
});

View File

@ -146,4 +146,9 @@ class Bootstrap {
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');
// $_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 (Text::isEmpty($filename)) {
if ($filename==false) {
exit (json_encode(array(
'status'=>1,
'message'=>'The filename is empty.'
@ -13,18 +15,12 @@ if (Text::isEmpty($filename)) {
}
// Check if the filename exist
if (!Sanitize::pathFile(PATH_UPLOADS.$filename)) {
exit (json_encode(array(
'status'=>1,
'message'=>'The file does not exist.'
)));
if (Sanitize::pathFile(PATH_UPLOADS.$filename)) {
Filesystem::rmfile(PATH_UPLOADS.$filename);
}
// Delete the file
Filesystem::rmfile(PATH_UPLOADS.$filename);
// Check if the file has a thumbnail
if (Sanitize::pathFile(PATH_UPLOADS_THUMBNAILS.$filename)) {
// Delete the file
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.');
header('Content-Type: application/json');
// $_GET
// $_POST
// ----------------------------------------------------------------------------
// (integer) $_GET['pageNumber']
$pageNumber = isset($_GET['pageNumber']) ? (int)$_GET['pageNumber'] : '1';
// (integer) $_POST['pageNumber'] > 0
$pageNumber = !empty($_POST['pageNumber']) ? (int)$_POST['pageNumber'] : 1;
$pageNumber = $pageNumber - 1;
// (string) $_GET['path']
$path = isset($_GET['path']) ? $_GET['path'] : PATH_UPLOADS_THUMBNAILS;
// (string) $_POST['path']
$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
$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');
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
$filename = Text::lowercase($filename);
$fileExtension = pathinfo($filename, PATHINFO_EXTENSION);
$filename = pathinfo($filename, PATHINFO_FILENAME);
$filename = Text::replace(' ', '', $filename);
$filename = Text::replace('_', '', $filename);
// File extension
$fileExtension = pathinfo($nextFilename, PATHINFO_EXTENSION);
// Generate the next filename if the filename already exist
$tmpName = $filename.'.'.$fileExtension;
if (Sanitize::pathFile(PATH_UPLOADS.$tmpName)) {
$number = 0;
$tmpName = $filename.'_'.$number.'.'.$fileExtension;
while (Sanitize::pathFile(PATH_UPLOADS.$tmpName)) {
$number++;
$tmpName = $filename.'_'.$number.'.'.$fileExtension;
}
// Move from temporary directory to uploads folder
rename($_FILES['bluditInputFiles']['tmp_name'][$key], PATH_UPLOADS.$nextFilename);
// Generate Thumbnail
// Exclude generate thumbnail for SVG format and generate a symlink to the svg
if ($fileExtension == 'svg') {
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
$originalFile = PATH_TMP.'original'.'.'.$fileExtension;
move_uploaded_file($_FILES['bluditInputFiles']['tmp_name'][$key], $originalFile);
rename($originalFile, PATH_UPLOADS.$tmpName);
}
$absoluteURL = DOMAIN_UPLOADS.$nextFilename;
$absoluteURLThumbnail = DOMAIN_UPLOADS_THUMBNAILS.$nextFilename;
$absolutePath = PATH_UPLOADS.$nextFilename;
exit (json_encode(array(
'status'=>0,
'message'=>'Image uploaded success.',
'filename'=>$tmpName
'filename'=>$nextFilename,
'absoluteURL'=>$absoluteURL,
'absoluteURLThumbnail'=>$absoluteURLThumbnail,
'absolutePath'=>$absolutePath
)));
?>

View File

@ -108,4 +108,9 @@ define('SESSION_COOKIE_LIFE_TIME', 0);
// New Global Variables
$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);
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 );
}
public static function endsWithNumeric($string)
{
return( is_numeric(mb_substr($string, -1, 1)) );
@ -269,4 +268,5 @@ class Text {
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_BUILD = "'.BLUDIT_BUILD.'";'.PHP_EOL;
echo 'var DOMAIN_UPLOADS = "'.DOMAIN_UPLOADS.'";'.PHP_EOL;
echo 'var tokenCSRF = "'.$Security->getTokenCSRF().'";'.PHP_EOL;
echo '</script>';