praiadeseselle/wire/modules/Inputfield/InputfieldCKEditor/InputfieldCKEditor.module

1106 lines
41 KiB
Text
Raw Permalink Normal View History

2022-03-08 15:55:41 +01:00
<?php namespace ProcessWire;
/**
* ProcessWire Inputfield for CKEditor
*
* CKEditor Copyright (C) 2003-2021, CKSource - Frederico Knabben
* http://ckeditor.com
*
* ProcessWire 3.x, Copyright 2021 by Ryan Cramer
* https://processwire.com
*
* FIELD CONFIGURATION
* ===================
* @property bool|int $inlineMode (default=0)
* @property bool|int $usePurifier (default=0)
* @property bool|int $useACF (default=1)
* @property array $toggles
* @property string $toolbar
* @property string $contentsCss
* @property string $contentsInlineCss
* @property string $stylesSet
* @property string|array $extraPlugins
* @property string $removePlugins
* @property string $extraAllowedContent
* @property string $formatTags
* @property string $customOptions
* @property array $imageFields
* @property int $assetPageID
* @property string $configName
*
* MODULE CONFIGURATION
* ====================
* @property array $extraPluginsDirs Extra plugins directories, see addExtraPluginsDir() method. 3.0.179+
*
*
*/
class InputfieldCKEditor extends InputfieldTextarea implements ConfigModule {
public static function getModuleInfo() {
return array(
'title' => 'CKEditor',
'version' => 168,
'summary' => __('CKEditor textarea rich text editor.', __FILE__),
'installs' => array('MarkupHTMLPurifier'),
);
}
const toggleCleanDIV = 2; // remove <div>s
const toggleCleanP = 4; // remove empty <p> tags
const toggleCleanNBSP = 8; // remove &nbsp; entities
/**
* Placeholder that appears as the value in the hidden input used by inline mode
*
*/
const PLACEHOLDER_TEXT = ':IGNORE:';
/**
* Default value for CK Editor extraPlugins config option
*
*/
const EXTRA_PLUGINS = 'pwimage,pwlink,sourcedialog';
/**
* Default value for CK Editor removePlugins config option
*
*/
const REMOVE_PLUGINS = 'image,magicline';
/**
* Default value for CK Editor extraAllowedContent option
*
*/
const EXTRA_ALLOWED_CONTENT = '';
/**
* All possible options for format_tags
*
*/
const ALL_FORMAT_TAGS = 'p;h1;h2;h3;h4;h5;h6;pre;address;div';
/**
* Default value for CK Editor format_tags option
*
*/
const FORMAT_TAGS = 'p;h1;h2;h3;h4;h5;h6;pre;address';
/**
* Version number for CKEditor directory
*
*/
const CKEDITOR_VERSION = '4.16.0';
/**
* Instance of MarkupHTMLPurifier module
*
*/
static $purifier = null;
/**
* Names of JS config keys to avoid redundancy
*
*/
static $configNames = array();
/**
* Name of current JS config key
*
*/
protected $configName = '';
/**
* Whether or not the globalConfig has run. This ensures it only runs once per request.
*
*/
static protected $isConfigured = false;
/**
* Construct and set default configuration
*
*/
public function __construct() {
parent::__construct();
$this->set('inlineMode', 0);
$this->set('usePurifier', 1);
$this->set('useACF', 1);
$this->set('toggles', array());
$this->set('imageFields', array());
$this->set('assetPageID', 0); // FUTURE USE
$this->set('toolbar', '' .
"Format, Styles, -, Bold, Italic, -, RemoveFormat\n" .
"NumberedList, BulletedList, -, Blockquote\n" .
"PWLink, Unlink, Anchor\n" .
"PWImage, Table, HorizontalRule, SpecialChar\n" .
"PasteText, PasteFromWord\n" .
"Scayt, -, Sourcedialog"
);
$this->set('contentsCss', '');
$this->set('contentsInlineCss', '');
$this->set('stylesSet', '');
$this->set('extraPlugins', explode(',', self::EXTRA_PLUGINS));
$this->set('extraPluginsDirs', array()); // module config only
$this->set('removePlugins', self::REMOVE_PLUGINS);
$this->set('extraAllowedContent', self::EXTRA_ALLOWED_CONTENT);
$this->set('formatTags', self::FORMAT_TAGS);
$this->set('customOptions', ''); // custom user-defined config options
foreach($this->findPlugins() as $name => $file) {
$this->set("plugin_$name", ""); // json string of each plugin config settings
}
}
public function set($key, $value) {
// convert extraPlugins string to array
// used to be stored as a string in older versions
if($key == 'extraPlugins' && is_string($value)) {
$value = str_replace(' ', '', $value);
$value = explode(',', $value);
} else if($key == 'extraAllowedContent') {
$value = str_replace(array("\r\n", "\n"), "; ", trim($value));
} else if($key == 'configName') {
$this->configName = $value;
}
return parent::set($key, $value);
}
/**
* Given a toolbar config string, convert it to an array
*
* Toolbar items split by commas
* Groups of toolbar items split by lines
* Toolbar lines that starts with '#' are ignored
*
* @param string $str
* @return array
*
*/
protected function toolbarStringToArray($str) {
$str = str_replace(' ', '', $str);
$items = array();
$lines = explode("\n", $str);
foreach($lines as $line) {
$line = trim($line);
if(strpos($line, '#') === 0) { // @ocorreiododiogo PR #1040
continue;
} else if(empty($line)) {
$items[] = '/';
} else {
$lineArray = explode(',', $line);
$items[] = $lineArray;
}
}
return $items;
}
/**
* Prep a path starting from root to include any possible subdirs
*
* @param string $path
* @param bool $cacheBust Specify true to append a cache busting query string to the returned URL
* @return string URL from root
*
*/
protected function pathFromRoot($path, $cacheBust = false) {
if(strpos($path, '//') !== false) return $path; // don't modify URLs with scheme
$path = ltrim($path, '/');
if($cacheBust && strpos($path, '?') === false) {
$file = $this->wire('config')->paths->root . $path;
if(file_exists($file)) {
$path .= "?nc=" . filemtime($file);
}
}
$path = $this->wire('config')->urls->root . $path;
return $path;
}
/**
* Get field name to use for images, or blank if disabled (or unavailable)
*
* @param Page $page Asset page
* @return string
*
*/
protected function getImagesFieldName($page) {
$imageFields = $this->imageFields;
if(!is_array($imageFields)) $imageFields = array();
if(in_array('x', $imageFields)) return '';
if(!$page || !$page->id || !$page->template) return '';
$result = '';
foreach($imageFields as $name) {
if($page->template->hasField($name)) {
$result = $name;
break;
}
}
if(!$result && !count($imageFields)) {
// allow any available images field to be used, except those disallowed by ProcessPageEditImageSelect
$skipFields = $this->wire('session')->getFor($this, 'skipImageFields');
if(!is_array($skipFields)) {
$skipFields = array();
$skipData = $this->wire('modules')->getModuleConfigData('ProcessPageEditImageSelect');
if(!empty($skipData['skipFields'])) $skipFields = explode(' ', $skipData['skipFields']);
$this->wire('session')->setFor($this, 'skipImageFields', $skipFields);
}
foreach($page->template->fieldgroup as $field) {
if(!$field->type instanceof FieldtypeImage) continue;
if((int) $field->maxFiles == 1) continue;
if(in_array($field->name, $skipFields)) continue;
$result = $field->name;
break;
}
}
return $result;
}
public function renderReady(Inputfield $parent = null, $renderValueMode = false) {
static $loaded = false;
$class = $this->className();
$config = $this->wire('config');
$baseURL = $config->urls->$class;
$basePath = $baseURL . "ckeditor-" . self::CKEDITOR_VERSION . '/';
if(!$loaded) {
$config->scripts->add($basePath . "ckeditor.js");
$this->wire('modules')->get('JqueryUI')->use('modal');
$loaded = true;
}
$this->globalConfig();
if($this->contentsCss) {
$contentsCss = $this->pathFromRoot($this->contentsCss, true);
} else {
$contentsCss = $baseURL . 'contents.css';
}
// previous versions had a default setting removing the 'link' plugin, but now the Anchor
// tool requires it. this code fixes that situation for existing installations.
if(stripos($this->toolbar, 'Anchor') !== false && stripos($this->removePlugins, 'link') !== false) {
$this->removePlugins = preg_replace('/\blink,?\b/i','', $this->removePlugins);
}
// FUTURE USE
// $assetPage = $this->assetPageID ? $this->wire('pages')->get((int) $this->assetPageID) : $this->hasPage;
// if(!$assetPage || !$assetPage->id) $assetPage = $this->hasPage;
$assetPage = $this->hasPage;
if(!$assetPage) $assetPage = new NullPage();
$extraPlugins = $this->extraPlugins;
$imagesField = $this->getImagesFieldName($assetPage);
if($imagesField) {
$extraPlugins[] = 'uploadimage';
$this->addClass('InputfieldHasUpload', 'wrapClass');
}
$settings = array(
'baseHref' => $config->urls->root,
'contentsCss' => $contentsCss,
'extraAllowedContent' => $this->extraAllowedContent,
'extraPlugins' => implode(',', $extraPlugins),
'removePlugins' => trim(rtrim($this->removePlugins, ', ') . ',exportpdf', ','),
'toolbar' => $this->toolbarStringToArray($this->toolbar),
'format_tags' => rtrim($this->formatTags, '; '),
'language' => $this->_x('en', 'language-pack'), // CKEditor default language pack to use
// 'enterMode' => 'CKEDITOR.ENTER_P', // already the default, can be left out
'entities' => false,
'uploadUrl' => '',
'pwUploadField' => $imagesField,
'pwAssetPageID' => $assetPage->id,
);
if(empty($settings['extraAllowedContent'])) {
unset($settings['extraAllowedContent']);
}
if($assetPage !== $this->hasPage && $assetPage->id) {
// external asset page (FUTURE USE)
$imagesInputfield = $this->wire('modules')->get('InputfieldImage');
$imagesInputfield->set('hasPage', $assetPage);
$imagesInputfield->renderReady($parent, $renderValueMode);
$assetPageEditURL = $assetPage->editUrl() . "&InputfieldFileAjax=noTemp";
} else if($assetPage->id) {
// assetPage is hasPage
$assetPageEditURL = $assetPage->editUrl() . '&InputfieldFileAjax=1';
} else {
$assetPageEditURL = '';
}
if($imagesField && $assetPageEditURL) {
$settings['uploadUrl'] = $assetPageEditURL . '&ckeupload=1';
}
if(!$this->useACF) $settings['allowedContent'] = true; // disables ACF, per CKEditor docs
if($this->rows) $settings['height'] = ($this->rows*2) . 'em'; // set editor height, based on rows value
$stylesSet = $this->getSetting('stylesSet');
if(empty($stylesSet)) $stylesSet = "mystyles:/wire/modules/Inputfield/InputfieldCKEditor/mystyles.js";
if(strpos($stylesSet, ':') !== false) {
list($k, $v) = explode(':', $stylesSet);
$settings['stylesSet'] = "$k:" . $this->pathFromRoot($v, strpos($v, '/wire/') === false);
}
foreach($this->findPlugins() as $name => $file) {
if(!in_array($name, $this->extraPlugins)) continue;
$value = $this->get("plugin_$name");
if(empty($value)) continue;
$value = $this->convertPluginSettingsStr($value);
if($value) $settings[$name] = $value;
}
$configURL = $config->urls->siteModules . $class . '/';
$configPath = $config->paths->siteModules . $class . '/';
if(file_exists($configPath . "config-$this->name.js")) {
$settings['customConfig'] = $configURL . "config-$this->name.js?nc=" . filemtime($configPath . "config-$this->name.js");
} else if(file_exists($configPath . "config.js")) {
$settings['customConfig'] = $configURL . "config.js?nc=" . filemtime($configPath . "config.js");
} else {
// defaults to the one in /wire/modules/Inputfield/InputfieldCKEditor/ckeditor-x.x.x/config.js
}
$customOptions = $this->get('customOptions');
if($customOptions) {
$value = $this->convertPluginSettingsStr($customOptions);
if($value) $settings = array_merge($settings, $value);
}
// optimization to remember the name of our JS config entry to prevent redundancy in multi-lang fields
if(!$this->configName) $this->configName = $this->className() . '_' . $this->name;
// optimization to prevent redundant configuration code when used in a repeater
if(strpos($this->configName, '_repeater')) $this->configName = preg_replace('/_repeater\d+/', '', $this->configName);
if(!in_array($this->configName, self::$configNames)) $this->config->js($this->configName, $settings);
self::$configNames[] = $this->configName;
if($this->inlineMode) {
// inline css must be pre-loaded
if($this->contentsInlineCss) {
$this->config->styles->add($this->pathFromRoot($this->contentsInlineCss, true));
} else {
$this->config->styles->add($this->config->urls('InputfieldCKEditor') . "contents-inline.css");
}
}
return parent::renderReady($parent, $renderValueMode);
}
/**
* Render the output code for CKEditor
*
*/
public function ___render() {
return ($this->inlineMode ? $this->renderInline() : $this->renderNormal());
}
/**
* Setup configuration specific to all instances rendered on the same page
*
* Primarily for language translation purposes
*
*/
protected function globalConfig() {
if(self::$isConfigured) return;
$cancelButtonLabel = $this->_('Cancel'); // Cancel button label
$linkClassOptions = array();
$linkConfig = $this->wire('modules')->getModuleConfigData('ProcessPageEditLink');
if(!empty($linkConfig) && !empty($linkConfig['classOptions'])) {
foreach(explode("\n", $linkConfig['classOptions']) as $option) {
$linkClassOptions[] = trim($option, '+ ');
}
}
$info = self::getModuleInfo();
$settings = array(
'language' => $this->_x('en', 'language-code'), // 2 character language code, lowercase
'timestamp' => '2015030801.' . $info['version'], // for cache busting (thanks teppo!)
'plugins' => $this->findPlugins(),
'editors' => array(),
'pwlink' => array(
'label' => $this->_('Insert Link'), // Insert link label, window headline and button text
'edit' => $this->_('Edit Link'), // Edit link label
'cancel' => $cancelButtonLabel,
'classOptions' => implode(',', $linkClassOptions),
),
'pwimage' => array(
'selectLabel' => $this->_('Select Image'),
'editLabel' => $this->_('Edit Image'),
'captionLabel' => $this->_('Your caption text here'),
'savingNote' => $this->_('Saving Image'),
'cancelBtn' => $cancelButtonLabel,
'insertBtn' => $this->_('Insert Image'),
'selectBtn' => $this->_('Select Another')
)
);
if($this->hasFieldtype === false) {
// not applicable when no page attached
unset($settings['pwlink'], $settings['pwimage']);
unset($settings['plugins']['pwlink'], $settings['plugins']['pwimage']);
}
$this->wire('config')->js($this->className(), $settings);
self::$isConfigured = true;
}
/**
* Locate all external plugins and return array of name => file
*
* @param bool $create Create necessary paths that don't exist? Does not apply to $extraPluginDirs. (default=false)
* @return array of plugin name => filename
*
*/
protected function findPlugins($create = false) {
static $plugins = array();
if(count($plugins) && !$create) return $plugins;
$files = $this->wire()->files;
$config = $this->wire()->config;
$class = $this->className();
$plugins = array();
$paths = array(
$config->paths->$class . "plugins/",
$config->paths->siteModules . "$class/plugins/",
);
$urls = array(
$config->urls->$class . "plugins/",
$config->urls->siteModules . "$class/plugins/",
);
foreach($this->extraPluginsDirs as $dir) {
$dir = trim($files->unixDirName($dir), '/');
if(strlen($dir) < 3 || !is_dir($config->paths->root . $dir)) continue;
$paths[] = $config->paths->root . "$dir/";
$urls[] = $config->urls->root . "$dir/";
}
foreach($paths as $key => $path) {
if(!file_exists($path)) {
if($create) {
$url = $urls[$key];
if($files->mkdir($path, true)) {
$this->message("Created new CKEditor external plugins directory: $url");
} else {
$this->warning("The CKEditor external plugins directory does not exist: $url - Please create it when/if you want to install external plugins.");
}
}
continue;
}
foreach(new \DirectoryIterator($path) as $dir) {
if(!$dir->isDir() || $dir->isDot()) continue;
$basename = $dir->getBasename();
$file = "$path$basename/plugin.js";
if(!file_exists($file)) continue;
$url = $urls[$key] . "$basename/plugin.js";
$plugins[$basename] = $url;
}
}
return $plugins;
}
/**
* Render the output code for CKEditor Normal Mode
*
*/
protected function renderNormal() {
//$out = parent::___render() . "<script>CKEDITOR.replace('$this->id', config.$this->configName);</script>";
$this->addClass('InputfieldCKEditorNormal');
$this->attr('data-configName', $this->configName);
$out = parent::___render() .
"<script>" .
"ProcessWire.config.InputfieldCKEditor.editors.$this->id = '$this->configName';" .
"config.InputfieldCKEditor.editors.$this->id = '$this->configName';" .
"</script>";
return $out;
}
/**
* Render the output code for CKEditor Inline Mode
*
*/
protected function renderInline() {
if(!$this->wire('modules')->get('MarkupHTMLPurifier')) {
$this->error($this->_('CKEditor inline mode requires the MarkupHTMLPurifier module. Using normal mode instead.'));
return $this->renderNormal();
}
$value = $this->purifyValue($this->attr('value'));
$attrs = array(
'id' => "{$this->id}_ckeditor",
'class' => 'InputfieldCKEditorInline InputfieldCKEditorInlineEditor',
'tabindex' => '0',
'data-configName' => $this->configName,
);
if((int) $this->inlineMode > 1 && (int) $this->attr('rows') > 1) {
$height = (((int) $this->attr('rows')) * 2) . 'em';
$attrs['style'] = "overflow:auto;height:$height";
}
$attrs = $this->getAttributesString($attrs);
$out =
"<div $attrs>$value</div>" .
"<input type='hidden' name='$this->name' id='$this->id' value='" . self::PLACEHOLDER_TEXT . "' />";
return $out;
}
public function ___renderValue() {
$out = "<div class='InputfieldTextareaContentTypeHTML InputfieldCKEditorInline'>" .
$this->wire('sanitizer')->purify($this->attr('value')) . "</div>";
return $out;
}
/**
* Clean up a value that will be sent to/from the editor
*
* This is primarily for HTML Purifier
*
* @param string $value
* @return string
*
*/
protected function purifyValue($value) {
$value = (string) $value;
if(strpos($value, "\r") !== false) $value = str_replace(array("\r\n", "\r"), "\n", $value);
$length = strlen($value);
if(!$length) return '';
if($this->usePurifier && $this->wire('modules')->isInstalled('MarkupHTMLPurifier')) {
$enableID = stripos($this->toolbar, 'anchor') !== false || $this->isExtraAllowedContentAttribute('id');
if(is_null(self::$purifier)) self::$purifier = $this->wire('modules')->get('MarkupHTMLPurifier');
$configData = $this->wire('modules')->getModuleConfigData('ProcessPageEditLink');
$targets = isset($configData['targetOptions']) ? $configData['targetOptions'] : '_blank';
$targets = explode("\n", $targets);
foreach($targets as $k => $v) $targets[$k] = trim(trim($v), '+');
self::$purifier->set('Attr.AllowedFrameTargets', $targets); // allow links opened in new window/tab
self::$purifier->set('Attr.EnableID', $enableID); // for anchor plugin use of id and name attributes
$value = self::$purifier->purify($value);
// $newLength = strlen($value);
// if($length != $newLength) $this->message("HTML Purifier: $this->name (before: $length bytes, after: $newLength bytes)", Notice::debug);
}
// convert <div> to paragraphs
$toggles = $this->toggles;
if(is_array($toggles)) {
if(in_array(self::toggleCleanDIV, $toggles) && strpos($this->formatTags, 'div') === false && strpos($value, '<div') !== false) {
// for some reason CKEditor insists on pasting DIVs sometimes when they should be paragraphs
// so we attempt to fix that issue here
$value = preg_replace('{\s*(</?)div[^><]*>\s*}is', '$1' . 'p>', $value);
// fix doubled paragraph tags, in case the above replacement cased any
while(strpos($value, '<p><p>') !== false) {
$value = str_replace(array('<p><p>', '</p></p>'), array('<p>', '</p>'), $value);
}
}
// remove gratuitous whitespace added by CKEditor
if(in_array(self::toggleCleanP, $toggles)) {
$value = str_replace(array('<p><br /></p>', '<p>&nbsp;</p>', "<p>\xc2\xa0</p>", '<p></p>', '<p> </p>'), '', $value);
}
// convert non-breaking space to regular space
if(in_array(self::toggleCleanNBSP, $toggles)) {
$value = str_ireplace('&nbsp;', ' ', $value);
$value = str_replace("\xc2\xa0",' ', $value);
}
}
// remove UTF-8 line separator characters
$value = str_replace($this->wire('sanitizer')->unentities('&#8232;'), '', $value);
return $value;
}
/**
* Process data submitted to a CKEditor field
*
* When inline mode is used, the content is run through HTML Purifier
*
* @param WireInputData $input
* @return $this
*
*/
public function ___processInput(WireInputData $input) {
$value = trim($input[$this->name]);
if($value == self::PLACEHOLDER_TEXT) return $this; // ignore value
$value = $this->purifyValue($value);
if($value != $this->attr('value')) {
$this->trackChange('value');
$this->setAttribute('value', $value);
}
return $this;
}
/**
* Convert a JSON-like plugin settings string to an array
*
* @param string $str
* @param array|string $returnType Specify blank array to return settings as array, specify blank string to return JSON string.
* @return bool|array Returns boolean false on failure
*
*/
protected function convertPluginSettingsStr($str, $returnType = array()) {
$str = trim($str, "{}\r\n "); // trim off surrounding whitespace and { }
if(empty($str)) return is_array($returnType) ? array() : '';
$test = "{ $str }";
$test = json_decode($test, true);
if(!empty($test)) {
// if string already validates as JSON, we don't need to do anything further
return is_array($returnType) ? $test : $str;
}
$lines = explode("\n", $str);
foreach($lines as $key => $line) {
$line = trim($line);
if(empty($line)) continue;
if(strpos(rtrim($line, ':, '), ':')) {
// line defines a "property: value"
$line = rtrim($line, ', ');
list($k, $v) = explode(':', $line);
$test = strtolower(trim($v));
if($test == 'true' || $test == 'false') {
// line has a boolean
} else if(is_numeric($test)) {
// line has a number
} else if(trim($test, "{}[]") != $test) {
// line is defining a map or array
} else if(trim($test, '"\'') != $test) {
// line is already surrounded in quotes
} else {
// line needs to be surrounded in quotes
$v = str_replace('"', '\\"', $v); // escape existing quotes
$v = '"' . trim($v) . '"';
}
$k = trim($k, '"\''); // if property is quoted, unquote it
$line = "\"$k\": $v,";
}
$lines[$key] = $line;
}
$str = implode("\n", $lines); // convert lines back to string
$str = rtrim($str, ", "); // remove last comma
if(strpos($str, '}') || strpos($str, ']') !== false) {
// remove commas that come right before a closing brace
$str = preg_replace('/,([\s\r\n]*[\}\]])/s', '$1', $str);
}
$str = str_replace(",\n", ", ", $str);
$str = "{ $str }";
$data = json_decode($str, true);
if($data === false || is_null($data)) return false;
if(is_string($returnType)) $data = trim(wireEncodeJSON($data, true, true), "{}\r\n ");
return $data;
}
/**
* Is the given attribute present for any tag in the extraAllowedContent?
*
* @param string $attr
* @param string $type One of 'attribute', 'class' or 'style' (default='attribute')
* @return bool
*
*/
protected function isExtraAllowedContentAttribute($attr, $type = 'attribute') {
$types = array(
'attribute' => array('[', ']'),
'class' => array('(', ')'),
'style' => array('{', '}'),
);
$is = false;
list($open, $close) = $types[$type];
foreach(explode($open, str_replace(array(' ', '!'), '', $this->extraAllowedContent)) as $attrs) {
list($attrs,) = explode($close, $attrs, 2);
$attrs = explode(',', $attrs);
if(!in_array($attr, $attrs)) continue;
$is = true;
break;
}
return $is;
}
/**
* Add an extra plugins dir available to all CKEditor instances
*
* Add an extra plugins dir, relative to ProcessWire installation root. An example could be
* `/site/modules/MyModule/plugins/`. Dir should have one or more directories within it having
* CKEditor plugins, which are identified by the presence of a plugin.js file in a directory,
* for example `/site/modules/MyModule/plugins/foobar/plugin.js` for a plugin named 'foobar'.
* Please note that the `/foobar/` portion of the example directory would NOT be in the dir
* specified to this method.
*
* Note the dir added from this method is saved to the CKEditor module configuration and thus
* is present for all future CKEditor instances, whether in this request or another. It will
* remain until removed by removeExtraPluginsDir().
*
* ~~~~~
* $f = $modules->get('InputfieldCKEditor');
* $f->addExtraPluginsDir('/site/modules/MyModule/plugins/');
* ~~~~~
*
* @param string $dir
* @since 3.0.179
* @see InputfieldCKEditor::removeExtraPluginsDir()
*
*/
public function addExtraPluginsDir($dir) {
$dirs = $this->extraPluginsDirs;
if(!is_array($dirs)) $dirs = array();
if(in_array($dir, $dirs)) return;
$dirs[] = $dir;
$this->extraPluginsDirs = $dirs;
$this->wire()->modules->saveConfig($this, 'extraPluginsDirs', $dirs);
}
/**
* Remove an extra plugins dir for all CKEditor instances
*
* ~~~~~
* $f = $modules->get('InputfieldCKEditor');
* $f->removeExtraPluginsDir('/site/modules/MyModule/plugins/');
* ~~~~~
*
* @param string $dir Dir relative to PW installation root, i.e. /site/modules/MyModule/plugins/
* @since 3.0.179
* @see InputfieldCKEditor::addExtraPluginsDir()
*
*/
public function removeExtraPluginsDir($dir) {
$dirs = $this->extraPluginsDirs;
if(!is_array($dirs)) return;
$key = array_search($dir, $dirs, true);
if($key === false) return;
unset($dirs[$key]);
$this->extraPluginsDirs = $dirs;
$this->wire()->modules->saveConfig($this, 'extraPluginsDirs', $dirs);
}
/*
* Inputfield configuration screen
*
*/
public function ___getConfigInputfields() {
$inputfields = parent::___getConfigInputfields();
$yes = $this->_('Yes');
$no = $this->_('No');
$example = '**' . $this->_('Example:') . '** ';
if(!$this->stripTags) {
// remove non-applicable property
$f = $inputfields->get('stripTags');
if($f) $inputfields->remove($f);
} else {
// keep showing it if value is set, in case a regular textarea w/stripTags was converted to a CKEditor
}
if(!$this->placeholder) {
$f = $inputfields->get('placeholder');
if($f) $inputfields->remove($f);
}
/** @var InputfieldFieldset $wrapper */
$wrapper = $this->wire('modules')->get('InputfieldFieldset');
$wrapper->label = $this->_('CKEditor Settings');
/** @var InputfieldTextarea $f */
$f = $this->wire('modules')->get('InputfieldTextarea');
$f->attr('name', 'toolbar');
$f->attr('value', $this->toolbar);
$f->label = $this->_('CKEditor Toolbar');
$f->description = $this->_('Separate each toolbar item with a comma. Group items by placing them on the same line and use a hyphen "-" where you want a separator to appear within a group. If you want more than one toolbar row, separate each row with a blank line.'); // Toolbar options description
$f->description .= ' ' . $this->_('Insert a hash "#" at the beginning of a line if you want it to be ignored.');
$f->notes = $this->_('Available core toolbar items:') . ' ' .
'About, Anchor, Blockquote, Bold, BulletedList, Copy, CopyFormatting, CreateDiv, Cut, Find, Flash, Format, ' .
'HorizontalRule, Iframe, Image, Indent, Italic, JustifyBlock, JustifyCenter, JustifyLeft, JustifyRight, ' .
'Language, Link, Maximize, NewPage, NumberedList, Outdent, PageBreak, Paste, PasteFromWord, PasteText, ' .
'Preview, Print, PWImage, PWLink, Redo, RemoveFormat, Replace, Save, Scayt, SelectAll, ShowBlocks, Smiley, ' .
'Source, Sourcedialog, SpecialChar, SpellChecker, Strike, Styles, Subscript, Superscript, ' .
'Table, Templates, Underline, Undo, Unlink';
$wrapper->add($f);
$purifierInstalled = $this->wire('modules')->isInstalled('MarkupHTMLPurifier');
$inlineLabel = $this->_('Inline editor');
$regularLabel = $this->_('Regular editor');
/** @var InputfieldRadios $f */
$f = $this->wire('modules')->get('InputfieldRadios');
$f->attr('name', 'inlineMode');
$f->label = $this->_('Editor Mode');
$f->addOption(0, $regularLabel . ' [span.detail] ' . $this->_('(flexible height, user adjustable)') . ' [/span]');
$f->addOption(1, $inlineLabel . ' [span.detail] ' . $this->_('(variable height, matches content)') . ' * [/span]');
$f->addOption(2, $inlineLabel . ' [span.detail] ' . $this->_('(fixed height, uses rows setting)') . ' * [/span]');
$f->attr('value', (int) $this->inlineMode);
$f->description = $this->_('When inline mode is enabled, the editor will not be loaded until you click in the text. This is faster and more efficient when there are numerous CKEditor fields on the page. However, it may not support as many features or editor customizations as regular mode.'); // Mode selection description
$f->notes = $this->_('*Inline mode requires that the HTML Purifier module is installed (MarkupHTMLPurifier).');
if($purifierInstalled) $f->notes = $this->_('*The required HTML Purifier module is installed.');
else $f->notes .= "\n" . $this->_('WARNING: it is not currently installed. You should install it before enabling inline mode.');
$wrapper->add($f);
// character and word counter option not available for inline editors
$f = $inputfields->getChildByName('showCount');
if($f) $f->notes = $this->_('Counter is supported for regular CKEditor fields, but not inline CKEditor fields.');
$f = $this->modules->get("InputfieldRadios");
$f->label = $this->_('Use ACF?');
$f->description = $this->_('When yes, the CKEditor Advanced Content Filter (ACF) will be active. This filter automatically strips any unrecognized markup or attributes from your HTML. Recommended.');
$f->attr('name', 'useACF');
$f->addOption(1, $yes);
$f->addOption(0, $no);
$f->attr('value', $this->useACF);
$f->columnWidth = 50;
$f->optionColumns = 1;
$wrapper->add($f);
$f = $this->modules->get("InputfieldRadios");
$f->label = $this->_('Use HTML Purifier?');
$f->description = $this->_('When yes, submitted content is run through [HTML Purifier](http://htmlpurifier.org/) for sanitization. This is a must have when using CKEditor for either inline mode or non-trusted users. Recommended either way.');
$f->attr('name', 'usePurifier');
$f->addOption(1, $yes);
$f->addOption(0, $no);
$f->attr('value', $this->usePurifier && $purifierInstalled ? 1 : 0);
if(!$purifierInstalled) $f->attr('disabled', 'disabled');
$f->columnWidth = 50;
$f->optionColumns = 1;
$wrapper->add($f);
/** @var InputfieldAsmSelect $f */
$f = $this->modules->get('InputfieldAsmSelect');
$f->attr('name', 'imageFields');
$f->label = $this->_('Images fields that may be used for dragged-in or pasted-in images');
$f->description = $this->_('If no fields are selected then an available images field will be automatically chosen at runtime. If the option labeled “None” is selected, then the feature will be disabled.');
$f->icon = 'picture-o';
$imageFields = $this->imageFields;
if(!is_array($imageFields)) $imageFields = array();
if(in_array('x', $imageFields) && count($imageFields) > 1) $imageFields = array('x');
foreach($this->wire('fields') as $field) {
if(!$field->type instanceof FieldtypeImage) continue;
if((int) $field->maxFiles == 1) continue;
$f->addOption($field->name);
}
$f->addOption('x', $this->_('None (disable drag/paste image uploads)'));
$f->attr('value', $imageFields);
// $f->columnWidth = 50;
$wrapper->add($f);
/* FUTURE USE
$f = $this->modules->get('InputfieldPageListSelect');
$f->attr('name', 'assetPageID');
$f->label = $this->_('Page to use for image/asset storage');
$f->description = $this->_('By default, uploaded images will be stored with the page being edited. If you want to use a shared page for these assets instead, select it here.');
$f->columnWidth = 50;
$f->attr('value', (int) $this->assetPageID);
$wrapper->add($f);
*/
$f = $this->modules->get("InputfieldCheckboxes");
$f->label = $this->_('Beautify Markup Toggles');
$f->attr('name', 'toggles');
$f->addOption(self::toggleCleanDIV, $this->_('Convert div tags to paragraph tags'));
$f->addOption(self::toggleCleanP, $this->_('Remove empty paragraph tags'));
$f->addOption(self::toggleCleanNBSP, $this->_('Remove non-breaking spaces (nbsp)'));
$f->description = $this->_('These are extra cleaning options (beyond ACF and HTML Purifier) that we have found helpful in many situations. They are applied when the page is saved. Checking all of these is recommended, unless you have a need to let any of these through in the markup.');
$f->attr('value', $this->toggles);
$wrapper->add($f);
$f = $this->modules->get("InputfieldText");
$f->label = $this->_('Format Tags');
$f->description = $this->_('Semicolon-separated list of selectable tags shown in the "format" dropdown.');
$f->notes = $this->_('Default format tags are:') . ' ' . self::FORMAT_TAGS;
$f->attr('name', 'formatTags');
$value = $this->get('formatTags');
$f->collapsed = ($value == self::FORMAT_TAGS ? Inputfield::collapsedYes : Inputfield::collapsedNo);
$f->attr('value', $value);
$wrapper->add($f);
$f = $this->modules->get("InputfieldTextarea");
$f->label = $this->_('Extra Allowed Content');
$f->description = $this->_('Allowed content rules per CKEditor [extraAllowedContent](http://docs.ckeditor.com/#!/api/CKEDITOR.config-cfg-extraAllowedContent) option. Applies only if the "Use ACF" checkbox above is checked.');
$f->description .= ' ' . $this->_('You may enter multiple rules by putting each on its own line.');
$f->notes = $example . "img[alt,!src,width,height]\n" . $this->_('The above example would allow alt, src, width and height attributes for img tags, with the src attribute always required.') . "\n" .
$this->_('See [details](http://docs.ckeditor.com/#!/guide/dev_allowed_content_rules-section-2) in CKEditor documentation.');
$f->attr('name', 'extraAllowedContent');
$value = $this->get('extraAllowedContent');
$f->collapsed = ($value == self::EXTRA_ALLOWED_CONTENT ? Inputfield::collapsedYes : Inputfield::collapsedNo);
$f->attr('value', str_replace("; ", "\n", $value)); // convert to multi-line for ease of input
$wrapper->add($f);
$pathNote = $this->_('Paths should be relative to your ProcessWire installation root (i.e. if site is running from a subdirectory, exclude that part).');
$descriptionCustomCss = $this->_('This option enables you to modify the way that text and other elements appear in your editor. This covers how they look in the administrative environment only, and has nothing to do with the front-end of your site.'); // contents.css description
$instructionsCustomCss = sprintf($this->_('Please see our [instructions](%s) on how to use this.'), 'https://github.com/processwire/processwire/blob/master/wire/modules/Inputfield/InputfieldCKEditor/README.md#custom-editor-css-file'); // custom editor css instructions
$f = $this->modules->get("InputfieldText");
$f->label = $this->_('Custom Editor CSS File (regular mode)');
$f->description = $descriptionCustomCss;
$f->notes = $example . "/site/modules/InputfieldCKEditor/contents.css\n$instructionsCustomCss $pathNote";
$f->attr('name', 'contentsCss');
$value = $this->get('contentsCss');
$f->collapsed = Inputfield::collapsedBlank;
$f->attr('value', $value);
$f->showIf = "inlineMode<1";
$wrapper->add($f);
$f = $this->modules->get("InputfieldText");
$f->label = $this->_('Custom Editor CSS File (inline mode)');
$f->description = $descriptionCustomCss;
$f->notes .= $example . "/site/modules/InputfieldCKEditor/contents-inline.css\n$instructionsCustomCss $pathNote";
$f->attr('name', 'contentsInlineCss');
$value = $this->get('contentsInlineCss');
$f->collapsed = Inputfield::collapsedBlank;
$f->attr('value', $value);
$f->showIf = 'inlineMode>0';
$wrapper->add($f);
$f = $this->modules->get("InputfieldText");
$f->label = $this->_('Custom Editor JS Styles Set');
$f->description = $this->_('This option enables you to specify custom styles for selection in your editor. It requires that you have a "Styles" item in your toolbar settings above.'); // styles set description
$f->notes = $example . "mystyles:/site/modules/InputfieldCKEditor/mystyles.js";
$f->notes .= "\n" .
sprintf(
$this->_('Please see our [instructions](%s) on how to use this.'), // styles set notes
'https://github.com/processwire/processwire/blob/master/wire/modules/Inputfield/InputfieldCKEditor/README.md#custom-editor-js-styles-set'
) . ' ' . $pathNote;
$f->attr('name', 'stylesSet');
$value = $this->get('stylesSet');
$f->collapsed = Inputfield::collapsedBlank;
$f->attr('value', $value);
$wrapper->add($f);
$descriptionJSON = $this->_('If used, enter one per line of **property: value**, or use a JSON string.');
$f = $this->modules->get('InputfieldTextarea');
$f->attr('name', "customOptions");
$f->label = $this->_('Custom Config Options');
$f->description = $this->_('Use this when you want to specify CKEditor config settings beyond those available on this screen.') . " $descriptionJSON";
$f->collapsed = Inputfield::collapsedBlank;
$value = $this->get("customOptions");
if($value) {
$test = $this->convertPluginSettingsStr($value, '');
if($test === false) {
$f->error($this->_('Custom Config Options failed JSON validation.'));
}
}
$f->attr('value', $value ? $value : '');
$f->notes = $example . "uiColor: #438ef0\n" .
$this->_('If preferred, these settings can also be set in one of these files:') .
"\n[/site/modules/InputfieldCKEditor/config.js](https://github.com/processwire/processwire/blob/master/site-default/modules/InputfieldCKEditor/config.js) - " .
$this->_('for all CKEditor fields') . " " .
"\n[/site/modules/InputfieldCKEditor/config-$this->name.js](https://github.com/processwire/processwire/blob/master/site-default/modules/InputfieldCKEditor/config-body.js) - " .
$this->_('only for this CKEditor field');
$wrapper->add($f);
/** @var InputfieldFieldset $fieldset */
$fieldset = $this->modules->get('InputfieldFieldset');
$fieldset->attr('name', '_plugins_fieldset');
$fieldset->label = $this->_('Plugins');
$wrapper->add($fieldset);
/** @var InputfieldCheckboxes $f */
$f = $this->modules->get('InputfieldCheckboxes');
$f->attr('name', 'extraPlugins');
$f->label = $this->_('Extra Plugins');
$f->description = $this->_('The following plugins were found. Check the box next to each plugin you would like to load.');
$f->description .= ' ' . $this->_('At least one plugin must be checked.');
$f->notes = $this->_('To add more plugins, place them in **/site/modules/InputfieldCKEditor/plugins/[name]/**, replacing **[name]** with the name of the plugin.');
$plugins = $this->findPlugins(true);
ksort($plugins);
foreach($plugins as $name => $file) {
$label = $name;
if($name == 'pwlink' || $name == 'pwimage') $label .= " (" . $this->_('recommended') . ")";
$f->addOption($name, $label);
}
$f->attr('value', $this->extraPlugins);
$fieldset->add($f);
foreach($plugins as $name => $file) {
if($name == 'pwimage' || $name == 'pwlink') continue;
$f = $this->modules->get('InputfieldTextarea');
$f->attr('name', "plugin_$name");
$f->label = sprintf($this->_('%s settings'), ucfirst($name));
$f->description = $descriptionJSON;
$f->collapsed = Inputfield::collapsedBlank;
$value = $this->get("plugin_$name");
if($value) {
$test = $this->convertPluginSettingsStr($value, '');
if($test === false) {
$f->error(sprintf($this->_('Plugin settings for "%s" failed JSON validation.'), $name));
}
}
$f->attr('value', $value ? $value : '');
$fieldset->add($f);
}
/*
$f = $this->modules->get("InputfieldTextarea");
$f->label = $this->_('Extra Plugins');
$f->description = $this->_('Comma separated list of extra plugins that CKEditor should load.');
$f->notes = $this->_('Example: pwlink,pwimage,myplugin,anotherplugin');
$f->attr('name', 'extraPlugins');
$value = $this->get('extraPlugins');
$f->collapsed = ($value == self::EXTRA_PLUGINS ? Inputfield::collapsedYes : Inputfield::collapsedNo);
$f->attr('value', $value);
$fieldset->add($f);
*/
$f = $this->modules->get("InputfieldText");
$f->label = $this->_('Remove Plugins');
$f->description = $this->_('Comma separated list of removed plugins that CKEditor should not load.');
$f->notes = $example . 'link,image';
$f->attr('name', 'removePlugins');
$value = $this->get('removePlugins');
$f->collapsed = ($value == self::REMOVE_PLUGINS ? Inputfield::collapsedYes : Inputfield::collapsedNo);
$f->attr('value', $value);
$fieldset->add($f);
$inputfields->add($wrapper);
return $inputfields;
}
}