'CKEditor', 'version' => 128, 'summary' => __('CKEditor textarea rich text editor.', __FILE__), 'installs' => array('MarkupHTMLPurifier'), ); } const toggleCleanDIV = 2; // remove
tags const toggleCleanNBSP = 8; // remove 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.4.3'; /** * 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('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('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)); } 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 * */ protected function toolbarStringToArray($str) { $str = str_replace(' ', '', $str); $items = array(); $lines = explode("\n", $str); foreach($lines as $line) { $line = trim($line); if(empty($line)) { $items[] = '/'; } else { $lineArray = explode(',', $line); $items[] = $lineArray; } } return $items; } /** * Prep a path starting from root to include any possible subdirs * */ protected function pathFromRoot($path) { if(strpos($path, '//') === false) { // regular path without domain $path = $this->wire('config')->urls->root . ltrim($path, '/'); } return $path; } /** * Render the output code for CKEditor * */ public function ___render() { $this->globalConfig(); $class = $this->className(); if($this->contentsCss) { $contentsCss = $this->pathFromRoot($this->contentsCss); } else { $contentsCss = $this->wire('config')->urls->$class . '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); } $settings = array( 'baseHref' => wire('config')->urls->root, 'contentsCss' => $contentsCss, 'extraAllowedContent' => $this->extraAllowedContent, 'extraPlugins' => implode(',', $this->extraPlugins), 'removePlugins' => $this->removePlugins, '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, ); 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->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); } 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 = $this->wire('config')->urls->siteModules . $class . '/'; $configPath = $this->wire('config')->paths->siteModules . $class . '/'; if(file_exists($configPath . "config-$this->name.js")) { $settings['customConfig'] = $configURL . "config-$this->name.js"; } else if(file_exists($configPath . "config.js")) { $settings['customConfig'] = $configURL . "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; 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 $settings = array( 'language' => $this->_x('en', 'language-code'), // 2 character language code, lowercase 'pwlink' => array( 'label' => $this->_('Insert Link'), // Insert link label, window headline and button text 'cancel' => $cancelButtonLabel ), 'pwimage' => array( 'selectLabel' => $this->_('Select Image'), 'editLabel' => $this->_('Edit Image'), 'savingNote' => $this->_('Saving Image'), 'cancelBtn' => $cancelButtonLabel, 'insertBtn' => $this->_('Insert This Image'), 'selectBtn' => $this->_('Select Another Image') ), 'plugins' => $this->findPlugins(), 'editors' => array() ); $this->wire('config')->js($this->className(), $settings); self::$isConfigured = true; } /** * Ensures that ckeditor.js is loaded before our own InputfieldCKEditor.js * * This method originates from Inputfield::hookRender * * @param HookEvent $event * */ public function hookRender($event) { static $loaded = false; if(!$loaded) { $class = $this->className(); $config = $this->wire('config'); $config->scripts->add($config->urls->$class . "ckeditor-" . self::CKEDITOR_VERSION . "/ckeditor.js"); $loaded = true; } parent::hookRender($event); } /** * Locate all external plugins and return array of name => file * * @param bool $create Create necessary paths that don't exist. (default=false) * @return array of plugin name => filename * */ protected function findPlugins($create = false) { static $plugins = array(); if(count($plugins) && !$create) return $plugins; $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($paths as $key => $path) { if(!file_exists($path)) { if($create) { $url = $urls[$key]; if(wireMkdir($path, true)) { $this->message("Created new CKEditor external plugins directory: $url"); } else { $this->error("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() . ""; $out = parent::___render() . ""; return $out; } /** * Render the output code for CKEditor Inline Mode * */ protected function renderInline() { if(!wire('modules')->get('MarkupHTMLPurifier')) { $this->error($this->_('CKEditor inline mode requires the MarkupHTMLPurifier module. Using normal mode instead.')); return $this->renderNormal(); } if($this->contentsInlineCss) $this->config->styles->add($this->pathFromRoot($this->contentsInlineCss)); else $this->config->styles->add($this->config->urls->InputfieldCKEditor . "contents-inline.css"); $value = $this->purifyValue($this->attr('value')); $out = "
') !== false) { $value = str_replace(array('
', '
'), array('', '
'), $value); } } // remove gratitutious whitespace added by CKEditor if(in_array(self::toggleCleanP, $this->toggles)) { $value = str_replace(array('', '', '
'), '', $value); } // convert non-breaking space to regular space if(in_array(self::toggleCleanNBSP, $this->toggles)) { $value = str_ireplace(' ', ' ', $value); $value = str_replace("\xc2\xa0",' ', $value); } return $value; } /** * Process data submitted to a CKEditor field * * When inline mode is used, the content is run through HTML Purifier * */ 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; } /* * Inputfield configuration screen * */ public function ___getConfigInputfields() { $inputfields = parent::___getConfigInputfields(); $yes = $this->_('Yes'); $no = $this->_('No'); $example = '**' . $this->_('Example:') . '** '; $f = $inputfields->get('stripTags'); if($f) $inputfields->remove($f); $f = $inputfields->get('placeholder'); if($f) $inputfields->remove($f); $wrapper = wire('modules')->get('InputfieldFieldset'); $wrapper->label = $this->_('CKEditor Settings'); $f = 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 $wrapper->add($f); $purifierInstalled = wire('modules')->isInstalled('MarkupHTMLPurifier'); $f = wire('modules')->get('InputfieldRadios'); $f->attr('name', 'inlineMode'); $f->label = $this->_('Editor Mode'); $f->addOption(0, $this->_('Regular Editor')); $f->addOption(1, $this->_('Inline Editor *')); $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.'); $f->optionColumns = 1; $wrapper->add($f); $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); $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 = $this->_('Please see our [instructions](https://github.com/ryancramerdesign/ProcessWire/blob/dev/wire/modules/Inputfield/InputfieldCKEditor/README.md#custom-editor-css-file) on how to use this.'); // 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=1'; $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" . $this->_('Please see our [instructions](https://github.com/ryancramerdesign/ProcessWire/blob/dev/wire/modules/Inputfield/InputfieldCKEditor/README.md#custom-editor-js-styles-set) on how to use this.') . " $pathNote"; // styles set notes $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/ryancramerdesign/ProcessWire/blob/dev/site-default/modules/InputfieldCKEditor/config.js) - " . $this->_('for all CKEditor fields') . " " . "\n[/site/modules/InputfieldCKEditor/config-$this->name.js](https://github.com/ryancramerdesign/ProcessWire/blob/dev/site-default/modules/InputfieldCKEditor/config-body.js) - " . $this->_('only for this CKEditor field'); $wrapper->add($f); $fieldset = $this->modules->get('InputfieldFieldset'); $fieldset->attr('name', '_plugins_fieldset'); $fieldset->label = $this->_('Plugins'); $wrapper->add($fieldset); $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->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; } }