Использование одной формы для управления редактором TinyMCE и загрузки файлов с вводом текста - PullRequest
0 голосов
/ 11 октября 2018

Для проекта, который мне нужно изменить для клиента, у меня есть экземпляр редактора TinyMCE, реализованный внутри формы.Запрос клиента состоит в том, чтобы иметь простую систему для сохранения некоторых данных портфеля, таких как имя его клиента, логотип клиента, а затем краткое описание проектов клиентов.Я не писал оригинальный код, и я обнаружил что-то вроде катастрофы.Я никогда раньше не пользовался редактором tinyMCE, я начал читать документацию, и он, похоже, хорошо настроен человеком, который изначально написал код.Проблема в том, что я хочу использовать только одну форму для управления всеми запрошенными полями, но теперь есть разные формы.Я попытался поместить все поля в одну форму, но он перестал работать, а данные и логотип не были сохранены в базе данных / загружены.Вот код, как мне этого добиться?

HTML код:

<div class="container" id="editor">
  <div class="row">
    <div id="step-1" class="col-sm-12 col-md-12 col-lg-12">
      <form method="POST" action="" enctype="multipart/form-data" id="imageForm">
        <div class="form-row">
          <div class="col-sm-12 col-md-3 col-lg-3">
            <input type="text" class="form-control" name="client_name" id="clientName" placeholder="Client name">
          </div>

          <div class="col-sm-12 col-md-3 col-lg-3">
            <div class="custom-file">
              <input type="file" name="client_logo" class="custom-file-input" id="clientLogo">
              <label class="custom-file-label" for="clientLogo">Client logo</label>
            </div>
          </div>

          <div class="col-sm-12 col-md-6 col-lg-6" id="imagePreview">
            <img class="card-img-top" id="prvImage" src="" alt="Preview logo">
          </div>
        </div>
            <button type="submit" class="btn btn-primary btn-submit">Carica</button>
      </form>
    </div>

    <div id="step-2" class="col-sm-12 col-md-12 col-lg-12">
      <form method="POST" action="" id="editorForm">
        <textarea class="form-control" name="post_content" id="postContent"></textarea>
      </form>
    </div>
  </div>
</div>

JS код:

$(document).ready(function(){

editor();
imageLogoHandler();
imgPreviewHandler();

});

var imageLogoHandler = function(){
    $('.btn-submit').on('click' , function(e){
      e.preventDefault();
      alert('Upload in progress');
          var data = new FormData();
          data.append('client_logo', $('#clientLogo').get(0).files[0]);
          data.append('client_name', $('#clientName[name="client_name"]').val());
          data.append('action', 'upimg');

          $.ajax({
            type: 'POST',
             url: 'PostHandler.php',
             data: data,
             processData: false,
             contentType: false,
             cache: false,
             success: function(res){

             }
          });
    });
}

var imgPreviewHandler = function(){
  document.getElementById('clientLogo').onchange = function (evt) {
    var tgt = evt.target || window.event.srcElement,
        files = tgt.files;
    if (FileReader && files && files.length) {
        var fr = new FileReader();
        fr.onload = function () {
            document.getElementById('prvImage').src = fr.result;
        }
        fr.readAsDataURL(files[0]);
      }
    }
}

var editor = function(){
  tinymce.init({
    selector: '#postContent',
    height: 380,
    plugins: 'save print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template table charmap hr pagebreak nonbreaking anchor toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern help',
    toolbar: 'save | formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat | image',
    relative_urls : false,
    remove_script_host : false,
    convert_urls: true,
    images_upload_url: 'ImageHandler.php',
    automatic_uploads: false,
    save_onsavecallback: function(){
          var action = 'savePost';
          var data = tinymce.get('postContent').getContent();
          $.ajax({
            type: 'POST',
            url: 'PostHandler.php',
            data: {action: action, post_content: data},
            cache: false,
            success: function(response){
              alert(response);
            }
      });
    }
  });
}

PHP

<?php
// PostHandler.php
session_start();

require_once dirname(__DIR__, 1).'/Config.php';

if(isset($_POST['action']) && $_POST['action'] === 'upimg'){

  if(is_uploaded_file($_FILES['client_logo']['tmp_name'])){

    if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $_FILES['client_logo']['name'])) {
        header("HTTP/1.1 400 Invalid file name.");
        return;
    }

    if(!in_array(strtolower(pathinfo($_FILES['client_logo']['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "jpeg" ,"png"))) {
        header("HTTP/1.1 400 Invalid extension.");
        return;
    }

  $clientName = filter_var($_POST['client_name'], FILTER_SANITIZE_STRING);

  $_SESSION['client_name'] = $clientName;

  $imageFolder = '../../img/portfolio/';

  $file = $imageFolder . $_FILES['client_logo']['name'];

  move_uploaded_file($_FILES['client_logo']['tmp_name'], $file);

  $stmt = $db->prepare('INSERT INTO portfolio (client_name, client_logo) VALUES (?, ?)');
    if($stmt->execute(array($clientName, $file))){
      echo '';
    } else {
      echo '';
    }
  }

}
elseif(isset($_POST['action']) && $_POST['action'] === 'savePost'){

  $postContent = $_POST['post_content'];

  $stmt = $db->prepare('UPDATE portfolio SET post_content = ? WHERE client_name = ?');
    if($stmt->execute(array($postContent, $_SESSION['client_name']))){
      echo '';
    } else {
      echo '';
    }

}

?>

<?php
  //ImageHandelr.php
  /*******************************************************
   * Only these origins will be allowed to upload images *
   ******************************************************/
  $accepted_origins = array("http://localhost:8000/u/", "http://192.168.1.1", "http://example.com");

  /*********************************************
   * Change this line to set the upload folder *
   *********************************************/
  $imageFolder = "../../img/portfolio/";

  reset ($_FILES);
  $temp = current($_FILES);
  if (is_uploaded_file($temp['tmp_name'])){

    // if (isset($_SERVER['HTTP_ORIGIN'])) {
    //   // same-origin requests won't set an origin. If the origin is set, it must be valid.
    //   if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
    //     header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
    //   } else {
    //     header("HTTP/1.1 403 Origin Denied");
    //     return;
    //   }
    // }

    /*
      If your script needs to receive cookies, set images_upload_credentials : true in
      the configuration and enable the following two headers.
    */
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // Sanitize input
    if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
        header("HTTP/1.1 400 Invalid file name.");
        return;
    }

    // Verify extension
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
        header("HTTP/1.1 400 Invalid extension.");
        return;
    }

    // if(!file_exists($_POST['client_name'])){
    //   $clientFolder = mkdir($imageFolder.$_POST['client_name'], 0777);
    // }

    // Accept upload if there was no origin, or if it is an accepted origin
    //$filetowrite = $imageFolder . $temp['name'];
    $filetowrite = $imageFolder . $temp['name'];

    move_uploaded_file($temp['tmp_name'], $filetowrite);

    // Respond to the successful upload with JSON.
    // Use a location key to specify the path to the saved image resource.
    // { location : '/your/uploaded/image/file'}


    echo json_encode(array('location' => $filetowrite));

  } else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
  }

?>

Еще один вопрос касается визуализации содержимого переднего плана.Я знаю, что tinyMCE является редактором WordPress по умолчанию, и для внешнего интерфейса я хочу отобразить предварительный просмотр содержимого, а не всего, как я могу это сделать?

...