Ajouter du code à l'éditeur Tiny MCE - Prestashop 1.7
Pour la réalisation de ce blog j'ai besoin de partager du code, et cette fonctionnalité existe via le plugin "codesample" de TinyMce.
Nous allons devoir changer le TinyMCE de Prestashop et par la même occasion récupérer la dernière version TinyMCE 5.
On recupere TinyMCE Community:
https://www.tiny.cloud/get-tiny/
On renomme le dossier /js/tiny_mce en /js/tiny_mce-bck
On upload la nouvelle version de TinyMCE
On télécharge le plugin Code Sample
https://www.tiny.cloud/docs/plugins/opensource/codesample/
et on le met dans le repertoire /js/tiny_mce/plugins
On va lier le nouvelle éditeur à Prestashop
On renomme /js/admin/tinymce.inc.js en tinymce.inc.js-bck
On le remplace par ce nouveau fichier /js/admin/tinymce.inc.js
function tinySetup(config) {
if (typeof tinyMCE === 'undefined') {
setTimeout(function() {
tinySetup(config);
}, 100);
return;
}
if (!config) {
config = {};
}
if (typeof config.editor_selector != 'undefined') {
config.selector = '.' config.editor_selector;
}
var default_config = {
selector: '.rte',
plugins: 'codesample emoticons link image table media placeholder lists advlist code table autoresize codesample fullscreen',
browser_spellcheck: true,
toolbar1:
'fullscreen undo emoticons code codesample link image bold italic underline strikethrough blockquote bullist numlist table media formatselect',
toolbar2: '',
language: iso_user,
content_style: lang_is_rtl === '1' ? 'body {direction:rtl;}' : '',
skin: 'tinymce-5-dark',
mobile: {
theme: 'mobile',
plugins: ['lists', 'align', 'link', 'table', 'placeholder', 'advlist', 'code'],
toolbar:
'undo code colorpicker bold italic underline strikethrough blockquote link align bullist numlist table formatselect styleselect',
},
images_upload_url: '/js/admin/postAcceptor.php',
automatic_uploads: true,
menubar: false,
statusbar: false,
relative_urls: false,
convert_urls: false,
entity_encoding: 'raw',
extended_valid_elements: 'em[class|name|id],@[role|data-*|aria-*]',
valid_children: ' *[*]',
valid_elements: '*[*]',
init_instance_callback: 'changeToMaterial',
rel_list: [{title: 'nofollow', value: 'nofollow'}]
};
if (typeof window.defaultTinyMceConfig !== 'undefined') {
Object.assign(default_config, window.defaultTinyMceConfig);
}
$.each(default_config, function(index, el) {
if (config[index] === undefined) config[index] = el;
});
var plugins_arr = config['plugins'].split(/[ ,]/);
var plugins = plugins_arr.join(',');
config.plugins = plugins;
// Change icons in popups
$('body').on('click', '.mce-btn, .mce-open, .mce-menu-item', function() {
changeToMaterial();
});
tinyMCE.init(config);
}
Ici on a ajouté des plugins comme codesample, on a changé de skin et on a ajouté une gestion d'upload d'image.
On ajoute un repertoire img pour reception des images uploadés via tinymce
On ajoute le fichier postAcceptor.php pour envoyer des images
<?php
/***************************************************
* Only these origins are allowed to upload images *
***************************************************/
$accepted_origins = array("https://www.presta.cafe");
/*********************************************
* Change this line to set the upload folder *
*********************************************/
$imageFolder = "img/";
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;
}
}
// Don't attempt to process the upload on an OPTIONS request
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Methods: POST, OPTIONS");
return;
}
reset ($_FILES);
$temp = current($_FILES);
if (is_uploaded_file($temp['tmp_name'])){
/*
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;
}
// Accept upload if there was no origin, or if it is an accepted origin
$filetowrite = $imageFolder . $temp['name'];
move_uploaded_file($temp['tmp_name'], $filetowrite);
// Determine the base URL
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https://" : "http://";
$baseurl = $protocol . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER['REQUEST_URI']), "/") . "/";
// 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' => $baseurl . $filetowrite));
} else {
// Notify editor that the upload failed
header("HTTP/1.1 500 Server Error");
}
?>
Désormais nous avons un nouvel éditeur WYSIWG TinyMCE E sur lequel on peux insérer du code:
Afin de fonctionner correctement le plugin codesample à besoin de la librairie Prism.js
https://prismjs.com/download.html#themes=prism-tomorrow&languages=markup css clike javascript
On ajoute les languages et options que l'on veut et on upload sur le serveur
Afin que l'on puisse styliser le code en front on appellera PrismJS dans le hook header du module de blog
$this->context->controller->addCSS(_PS_CORE_DIR_ . '/js/tiny_mce/prism/prism.css');
$this->context->controller->addJS(_PS_CORE_DIR_ . '/js/tiny_mce/prism/prism.js');
Leave a comment