CKEditor - Delete option in imgbrowse

Place for comments, problems, questions, or any issue related to the JavaScript / PHP scripts from this site.
byronclunz
Posts: 6

CKEditor - Delete option in imgbrowse

I've managed to get imgbrowse and imgupload working with ckeditor 4.5.4! I have assigned each user their own directory.
It would be nice if there were a way for the user to DELETE files they have uploaded.
I realize that probably requires a significant amount of new javascript so I will certainly use this plugin as it is. But if you are able to add the delete functionality, I'd be thrilled.

Admin Posts: 805
Hello
If you want to have Delete option in the imgbrowse CKEditor plugin:
1. Replace the code of the "imgbrowse.php" file (in "ckeditor/plugins/imgbrowse/" folder), with this code:

Code: Select all

<?php
session_start();
// class to browse images in a folder (for CKEditor plugin)
// from: https://coursesweb.net/javascript/
class imgbrowse {
  // IN $root - REPLACE "/ckeup" WITH THE PATH TO THE FOLDER WITH IMAGES RELATIVE TO ROOT OF YOUR WEBSITE ON SERVER
  protected $root = '/ckeup';
  protected $del = 1;  //SET 0 TO NOT INCLUDE DELETE OPTION
  protected $imgext = ['bmp', 'gif', 'jpg', 'jpe', 'jpeg', 'png'];  // allowed image extensions
  protected $imgdr = '';     // current folder (in $root) with images

  function __construct() {
    if(isset($_SESSION['user'])) $this->root = trim($this->root, '/') .'/'. $_SESSION['user'] .'/';
    else $this->root = trim($this->root, '/') .'/';
    $this->imgdr = isset($_POST['imgdr']) ? trim(trim(strip_tags($_POST['imgdr'])), '/') .'/' : '';
  }

  // return two-dimensional array with folders-list and images in specified $imgdr
  public function getMenuImgs() {
    $re = ['menu'=>'', 'imgs'=>''];
    try{
      $obdr = new DirectoryIterator($_SERVER['DOCUMENT_ROOT'] .'/'. $this->root . $this->imgdr);  // object of the dir
    }
    catch(Exception $e) {
      return '<h2>ERROR from PHP:</h2><h3>'. $e->getMessage() .'</h3><h4>Check the $root value in imgbrowse.php to see if it is the correct path to the image folder; RELATIVE TO ROOT OF YOUR WEBSITE ON SERVER</h4>';
    }

    // get protocol and host name to add absolute path in <img src>
    $protocol = !empty($_SERVER['HTTPS']) ? 'https://' : 'http://';
    $site = $protocol. $_SERVER['SERVER_NAME'] .'/';

    // traverse the $obdr
    foreach($obdr as $fileobj) {
      $name = $fileobj->getFilename();
      $del = $this->del ==1 ? '<span class="imgdel" data-img="'. $this->imgdr . $name .'">Delete</span>' :'';

      // if image file, else, directory (but not . or ..), add data in $re
      if($fileobj->isFile() && in_array($fileobj->getExtension(), $this->imgext)) $re['imgs'] .= '<span><img src="'. $site . $this->root . $this->imgdr . $name .'" alt="'. $name .'" height="50" />'. $name .$del .'</span>';
      else if($fileobj->isDir() && !$fileobj->isDot()) $re['menu'] .= '<li><span title="'. $this->imgdr . $name .'">'. $name .'</span></li>';
    }
    if($re['menu'] != '') $re['menu'] = '<ul>'. $re['menu'] .'</ul>';
    if($re['imgs'] == '') $re['imgs'] = '<h1>No Images</h1>';
    return $re;
  }

  //delete $f file
  public function delFile($f){
   if($this->del ==1) return unlink($_SERVER['DOCUMENT_ROOT'] .'/'.$this->root .$f) ?'ok' :'er';
  }
}

// uses the imgbrowse class, iif 'imgdel' call delFile() to delete file, else get menu-images
$obj = new imgbrowse;
$resp = isset($_POST['imgdel']) ? $obj->delFile(trim(strip_tags($_POST['imgdel']))) : json_encode($obj->getMenuImgs());
echo $resp;
  
2. Replace the code in the "imgbrowse.html" file with this code:

Code: Select all

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>CKeditor Image Browser</title>
<meta name="description" content="CKeditor Image Browser, from https://coursesweb.net/ , Free" />
<meta name="keywords" content="ckeditor, image browse" />
<meta name="robots" content="ALL" />
<meta name="author" content="MarPlo" />
<style>
<!--
@charset "utf-8";
body, html {background-color:#f0f1fe;margin:1px 1%;padding:0;text-align:center;font-size:1em;font-family:"Calibri",sans-serif;}
footer,section,nav{display:block}
#menu {
 position:absolute;
 top:5px;
 left:1px;
 width:10em;
 background:#fefefe;
 border:2px solid #bbb;
 padding:.2em;
 text-align:left;
-moz-border-radius:.8em;
-webkit-border-radius:.8em;
-khtml-border-radius:.8em;
 border-radius:.8em;
}
#menu ul {
 margin:1px 0 1px .1em;
 padding:0 0 0 .5em;
}
#menu li {
 margin:1px 0;
 background:#eee;
 padding:1px 2px;
 color:#0001da;
}
#menu li span {
 display:block;
 margin:0;
 text-decoration:underline;
 cursor:pointer;
}
#menu #c_li #c_span {
 background:#0001be;
 font-weight:700;
 text-decoration:none;
 color:#fff;
}
#menu li span:hover {
 background:#fbfb01;
 text-decoration:none;
}
#imgs {
 position:relative;
 height:100%;
 margin:0 0 1em calc(10.1em + .2%);
 background:#f7f8f9;
 padding:.2em .3em;
 text-align:left;
 overflow:auto;
}
#imgs h1 {
  margin:25% auto 1em auto;
  text-align:center;
  text-decoration:underline;
}
#imgs span {
 max-height:5em;
 margin:.2em .3%;
 display:inline-block;
 border:1px solid #bbb;
 background:#fefeff;
 padding:2px;
 text-align:center;
 font-weight:600;
 font-style:oblique;
}
#imgs span:hover {
 background:#ebfbeb;
}
#imgs span:hover img {
 background:#fefebe;
}
#imgs span.imgdel {
 display:block;
 width:30px;
 background:#fbfb00;
 border-radius:5px;
 font-size:11px;
 padding:0;
 cursor:pointer;
}
#imgs span.imgdel:hover {
 background:#feb8b8;
}
#imgs img {
 display:block;
 margin:0 auto 2px auto;
 border:none;
 padding:2px;
 cursor:pointer;
}
#footer {
 position:absolute;
 bottom:0;
 left:0;
 right:0;
 margin:1px auto;
 font-size:8px;
}
//-->
</style>
</head>
<body>
<section id="imgs"></section>
<nav id="menu"><ul><li id="c_li"><span id="c_span" title="">Root</span></li></ul></nav>
<footer id="footer">
 From: <a href="https://coursesweb.net/" title="CoursesWeb">https://coursesweb.net/javascript/javascript-scripts_s2</a>
</footer>
<script>
// <![CDATA[
var current_li = 'c_li';    // id of current accessed li-menu
var current_span = 'c_span';    // id of current accessed span in li-menu
var title_dir = document.getElementById(current_li).querySelector('span').title;    // title with dir-path of current span-li
var li_name = document.getElementById(current_li).querySelector('span').innerHTML;     // name of current accessed menu-list
var imgs = document.getElementById('imgs');    // element with images

// To get value of imgroot and CKEditorFuncNum from URL
var url = location.href;    // current page address
var imgroot = url.match(/imgroot=([^&]*)/) ? url.match(/imgroot=([^&]*)/)[1] : null;
var CKEditorFuncNum = url.match(/CKEditorFuncNum=([0-9]+)/) ? url.match(/CKEditorFuncNum=([0-9]+)/)[1] : null;

// Ajax, receives the url of file to access, data to send, and a callback function (called when the response is received)
function ajaxSend(datasend, callback) {
  if(!datasend.match(/^imgdel=/i)) imgs.innerHTML = '<h1>Loading ...: '+ li_name +'</h1>';  // message till ajax-response

  var request =  (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); // sets the XMLHttpRequest instance
  datasend += '&isajax=1';    // to know in php it is ajax request
  if(imgroot != null) datasend += '&imgroot='+ imgroot;

  request.open("POST", 'imgbrowse.php'); // define the request

  // adds  a header to tell the PHP script to recognize the data as is sent via POST, and send data
  request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  request.send(datasend);

  // Check request status,  when the response is completely received pass it to callback function
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      callback(request.responseText);
    }
  }
}

// callback from Ajax
function ajaxCallback(resp) {
  var content = JSON.parse(resp);

  if(resp.match(/ERROR from PHP:/)) imgs.innerHTML = '<h2>'+ content +'</h2>';
  else {
    // add new menu in current clicked list
    if(document.getElementById(current_li)) document.getElementById(current_li).innerHTML = '<span title="'+ title_dir +'" id="'+ current_span +'">'+ li_name +'</span>'+ content.menu;
    imgs.innerHTML = content.imgs;
    regEv();
  }
}

//for click event to .imgdel to delete file; $elm = delete-button
function imgDel(elm){
  if(window.confirm('The file will be deleted without posibility to recover')) ajaxSend('imgdel='+ elm.getAttribute('data-img').replace(/\?/g, '%3F').replace(/=/g, '%3D').replace(/&/g, '%26').replace(/[ ]+/g, '%20'), function(resp){
    if(resp =='ok'){
      elm.parentElement.style.display ='none';
      alert('The file successfully deleted.');
    }
    else if(resp =='er') alert('Unable to delete tje file');
  });
}

// to register events
function regEv() {
  if(document.getElementById('menu')) {
    // get menu LIs
    var lists = document.getElementById('menu').querySelectorAll('li span');
    var nr_lists = lists.length;

    // register click to eack span-li
    if(nr_lists > 0) {
      for(var i=0; i<nr_lists; i++) {
        lists[i].addEventListener('click', function(e){
          if(e.target.id == current_span) return false;
          else {
            // removes and sets id for current element
            if(document.getElementById(current_li)) document.getElementById(current_li).removeAttribute('id');
            if(document.getElementById(current_span)) document.getElementById(current_span).removeAttribute('id');
            e.target.parentNode.setAttribute('id', current_li);
            li_name = e.target.childNodes[0].nodeValue;
            title_dir = e.target.title;

            ajaxSend('imgdr='+ title_dir, ajaxCallback); // get data from php
          }
        }, false);
      }
    }

    // get images and register click to eack img, to acces window.parent.CKEDITOR.tools.callFunction()
    var img_all = imgs.querySelectorAll('img');

    // register click to eack span-li
    for(var i=0; i<img_all.length; i++) {
      img_all[i].addEventListener('click', function(e){
        if(CKEditorFuncNum !== null) window.opener.CKEDITOR.tools.callFunction(CKEditorFuncNum, e.target.src);
        window.close();
      });
    }

    // get .imgdel buttons and register click to call imgDel()
    var imgdels = document.querySelectorAll('span .imgdel');

    // register click to eack span-li
    for(var i=0; i<imgdels.length; i++) {
      imgdels[i].addEventListener('click', function(e){
        imgDel(e.target);
      });
    }
  }
}

ajaxSend('', ajaxCallback);  // get data from php
// ]]>
</script>
</body>
</html>
- Or Download and use the files from this attachment:
Attachments
imgbrowse.zip
imgbrowse plugin with Delete feature
(5.86 KiB) Downloaded 457 times

chill Posts: 7
When I set this up as directed it did not work, but when I added

Code: Select all

'. $del .'
at the end of this line it worked. Hopefully, this will help others with the same problem.

Code: Select all

if($fileobj->isFile() && in_array($fileobj->getExtension(), $this->imgext)) $re['imgs'] .= '<span><img src="'. $site . $this->root . $this->imgdr . $name .'" alt="'. $name .'" height="50" />'. $name .''. $del .'</span>';

Similar Topics