From f44f4d5087ac397a3e80d79dadb2488b2f722570 Mon Sep 17 00:00:00 2001 From: bezumkin Date: Thu, 5 Apr 2012 12:41:40 +0400 Subject: [PATCH] Include typograf from http://habrahabr.ru/post/67687/ --- _build/build.config.sample.php | 8 - _build/data/transport.settings.php | 4 +- .../tiny_mce/engines/Jare/Exception.php | 14 + .../tiny_mce/engines/Jare/Typograph.php | 162 ++++++++++ .../engines/Jare/Typograph/Exception.php | 19 ++ .../tiny_mce/engines/Jare/Typograph/Param.php | 158 ++++++++++ .../Jare/Typograph/Param/Exception.php | 20 ++ .../tiny_mce/engines/Jare/Typograph/Tof.php | 231 +++++++++++++++ .../engines/Jare/Typograph/Tof/Dash.php | 80 +++++ .../engines/Jare/Typograph/Tof/Etc.php | 143 +++++++++ .../engines/Jare/Typograph/Tof/Number.php | 83 ++++++ .../engines/Jare/Typograph/Tof/Punctmark.php | 74 +++++ .../engines/Jare/Typograph/Tof/Quote.php | 87 ++++++ .../engines/Jare/Typograph/Tof/Space.php | 75 +++++ .../tiny_mce/engines/Jare/Typograph/Tool.php | 277 ++++++++++++++++++ .../tiny_mce/engines/remotetypograf.php | 123 ++++++++ .../plugins/typograf/editor_plugin.js | 222 ++++++++++++++ .../plugins/typograf/img/icon-jare.gif | Bin 0 -> 78 bytes .../plugins/typograf/img/icon-lebedev.gif | Bin 0 -> 151 bytes .../plugins/typograf/img/icon-spearance.gif | Bin 0 -> 166 bytes .../plugins/typograf/img/typograf.gif | Bin 0 -> 143 bytes .../tiny_mce/plugins/typograf/langs/en.js | 12 + .../tiny_mce/plugins/typograf/langs/ru.js | 12 + .../tiny_mce/plugins/typograf/typograf.php | 133 +++++++++ 24 files changed, 1927 insertions(+), 10 deletions(-) delete mode 100644 _build/build.config.sample.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Exception.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Exception.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param/Exception.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Dash.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Etc.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Number.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Punctmark.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Quote.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Space.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tool.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/engines/remotetypograf.php create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/editor_plugin.js create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-jare.gif create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-lebedev.gif create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-spearance.gif create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/typograf.gif create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/langs/en.js create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/langs/ru.js create mode 100644 assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/typograf.php diff --git a/_build/build.config.sample.php b/_build/build.config.sample.php deleted file mode 100644 index 15e9696..0000000 --- a/_build/build.config.sample.php +++ /dev/null @@ -1,8 +0,0 @@ - \ No newline at end of file diff --git a/_build/data/transport.settings.php b/_build/data/transport.settings.php index 45b7c0d..b57083a 100644 --- a/_build/data/transport.settings.php +++ b/_build/data/transport.settings.php @@ -44,7 +44,7 @@ $settings['tiny.custom_buttons1']= $modx->newObject('modSystemSetting'); $settings['tiny.custom_buttons1']->fromArray(array( 'key' => 'tiny.custom_buttons1', - 'value' => 'undo,redo,selectall,separator,pastetext,pasteword,separator,search,replace,separator,nonbreaking,hr,charmap,separator,image,modxlink,unlink,anchor,media,separator,cleanup,removeformat,separator,fullscreen,print,code,help', + 'value' => 'undo,redo,typograf,selectall,separator,pastetext,pasteword,separator,search,replace,separator,nonbreaking,hr,charmap,separator,image,modxlink,unlink,anchor,media,separator,cleanup,removeformat,separator,fullscreen,print,code,help', 'xtype' => 'textfield', 'namespace' => 'tinymce', 'area' => 'custom-buttons', @@ -89,7 +89,7 @@ $settings['tiny.custom_plugins']= $modx->newObject('modSystemSetting'); $settings['tiny.custom_plugins']->fromArray(array( 'key' => 'tiny.custom_plugins', - 'value' => 'style,advimage,advlink,modxlink,searchreplace,print,contextmenu,paste,fullscreen,noneditable,nonbreaking,xhtmlxtras,visualchars,media', + 'value' => 'style,advimage,advlink,modxlink,searchreplace,print,contextmenu,paste,fullscreen,noneditable,nonbreaking,xhtmlxtras,visualchars,media,typograf', 'xtype' => 'textfield', 'namespace' => 'tinymce', 'area' => 'general', diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Exception.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Exception.php new file mode 100644 index 0000000..24aa4de --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Exception.php @@ -0,0 +1,14 @@ + + * @category Jare + * @package Jare_Typograph + */ +class Jare_Exception extends Exception +{ +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph.php new file mode 100644 index 0000000..8e4ce66 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph.php @@ -0,0 +1,162 @@ + + * @category Jare + * @package Jare_Typograph + */ +class Jare_Typograph +{ + /** + * Перечень названий тофов, идущих с дистрибутивом + * + * @var array + */ + protected $_baseTof = array('quote', 'dash', 'punctmark', 'number', 'space', 'etc'); + + /** + * Массив из тофов, где каждой паре-ключ соответствует название тофа + * и его объект + * + * @var array + */ + protected $_tof = array(); + + /** + * Конструктор + * + * @param string $text строка для типографирования + * @return void + */ + public function __construct($text) + { + $this->_text = $text; + $this->_text = trim($this->_text); + } + + /** + * Метод для быстрого типографирования текста, при котором не нужно + * делать настройки тофов, их базовых параметров и т.п. + * + * @param string $text строка для типографирования + * @return string + */ + public static function quickParse($text) + { + $typograph = new self($text); + return $typograph->parse($typograph->getBaseTofsNames()); + } + + /** + * Возвращает массив из названий тофов, которые идут вместе с дистрибутивом + * + * @return array + */ + public function getBaseTofsNames() + { + return $this->_baseTof; + } + + /** + * Добавление тофа в очередь на обработку текста + * + * @param string $name название тофа + * @param Jare_Typograph_Tof $object экземляр класса, унаследованного от 'Jare_Typograph_Tof' + * @throws Jare_Typograph_Exception + * @return void + */ + public function setTof($name, $object) + { + $name = strtolower($name); + + if (!$object instanceof Jare_Typograph_Tof) { + require_once 'Pride/Typograph/Exception.php'; + throw new Pride_Typograph_Exception("Tof '$name' class must be extend Jare_Typograph_Tof"); + } + + $this->_tof[$name] = $object; + $this->_tof[$name]->setStringToParse(&$this->_text); + } + + /** + * Получение объекта тофа + * + * Если тоф не был раннее добавлен и при этом он является базовым, экземляр его класса + * будет создан автоматически + * + * @param string $name + * @throws Jare_Typograph_Exception + * @return Jare_Typograph_Tof + */ + public function getTof($name) + { + $name = strtolower($name); + + if (!isset($this->_tof[$name])) { + if (!in_array($name, $this->_baseTof)) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception('Incorrect name of tof'); + } + + $fileName = 'Jare/Typograph/Tof/' . ucfirst($name) . '.php'; + $className = 'Jare_Typograph_Tof_' . ucfirst($name); + + require_once $fileName; + + if (!class_exists($className, false)) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception('Class not exists'); + } + + $this->setTof($name, new $className); + } + + return $this->_tof[$name]; + } + + /** + * Типографирование текста + * + * @param mixed $tofs строка или массив из названий тофов, которые будут применены при типографирование текста + * @throws Jare_Typograph_Exception + * @return string + */ + public function parse($tofs) + { + if (is_string($tofs)) { + $tofs = array($tofs); + } + + if (!is_array($tofs)) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception('Incorrect type of tof-variable - try set array or string'); + } + + if (!count($tofs)) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception('You must set 1 or more tofs; your array is empty!'); + } + + require_once 'Jare/Typograph/Tool.php'; + Jare_Typograph_Tool::addCustomBlocks('
', '
'); + Jare_Typograph_Tool::addCustomBlocks(''); + Jare_Typograph_Tool::addCustomBlocks(''); + + $this->_text = Jare_Typograph_Tool::safeCustomBlocks($this->_text, true); + $this->_text = Jare_Typograph_Tool::safeTagChars($this->_text, true); + $this->_text = Jare_Typograph_Tool::clearSpecialChars($this->_text); + + foreach ($tofs as $tofName) { + $this->getTof($tofName)->parse(); + } + + $this->_text = Jare_Typograph_Tool::safeTagChars($this->_text, false); + $this->_text = Jare_Typograph_Tool::safeCustomBlocks($this->_text, false); + + return $this->_text; + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Exception.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Exception.php new file mode 100644 index 0000000..fba86c8 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Exception.php @@ -0,0 +1,19 @@ + + * @category Jare + * @package Jare_Typograph + */ +class Jare_Typograph_Exception extends Jare_Exception +{ +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param.php new file mode 100644 index 0000000..3801ef1 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param.php @@ -0,0 +1,158 @@ + + * @category Jare + * @package Jare_Typograph + */ +class Jare_Typograph_Param +{ + /** + * Ключи настроек + */ + const KEY_DISABLE_DEFAULT = '_disable'; + const KEY_DISABLE_USER = 'user_disable'; + const KEY_PARSE_PATTERN = 'pattern'; + const KEY_PARSE_REPLACE = 'replacement'; + const KEY_FUNCTION_LINK = 'function_link'; + const KEY_POSITION = 'position'; + + /** + * Настройки + * + * @var array + */ + protected $_option = array(); + + /** + * Настройки, которые были заданы по умолчанию при создание экземпляра класса; невозможно изменить + * + * @var array + */ + protected $_defaultOption = array(); + + /** + * Конструктор + * + * @param array $option массив из настроек, которые будут заданы по умолчанию + * @return void + */ + public function __construct($option = array()) + { + $this->_defaultOption = $option; + $this->_option = $option; + } + + /** + * Отключение параметра + * + * @param bool $status + * @return Jare_Typograph_Param + */ + public function disable($status) + { + $this->_option[self::KEY_DISABLE_USER] = (bool) $status; + return $this; + } + + /** + * Сброс заданных настроек к тем, которые были заданы при создание экземпляра класса + * + * @throws Jare_Typograph_Param_Exception + * @return Jare_Typograph_Param + */ + public function reset() + { + if (!count($this->_defaultOption)) { + require_once 'Jare/Typograph/Param/Exception.php'; + throw new Jare_Typograph_Param_Exception('This parameter does not have default options'); + } + + $this->_option = $this->_defaultOption; + + return $this; + } + + /** + * Задание настройки + * + * @param string $name + * @param string $value + * @throws Jare_Typograph_Param_Exception + * @return Jare_Typograph_Param + */ + public function setOption($name, $value) + { + $name = strtolower($name); + $value = trim($value); + + if ('_' === substr($name, 0, 1)) { + require_once 'Jare/Typograph/Param/Exception.php'; + throw new Jare_Typograph_Param_Exception('Prefix "_" reserved for system option'); + } + + if (empty($value)) { + require_once 'Jare/Typograph/Param/Exception.php'; + throw new Jare_Typograph_Param_Exception('Empty value. It\'s bad.'); + } + + switch ($name) { + case self::KEY_FUNCTION_LINK: + $this->_option[self::KEY_PARSE_PATTERN] = ''; + $this->_option[self::KEY_PARSE_REPLACE] = ''; + case self::KEY_PARSE_PATTERN: + case self::KEY_PARSE_REPLACE: + $this->_option[self::KEY_FUNCTION_LINK] = ''; + } + + $this->_option[$name] = $value; + + return $this; + } + + /** + * Возврат списка заданных настроек параметра + * + * @throws Jare_Typograph_Param_Exception + * @return array + */ + public function getOptions() + { + if (!count($this->_option)) { + require_once 'Jare/Typograph/Param/Exception.php'; + throw new Jare_Typograph_Param_Exception('This parameter does not have options!'); + } + + if (!empty($this->_option[self::KEY_FUNCTION_LINK])) { + return $this->_option; + } + + if (empty($this->_option[self::KEY_PARSE_PATTERN]) && !empty($this->_option[self::KEY_PARSE_REPLACE])) { + require_once 'Jare/Typograph/Param/Exception.php'; + throw new Jare_Typograph_Param_Exception('You must set up pattern and replacement or function link'); + } + + return $this->_option; + } + + /** + * Получение значения настройки + * + * @param string $name + * @throws Jare_Typograph_Param_Exception + * @return string + */ + public function getOption($name) + { + if (!in_array($name, $this->option)) { + require_once 'Jare/Typograph/Param/Exception.php'; + throw new Jare_Typograph_Param_Exception("This option doesn't have value"); + } + + return $this->_option[$name]; + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param/Exception.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param/Exception.php new file mode 100644 index 0000000..f042376 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Param/Exception.php @@ -0,0 +1,20 @@ + + * @category Jare + * @package Jare_Typograph + * @subpackage Param + */ +class Jare_Typograph_Param_Exception extends Jare_Typograph_Exception +{ +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof.php new file mode 100644 index 0000000..0a72341 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof.php @@ -0,0 +1,231 @@ + + * @category Jare + * @package Jare_Typograph + */ +abstract class Jare_Typograph_Tof +{ + /** + * Отключение обработки текста тофом + * + * @var bool + */ + protected $_disableParsing = false; + + /** + * Текст для типографирования + * + * @var string + */ + protected $_text = ''; + + /** + * Базовые параметры тофа + * + * @var array + */ + protected $_baseParam = array(); + + /** + * Установка базового параметра + * + * @param string $name + * @param Jare_Typograph_Param $param + * @return Jare_Typograph_Tof + */ + public function setBaseParam($name, Jare_Typograph_Param $param) + { + $this->_baseParam[$name] = $param->getOptions(); + return $this; + } + + /** + * Получение экземпляра класса базового параметра + * + * @param string $name + * @throws Jare_Typograph_Exception + * @return Jare_Typograph_Param + */ + public function getBaseParam($name) + { + if(!isset($this->_baseParam[$name])) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception("Incorrect base parameter name"); + } + + $param = new Jare_Typograph_Param($this->_baseParam[$name]); + return $param; + } + + /** + * Установка текста для типографирования + * + * @param string $text + * @return void + */ + public function setStringToParse($text) + { + $this->_text = &$text; + } + + /** + * Отключение типографирования текста данным тофом + * + * @param bool $status + * @return Jare_Typograph_Tof + */ + public function disableParsing($status) + { + $this->_disableParsing = (bool) $status; + return $this; + } + + /** + * Возврат статуса для типографирования данным тофом + * + * @return bool + */ + public function isDisabledParsing() + { + return $this->_disableParsing; + } + + /** + * Отключение базовых параметров тофа + * + * @param mixed $name массив или строка из названий параметров, которые необходимо отключить + * @return Jare_Typograph_Tof + */ + public function disableBaseParam($name) + { + if (!is_array($this->_baseParam) || !count($this->_baseParam)) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception("This tof dosn't have base parameters"); + } + + if (is_string($name)) { + $name = array($name); + } + + if (!is_array($name)) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception("Incorrect var type"); + } + + foreach ($name as $accessKey) { + if (!isset($this->_baseParam[$accessKey])) { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception("Incorrect name of base param - '$accessKey'"); + } else { + $this->_baseParam[$accessKey][Jare_Typograph_Param::KEY_DISABLE_USER] = true; + } + } + + return $this; + } + + /** + * Стандартное типографирование текста тофом + * + * @throws Jare_Typograph_Exception + * @return string + */ + public function parse() + { + $this->_preParse(); + + if (true === $this->_disableParsing) { + return $this->_text; + } + + if (is_array($this->_baseParam) || count($this->_baseParam)) { + foreach ($this->_baseParam as $accessKey => $param) { + $ignoreParsing = null; + + // Типографирование параметром отключено или включено пользователем + if (isset($param[Jare_Typograph_Param::KEY_DISABLE_USER])) { + $ignoreParsing = (bool) $param[Jare_Typograph_Param::KEY_DISABLE_USER]; + } + + if (null === $ignoreParsing) { + // Параметр отключен по умолчанию... + if (isset($param[Jare_Typograph_Param::KEY_DISABLE_DEFAULT])) { + $ignoreParsing = $param[Jare_Typograph_Param::KEY_DISABLE_DEFAULT]; + } + } + + if ($ignoreParsing) { + continue; + } + + // Ссылка на метод класса с правилами типографирования + if (!empty($param[Jare_Typograph_Param::KEY_FUNCTION_LINK])) { + $methodName = $param[Jare_Typograph_Param::KEY_FUNCTION_LINK]; + + if (method_exists($this, $methodName)) { + $this->$methodName(); + continue; + } else { + require_once 'Jare/Typograph/Exception.php'; + throw new Jare_Typograph_Exception("Incorrect method name - '$methodName'"); + } + } + + // Классическое типографирование регулярными выражениями + $this->_text = preg_replace($param[Jare_Typograph_Param::KEY_PARSE_PATTERN], $param[Jare_Typograph_Param::KEY_PARSE_REPLACE], $this->_text); + } + } + + $this->_postParse(); + + return $this->_text; + } + + /** + * Метод, который вызывается перед стандартным типографированием текста тофом + * + * @return void + */ + protected function _preParse() + { + } + + /** + * Метод, который вызывается после стандартным типографированием текста тофом + * + * @return void + */ + protected function _postParse() + { + } + + /** + * Создание защищенного тега с содержимым + * + * @see Jare_Typograph_Tool::buildSafeTag + * @param string $content + * @param string $tag + * @param array $attribute + * @return string + */ + protected function _buildTag($content, $tag = 'span', $attribute = array()) + { + require_once 'Jare/Typograph/Tool.php'; + $html = Jare_Typograph_Tool::buildSafedTag($content, $tag, $attribute); + + return $html; + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Dash.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Dash.php new file mode 100644 index 0000000..8599b00 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Dash.php @@ -0,0 +1,80 @@ + + * @category Jare + * @package Jare_Typograph + * @subpackage Tof + */ +class Jare_Typograph_Tof_Dash extends Jare_Typograph_Tof +{ + /** + * Базовые параметры тофа + * + * @var array + */ + protected $_baseParam = array( + 'mdash' => array( + '_disable' => false, + 'pattern' => '/([a-zа-я0-9]+|\,|\:|\)|\»\;|\|\")(\040|\t)(\-|\&mdash\;)(\s|$|\<)/u', + 'replacement' => '\1 —\4'), + 'mdash_2' => array( + '_disable' => false, + 'pattern' => '/(\n|\r|^|\>)(\-|\&mdash\;)(\t|\040)/', + 'replacement' => '\1— '), + 'mdash_3' => array( + '_disable' => false, + 'pattern' => '/(\.|\!|\?|\&hellip\;)(\040|\t|\ \;)(\-|\&mdash\;)(\040|\t|\ \;)/', + 'replacement' => '\1 — '), + 'years' => array( + '_disable' => false, + 'pattern' => '/(с|по|период|середины|начала|начало|конца|конец|половины|в|между)(\s+|\ \;)([\d]{4})(-)([\d]{4})(г|гг)?/eui', + 'replacement' => '"\1\2" . $this->_buildYears("\3","\5","\4") . "\6"'), + 'iz_za_pod' => array( + '_disable' => false, + 'pattern' => '/(\s|\ \;|\>)(из)(\040|\t|\ \;)\-?(за|под)([\.\,\!\?\:\;]|\040|\ \;)/uie', + 'replacement' => '("\1" == " " ? " " : "\1") . "\2-\4" . ("\5" == " "? " " : "\5")'), + 'to_libo_nibud' => array( + '_disable' => false, + 'function_link' => '_buildToLiboNibud') + ); + + /** + * Расстановка короткого тире между годами + * + * @param string $start + * @param string $end + * @param string $sep + * @return string + */ + protected function _buildYears($start, $end, $sep) + { + $start = (int) $start; + $end = (int) $end; + + return ($start >= $end) ? "$start$sep$end" : "$start–$end"; + } + + /** + * Расстановка дефиса перед -то, -либо, -нибудь + * + * @return void + */ + protected function _buildToLiboNibud() + { + $regExpMask = '/(\s|^|\ \;|\>)(кто|кем|когда|зачем|почему|как|что|чем|где|чего|кого)\-?(\040|\t|\ \;)\-?(то|либо|нибудь)([\.\,\!\?\;]|\040|\ \;|$)/ui'; + + while( preg_match($regExpMask, $this->_text)) { + $this->_text = preg_replace($regExpMask . 'e', '("\1" == " " ? " " : "\1") . "\2-\4" . ("\5" == " "? " " : "\5")', $this->_text); + } + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Etc.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Etc.php new file mode 100644 index 0000000..ce86d94 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Etc.php @@ -0,0 +1,143 @@ + + * @category Jare + * @package Jare_Typograph + * @subpackage Tof + */ +class Jare_Typograph_Tof_Etc extends Jare_Typograph_Tof +{ + /** + * Защищенные теги + * + * @todo привязать к методам из Jare_Typograph_Tool + */ + const BASE64_PARAGRAPH_TAG = 'cA=='; // p + const BASE64_BREAKLINE_TAG = 'YnIgLw=='; // br / (с пробелом и слэшем) + + /** + * Базовые параметры тофа + * + * @var array + */ + protected $_baseParam = array( + 'tm_replace' => array( + '_disable' => false, + 'pattern' => '/([\040\t])?\(tm\)/i', + 'replacement' => '™'), + 'r_sign_replace' => array( + '_disable' => false, + 'pattern' => '/\(r\)/ei', + 'replacement' => '$this->_buildTag($this->_buildTag("®", "small"), "sup")'), + 'copy_replace' => array( + '_disable' => false, + 'pattern' => '/\((c|с)\)\s+/iu', + 'replacement' => '© '), + 'acute_accent' => array( + '_disable' => false, + 'pattern' => '/(у|е|ы|а|о|э|я|и|ю|ё)\`(\w)/i', + 'replacement' => '\1́\2'), + 'auto_links' => array( + '_disable' => false, + 'pattern' => '/(\s|^)(http|ftp|mailto|https)(:\/\/)([\S]{4,})(\s|\.|\,|\!|\?|$)/ieu', + 'replacement' => '"\1" . $this->_buildTag("\4", "a", array("href" => "\2\3\4")) . "\5"'), + 'email' => array( + '_disable' => false, + 'pattern' => '/(\s|^)([a-z0-9\-\_\.]{3,})\@([a-z0-9\-\.]{2,})\.([a-z]{2,6})(\s|\.|\,|\!|\?|$|\<)/e', + 'replacement' => '"\1" . $this->_buildTag("\2@\3.\4", "a", array("href" => "mailto:\2@\3.\4")) . "\5"'), + 'hyphen_nowrap' => array( + '_disable' => false, + 'pattern' => '/(\ \;|\s|\>|^)([a-zа-я]+)\-([a-zа-я]+)(\s|\.|\,|\!|\?|\ \;|\&hellip\;|$)/uie', + 'replacement' => '"\1" . $this->_buildTag("\2-\3", "span", array("style" => "word-spacing:nowrap;")) . "\4"'), + 'simple_arrow' => array( + '_disable' => false, + 'function_link' => '_buildArrows'), + 'ip_address' => array( + '_disable' => false, + 'pattern' => '/(\s|\ \;|^)(\d{0,3}\.\d{0,3}\.\d{0,3}\.\d{0,3})/ie', + 'replacement' => '"\1" . $this->_nowrapIpAddress("\2")'), + 'optical_alignment' => array( + '_disable' => false, + 'function_link' => '_buildOpticalAlignment'), + 'paragraphs' => array( + '_disable' => false, + 'function_link' => '_buildParagraphs'), + + ); + + /** + * Объединение IP-адрессов в неразрывные конструкции (IPv4 only) + * + * @param unknown_type $triads + * @return unknown + */ + protected function _nowrapIpAddress($triads) + { + $triad = explode('.', $triads); + $addTag = true; + + foreach ($triad as $value) { + $value = (int) $value; + if ($value > 255) { + $addTag = false; + break; + } + } + + if (true === $addTag) { + $triads = $this->_buildTag($triads, 'span', array('style' => "word-spacing:nowrap;")); + } + + return $triads; + } + + /** + * Оптическое выравнивание для пунктуации + * + * @return void + */ + protected function _buildOpticalAlignment() + { + $this->_text = preg_replace('/(\040|\ \;|\t)\(/ei', '$this->_buildTag("\1", "span", array("style" => "margin-right:0.3em;")) . $this->_buildTag("(", "span", array("style" => "margin-left:-0.3em;"))', $this->_text); + $this->_text = preg_replace('/(\n|\r|^)\(/ei', '"\1" . $this->_buildTag("(", "span", array("style" => "margin-left:-0.3em;"))', $this->_text); + $this->_text = preg_replace('/([а-яa-z0-9]+)\,(\040+)/iue', '"\1" . $this->_buildTag(",", "span", array("style" => "margin-right:-0.2em;")) . $this->_buildTag(" ", "span", array("style" => "margin-left:0.2em;"))', $this->_text); + } + + /** + * Расстановка защищенных тегов параграфа (

...

) и переноса строки + * + * @return void + */ + protected function _buildParagraphs() + { + if (!preg_match('/\<\/?' . self::BASE64_PARAGRAPH_TAG . '\>/', $this->_text)) { + $this->_text = '<' . self::BASE64_PARAGRAPH_TAG . '>' . $this->_text . ''; + $this->_text = preg_replace('/([\040\t]+)?(\n|\r){2,}/e', '"<" .self::BASE64_PARAGRAPH_TAG . ">"', $this->_text); + } + + if (!preg_match('/\<' . self::BASE64_BREAKLINE_TAG . '\>/', $this->_text)) { + $this->_text = preg_replace('/(\n|\r)/e', '"<" . self::BASE64_BREAKLINE_TAG . ">"', $this->_text); + } + } + + /** + * Преобразование -> и <- в коды + * + * @return void + */ + protected function _buildArrows() + { + $this->_text = preg_replace('/(\s|\>|\ \;)\-\>(\s|\ \;|\<\/)/', '\1→\2', $this->_text); + $this->_text = preg_replace('/(\s|\>|\ \;)\<\-(\s|\ \;)/', '\1←\2', $this->_text); + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Number.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Number.php new file mode 100644 index 0000000..028e656 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Number.php @@ -0,0 +1,83 @@ + + * @category Jare + * @package Jare_Typograph + * @subpackage Tof + */ +class Jare_Typograph_Tof_Number extends Jare_Typograph_Tof +{ + /** + * Базовые параметры тофа + * + * @var array + */ + protected $_baseParam = array( + 'auto_times_x' => array( + '_disable' => false, + 'function_link' => '_buildTimesx'), + 'numeric_sub' => array( + '_disable' => false, + 'pattern' => '/([a-zа-я0-9])\_([\d]{1,3})([^а-яa-z0-9]|$)/ieu', + 'replacement' => '"\1" . $this->_buildTag($this->_buildTag("\2","small"),"sub") . "\3"'), + 'numeric_sup' => array( + '_disable' => false, + 'pattern' => '/([a-zа-я0-9])\^([\d]{1,3})([^а-яa-z0-9]|$)/ieu', + 'replacement' => '"\1" . $this->_buildTag($this->_buildTag("\2","small"),"sup") . "\3"'), + 'simple_fraction' => array( + '_disable' => true, + 'function_link' => '_buildSimpleFraction'), + 'math_chars' => array( + '_disable' => false, + 'function_link' => '_buildMathChars'), + ); + + /** + * Преобразование простых дробей (1/2, 1/4 и 3/4) в HTML-коды + * + * @return void + */ + protected function _buildSimpleFraction() + { + $this->_text = preg_replace('/(\D)1\/(2|4)(\D)/', '\1&frac1\2\3', $this->_text); + $this->_text = preg_replace('/(\D)3\/4(\D)/', '\1¾\2', $this->_text); + } + + /** + * Расстановка × между числами + * + * @return void + */ + protected function _buildTimesx() + { + $regExpMask = '/(\×\;)?(\d+)(\040*)(x|х)(\040*)(\d+)/u'; + + while(preg_match($regExpMask, $this->_text)) { + $this->_text = preg_replace($regExpMask, '\1\2×\6', $this->_text); + } + } + + /** + * Расстановка простейших математических знаков + * + * @return void + */ + protected function _buildMathChars() + { + $this->_text = str_replace('!=', '≠', $this->_text); + $this->_text = str_replace('<=', '≤', $this->_text); + $this->_text = str_replace('>=', '≥', $this->_text); + $this->_text = str_replace('~=', '≅', $this->_text); + $this->_text = str_replace('+-', '±', $this->_text); + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Punctmark.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Punctmark.php new file mode 100644 index 0000000..fd141cf --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Punctmark.php @@ -0,0 +1,74 @@ + + * @category Jare + * @package Jare_Typograph + * @subpackage Tof + */ +class Jare_Typograph_Tof_Punctmark extends Jare_Typograph_Tof +{ + /** + * Базовые параметры тофа + * + * @var array + */ + protected $_baseParam = array( + 'auto_comma' => array( + '_disable' => false, + 'pattern' => '/([a-zа-я])(\s| )(но|а)(\s| )/iu', + 'replacement' => '\1,\2\3\4'), + 'punctuation_marks_limit' => array( + '_disable' => false, + 'pattern' => '/([\!\.\?]){4,}/', + 'replacement' => '\1\1\1'), + 'punctuation_marks_base_limit' => array( + '_disable' => false, + 'pattern' => '/([\,]|[\:]|[\;]]){2,}/', + 'replacement' => '\1'), + 'hellip' => array( + '_disable' => false, + 'function_link' => '_buildHellipTags'), + 'eng_apostrophe' => array( + '_disable' => false, + 'pattern' => '/(\s|^|\>)([a-z]{2,})\'([a-z]+)/i', + 'replacement' => '\1\2’\3'), + 'fix_pmarks' => array( + '_disable' => false, + 'pattern' => '/([a-zа-я0-9])(\!|\.|\?){2}(\s|$|\<)/i', + 'replacement' => '\1\2\3'), + 'fix_brackets' => array( + '_disable' => false, + 'function_link' => '_fixBrackets'), + ); + + /** + * Расстановка многоточия вместо трех и двух точек + * + * @return void + */ + protected function _buildHellipTags() + { + $this->_text = str_replace(array('...', '..'), '…', $this->_text); + } + + /** + * Удаление лишних пробелов внутри скобок + * + * @return void + */ + protected function _fixBrackets() + { + $this->_text = preg_replace('/(\()(\040|\t)+/', '\1', $this->_text); + $this->_text = preg_replace('/(\040|\t)+(\))/', '\2', $this->_text); + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Quote.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Quote.php new file mode 100644 index 0000000..f03c755 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Quote.php @@ -0,0 +1,87 @@ + + * @category Jare + * @package Jare_Typograph + * @subpackage Tof + */ +class Jare_Typograph_Tof_Quote extends Jare_Typograph_Tof +{ + /** + * Типы кавычек + */ + const QUOTE_FIRS_OPEN = '«'; + const QUOTE_FIRS_CLOSE = '»'; + const QUOTE_CRAWSE_OPEN = '„'; + const QUOTE_CRAWSE_CLOSE = '“'; + + /** + * Базовые параметры тофа + * + * @var array + */ + protected $_baseParam = array( + 'quotes_outside_a' => array( + '_disable' => false, + 'pattern' => '/(\<%%\_\_.+?\>)\"(.+?)\"(\<\/%%\_\_.+?\>)/s', + 'replacement' => '"\1\2\3"'), + 'open_quote' => array( + '_disable' => false, + 'function_link' => '_buildOpenQuote'), + 'close_quote' => array( + '_disable' => false, + 'function_link' => '_buildCloseQuote'), + 'optical_alignment' => array( + '_disable' => false, + 'function_link' => '_buildOpticalAlignment'), + ); + + /** + * Расстановка закрывающих кавычек + * + * @return void + */ + protected function _buildOpenQuote() + { + $regExpMask = '/(^|\(|\s|\>)(\"|\\\")(\S+)/iu'; + + while(preg_match($regExpMask, $this->_text)) { + $this->_text = preg_replace($regExpMask . 'e', '"\1" . self::QUOTE_FIRS_OPEN . "\3"', $this->_text); + } + } + + /** + * Расстановка закрывающих кавычек + * + * @return void + */ + protected function _buildCloseQuote() + { + $regExpMask = '/([a-zа-я0-9]|\.|\&hellip\;|\!|\?|\>)(\"|\\\")+(\.|\&hellip\;|\;|\:|\?|\!|\,|\s|\)|\<\/|$)/ui'; + + while(preg_match($regExpMask, $this->_text)) { + $this->_text = preg_replace($regExpMask . 'e', '"\1" . self::QUOTE_FIRS_CLOSE . "\3"', $this->_text); + } + } + + /** + * Оптическое выравнивание открывающей кавычки + * + * @return void + */ + protected function _buildOpticalAlignment() + { + $this->_text = preg_replace('/([a-zа-я\-]{3,})(\040|\ \;|\t)(\«\;)/uie', '"\1" . $this->_buildTag("\2", "span",array("style" => "margin-right:0.44em;")) . $this->_buildTag("\3", "span", array("style" => "margin-left:-0.44em;"))', $this->_text); + $this->_text = preg_replace('/(\n|\r|^)(\«\;)/ei', '"\1" . $this->_buildTag("\2", "span", array("style" => "margin-left:-0.44em;"))', $this->_text); + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Space.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Space.php new file mode 100644 index 0000000..fd1f1d8 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tof/Space.php @@ -0,0 +1,75 @@ + + * @category Jare + * @package Jare_Typograph + * @subpackage Tof + */ +class Jare_Typograph_Tof_Space extends Jare_Typograph_Tof +{ + /** + * Базовые параметры тофа + * + * @var array + */ + protected $_baseParam = array( + 'nobr_abbreviation' => array( + '_disable' => false, + 'pattern' => '/(\s+|^|\>)(\d+)(\040|\t)*(dpi|lpi)([\s\;\.\?\!\:\(]|$)/i', + 'replacement' => '\1\2 \4\5'), + 'nobr_acronym' => array( + '_disable' => false, + 'pattern' => '/(\s|^|\>)(гл|стр|рис|илл)\.(\040|\t)*(\d+)(\s|\.|\,|\?|\!|$)/iu', + 'replacement' => '\1\2. \4\5'), + 'nobr_before_unit' => array( + '_disable' => false, + 'pattern' => '/(\s|^|\>)(\d+)(м|мм|см|км|гм|km|dm|cm|mm)(\s|\.|\!|\?|\,|$)/iu', + 'replacement' => '\1\2 \3\4'), + 'remove_space_before_punctuationmarks' => array( + '_disable' => false, + 'pattern' => '/(\040|\t|\ \;)([\,\:\.])(\s+)/', + 'replacement' => '\2\3'), + 'autospace_after_comma' => array( + '_disable' => true, + 'pattern' => '/(\040|\t|\ \;)?\,([а-яa-z0-9])/iu', + 'replacement' => ', \2'), + 'autospace_after_pmarks' => array( + '_disable' => false, + 'pattern' => '/(\040|\t|\ \;)([a-zа-я0-9]+)(\040|\t|\ \;)?(\:|\)|\,|\.|\&hellip\;|(?:\!|\?)+)([а-яa-z])/iu', + 'replacement' => '\1\2\4 \5'), + 'super_nbsp' => array( + '_disable' => false, + 'pattern' => '/(\s|^|\«\;|\>|\(|\&mdash\;\ \;)([a-zа-я]{1,2}\s+)([a-zа-я]{1,2}\s+)?([a-zа-я0-9\-]{2,})/ieu', + 'replacement' => '"\1" . trim("\2") . " " . ("\3" ? trim("\3") . " " : "") . "\4"'), + 'many_spaces_to_one' => array( + '_disable' => false, + 'pattern' => '/(\040|\t)+/', + 'replacement' => ' '), + 'clear_percent' => array( + '_disable' => false, + 'pattern' => '/(\d+)([\t\040]+)\%/', + 'replacement' => '\1%'), + 'nbsp_before_open_quote' => array( + '_disable' => false, + 'pattern' => '/(^|\040|\t|>)([a-zа-я]{1,2})\040(\«\;|\&bdquo\;)/u', + 'replacement' => '\1\2 \3'), + 'nbsp_before_particle' => array( + '_disable' => false, + 'pattern' => '/(\040|\t)+(ли|бы|б|же|ж)(\ \;|\.|\,|\:|\;|\&hellip\;|\s)/iue', + 'replacement' => '" \2" . ("\3" == " " ? " " : "\3")'), + 'ps_pps' => array( + '_disable' => false, + 'pattern' => '/(^|\040|\t|\>|\r|\n)(p\.\040?)(p\.\040?)?(s\.)/ie', + 'replacement' => '"\1" . trim("\2") . " " . ("\3" ? trim("\3") . " " : "") . "\4"'), + ); +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tool.php b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tool.php new file mode 100644 index 0000000..723a2bc --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/Jare/Typograph/Tool.php @@ -0,0 +1,277 @@ + + * @category Jare + * @package Jare_Typograph + */ +class Jare_Typograph_Tool +{ + /** + * Таблица символов + * + * @var array + */ + protected static $_charsTable = array( + '"' => array('«', '»', '“', '‘', '„', '“', '"', '«', '»','«', '»', '„', '“', '”'), + ' ' => array(' ', ' ', ' ', ' '), + '-' => array('—', '–', '−', '—', '—', '—', '–'), + '==' => array('≡'), + '...' => array('…'), + '!=' => array('≠', '≠'), + '<=' => array('≤', '≤'), + '>=' => array('≥', '≥'), + '1/2' => array('½', '½'), + '1/4' => array('¼', '¼'), + '3/4' => array('¾', '¾'), + '+-' => array('±', '±'), + '&' => array('&', '&'), + '(tm)' => array('™'), + '(r)' => array('®', '®', '®'), + '(c)' => array('©', '©', '©'), + '`' => array('́'), + '\'' => array('’', '’'), + 'x' => array('×', '×', '×'), + ); + + /** + * Список из элементов, в которых текст не будет типографироваться + * + * @var array + */ + protected static $_customBlocks = array(); + + /** + * Добавление к тегам атрибута 'id', благодаря которому + * при повторном типографирование текста будут удалены теги, + * расставленные данным типографом + * + * @var array + */ + protected static $_typographSpecificTagId = false; + + + /** + * Удаление кодов HTML из текста + * + * @param string $text + * @return string + */ + public static function clearSpecialChars($text) + { + foreach (self::$_charsTable as $char => $vals) { + foreach ($vals as $code) { + $text = str_replace($code, $char, $text); + } + } + + return $text; + } + + /** + * Удаление тегов HTML из текста + * Тег
будет преобразов в перенос строки \n, сочетание тегов

- + * в двойной перенос + * + * @param string $text + * @param array $allowableTag массив из тегов, которые будут проигнорированы + * @return string + */ + public static function removeHtmlTags($text, $allowableTag = null) + { + $ignore = null; + + if (null !== $allowableTag) { + if (is_string($allowableTag)) { + $allowableTag = array($allowableTag); + } + + if (is_array($allowableTag)) { + require_once 'Jare/Typograph/Tool/Exception.php'; + throw new Jare_Typograph_Tool_Exception('Bad type of param #2'); + } + + foreach ($allowableTag as $tag) { + if ('<' !== substr($tag, 0, 1) || '>' !== substr($tag, -1, 1)) { + require_once 'Jare/Typograph/Tool/Exception.php'; + throw new Jare_Typograph_Tool_Exception("Incorrect tag $tag"); + } + + if ('/' === substr($tag, 1, 1)) { + require_once 'Jare/Typograph/Tool/Exception.php'; + throw new Jare_Typograph_Tool_Exception("Incorrect tag $tag"); + } + } + + $ignore = implode('', $allowableTag); + } + + $text = preg_replace('/\/i', "\n", $text); + $text = preg_replace('/\<\/p\>\s*\/', "\n\n", $text); + $text = strip_tags($text, $ignore); + + return $text; + } + + /** + * Сохраняем содержимое тегов HTML + * + * Тег 'a' кодируется со специальным префиксом для дальнейшей + * возможности выносить за него кавычки. + * + * @param string $text + * @param bool $safe + * @return string + */ + public static function safeTagChars($text, $safe) + { + $safe = (bool) $safe; + + if (true === $safe) { + $text = preg_replace('/(\<\/?)(.+?)(\>)/se', '"\1" . ( substr(trim("\2"), 0, 1) === "a" ? "%%___" : "" ) . self::_encrypteContent(trim("\2")) . "\3"', $text); + } else { + $text = preg_replace('/(\<\/?)(.+?)(\>)/se', '"\1" . ( substr(trim("\2"), 0, 3) === "%%___" ? self::_decrypteContent(substr(trim("\2"), 4)) : self::_decrypteContent(trim("\2")) ) . "\3"', $text); + } + + return $text; + } + + /** + * Создание тега с защищенным содержимым + * + * @param string $content текст, который будет обрамлен тегом + * @param string $tag + * @param array $attribute список атрибутов, где ключ - имя атрибута, а значение - само значение данного атрибута + * @return string + */ + public static function buildSafedTag($content, $tag = 'span', $attribute = array()) + { + $htmlTag = $tag; + + if (self::$_typographSpecificTagId) { + if(!isset($attribute['id'])) { + $attribute['id'] = 'jt-2' . mt_rand(1000,9999); + } + } + + if (count($attribute)) { + + foreach ($attribute as $attr => $value) { + $htmlTag .= " $attr=\"$value\""; + } + } + + return "<" . self::_encrypteContent($htmlTag) . ">$content"; + } + + /** + * Список защищенных блоков + * + * @return array + */ + public static function getCustomBlocks() + { + return self::$_customBlocks; + } + + /** + * Удаленного блока по его номеру ключа + * + * @param int $blockId + * @return void + */ + public static function removeCustomBlock($blockId) + { + if (!is_int($blockId)) { + require_once 'Jare/Typograph/Tool/Exception.php'; + throw new Jare_Typograph_Tool_Exception("Incorrect type of value"); + } + + if (!isset(self::$_customBlocks[$blockId])) { + require_once 'Jare/Typograph/Tool/Exception.php'; + throw new Jare_Typograph_Tool_Exception("Incorrect index"); + } + + unset(self::$_customBlocks[$blockId]); + } + + /** + * Добавление защищенного блока + * + * + * Jare_Typograph_Tool::addCustomBlocks('', ''); + * Jare_Typograph_Tool::addCustomBlocks('\', '\<\/span\>', true); + * + * + * @param string $open начало блока + * @param string $close конец защищенного блока + * @param bool $quoted специальные символы в начале и конце блока экранированы + * @return void + */ + public static function addCustomBlocks($open, $close, $quoted = false) + { + $open = trim($open); + $close = trim($close); + + if (empty($open) || empty($close)) { + require_once 'Jare/Typograph/Tool/Exception.php'; + throw new Jare_Typograph_Tool_Exception("Bad value"); + } + + if (false === $quoted) { + $open = preg_quote($open, '/'); + $close = preg_quote($close, '/'); + } + + self::$_customBlocks[] = array($open, $close); + } + + /** + * Сохранение содержимого защищенных блоков + * + * @param string $text + * @param bool $safe если true, то содержимое блоков будет сохранено, иначе - раскодировано. + * @return string + */ + public static function safeCustomBlocks($text, $safe) + { + $safe = (bool) $safe; + + if (count(self::$_customBlocks)) { + $safeType = true === $safe ? "self::_encrypteContent('\\2')" : "stripslashes(self::_decrypteContent('\\2'))"; + + foreach (self::$_customBlocks as $block) { + $text = preg_replace("/({$block[0]})(.+?)({$block[1]})/se", "'\\1' . $safeType . '\\3'" , $text); + } + } + + return $text; + } + + /** + * Метод, осуществляющий кодирование (сохранение) информации + * с целью невозможности типографировать ее + * + * @param string $text + * @return string + */ + protected static function _encrypteContent($text) + { + return base64_encode($text); + } + + /** + * Метод, осуществляющий декодирование информации + * + * @param string $text + * @return string + */ + protected static function _decrypteContent($text) + { + return base64_decode($text); + } +} \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/engines/remotetypograf.php b/assets/components/tinymce/jscripts/tiny_mce/engines/remotetypograf.php new file mode 100644 index 0000000..e31e320 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/engines/remotetypograf.php @@ -0,0 +1,123 @@ +processText ('" - ""? - !"'); +*/ + +class RemoteTypograf +{ + var $_entityType = 4; + var $_useBr = 1; + var $_useP = 1; + var $_maxNobr = 3; + var $_encoding = 'UTF-8'; + + function RemoteTypograf ($encoding) + { + if ($encoding) $this->_encoding = $encoding; + } + + function htmlEntities() + { + $this->_entityType = 1; + } + + function xmlEntities() + { + $this->_entityType = 2; + } + + function mixedEntities() + { + $this->_entityType = 4; + } + + function noEntities() + { + $this->_entityType = 3; + } + + function br ($value) + { + $this->_useBr = $value ? 1 : 0; + } + + function p ($value) + { + $this->_useP = $value ? 1 : 0; + } + + function nobr ($value) + { + $this->_maxNobr = $value ? $value : 0; + } + + function processText ($text) + { + $text = str_replace ('&', '&', $text); + $text = str_replace ('<', '<', $text); + $text = str_replace ('>', '>', $text); + + $SOAPBody = '_encoding . '"?> + + + + ' . $text . ' + ' . $this->_entityType . ' + ' . $this->_useBr . ' + ' . $this->_useP . ' + ' . $this->_maxNobr . ' + + +'; + + $host = 'typograf.artlebedev.ru'; + $SOAPRequest = 'POST /webservices/typograf.asmx HTTP/1.1 +Host: typograf.artlebedev.ru +Content-Type: text/xml +Content-Length: ' . strlen ($SOAPBody). ' +SOAPAction: "http://typograf.artlebedev.ru/webservices/ProcessText" + +'. + $SOAPBody; + + $remoteTypograf = fsockopen ($host, 80); + fwrite ($remoteTypograf, $SOAPRequest); + $typografResponse = ''; + while (!feof ($remoteTypograf)) + { + $typografResponse .= fread ($remoteTypograf, 8192); + } + fclose ($remoteTypograf); + + $startsAt = strpos ($typografResponse, '') + 19; + $endsAt = strpos ($typografResponse, ''); + $typografResponse = substr ($typografResponse, $startsAt, $endsAt - $startsAt - 1); + + $typografResponse = str_replace ('&', '&', $typografResponse); + $typografResponse = str_replace ('<', '<', $typografResponse); + $typografResponse = str_replace ('>', '>', $typografResponse); + + return $typografResponse; + } +} + +?> diff --git a/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/editor_plugin.js b/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/editor_plugin.js new file mode 100644 index 0000000..fc6eb53 --- /dev/null +++ b/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/editor_plugin.js @@ -0,0 +1,222 @@ +(function() { + + tinymce.PluginManager.requireLangPack("typograf"); + + tinymce.create("tinymce.plugins.Typograf", { + + init : function(ed, url) { + + this.editor = ed; + this.url = url; + + }, + + // COMMAND + + execCommand: function(cmd, ui, type) { + + var ed = tinyMCE.activeEditor; + var url = this.url; + var anchorStart = "{mceTypograf-selection-start}"; // This is pretty unique ;) + var anchorEnd = "{mceTypograf-selection-end}"; + + type = type || "lebedev"; // Default is A. Lebedev + + switch (cmd) { + + // Remember to have the "mce" prefix for commands so they don't intersect with built in ones in the browser. + case "mceTypograf": + + // Highlight the control + ed.controlManager.setActive("typograf", true); + + var sel = !ed.selection.isCollapsed(); + + // Remember current state of content and selection + var orig = ed.getContent(); + var mark = ed.selection.getBookmark(); + + // Handle selection + if (sel) { + + var range = ed.selection.getRng() + var h1 = "", h2 = "", hx = "", text = ""; + + // Range object has two parts, we will parse them separately + // Known issues script can die here if selection goes through the table, we should handle it somehow + + if (range.startContainer.data != range.endContainer.data) { + + // Start anchor + text = range.startContainer.data; + h1 = text.substr(0, range.startOffset); + h2 = text.substr(range.startOffset); + + text = h1 + anchorStart + h2; + range.startContainer.data = text; // Replace original content with anchored one + + // End anchor + text = range.endContainer.data; + h1 = text.substr(0, range.endOffset); + h2 = text.substr(range.endOffset); + + text = h1 + anchorEnd + h2; + range.endContainer.data = text; // Replace original content with anchored one + + } else { + + // Get both parts + h1 = range.startContainer.data.substr(0, range.startOffset); + h2 = range.startContainer.data.substr(range.endOffset); + hx = range.startContainer.data.substr(range.startOffset, range.endOffset - range.startOffset); + + range.startContainer.data = h1 + anchorStart + hx + anchorEnd + h2; + + } + + } + + var send = ed.getContent(); + + // Put back original content while transaction. Sometimes content may twitch + ed.setContent(orig); + ed.selection.moveToBookmark(mark); + + // Prepare content part + if (sel) { + + var h1 = send.indexOf(anchorStart); + var h2 = send.indexOf(anchorEnd); + + var part1 = send.substr(0, h1); + var part2 = send.substr(h2 + anchorEnd.length); + send = send.substr(h1 + anchorStart.length, h2 - h1 - anchorStart.length); + + // Add whitespaces if there are any + part1 = part1 + (/^[\s]+/i.exec(send) || [""])[0]; + part2 = (/[\s]+$/i.exec(send) || [""])[0] + part2; + + send.replace(/^[\s]+/i, "").replace(/[\s]+$/i, ""); + + } + + // Send raw XML data + tinymce.util.XHR.send({ + type : "POST", + url : url + "/typograf.php", + data : "" + type + "", + error : function(e, x) { alert(e); }, + success : function(text) { + + // Remove BOM + text = text.replace(/^[\ufeff]+/g, ''); + + if (sel) text = part1 + text + part2; + + // Set new contents + ed.setContent(text); + ed.selection.moveToBookmark(mark); // Usually it fits, because typograf only transforms entities, so the length of the text is equal + + if (!confirm(ed.getLang("typograf.confirm"))) { // Set original contents + + // Restore everything + ed.setContent(orig); + ed.selection.moveToBookmark(mark); + + } + + // Remove highlight from the control + ed.controlManager.setActive("typograf", false); + + } + }); + + return true; + break; + + } + + // Pass to next handler in chain + return false; + + }, + + // CONTROL + + createControl: function(n, cm) { + + var ed = tinyMCE.activeEditor; + var url = this.url; + + switch (n) { + case "typograf": + + var c = cm.createSplitButton(n, { + title: "typograf.desc", + image: url + "/img/typograf.gif", + onclick: function() { + + ed.execCommand("mceTypograf", false, ""); + + } + }); + + c.onRenderMenu.add(function(c, m) { + m.add({ + title: "typograf.title", + "class" : "mceMenuItemTitle" + }).setDisabled(1); + m.add({ + title: "typograf.lebedev", + image: url + "/img/icon-lebedev.gif", + onclick: function() { + + ed.execCommand("mceTypograf", false, "lebedev"); + + } + }); + m.add({ + title: 'typograf.spearance', + image: url + "/img/icon-spearance.gif", + onclick: function() { + + ed.execCommand("mceTypograf", false, "spearance"); + + } + }); + m.add({ + title: 'typograf.jare', + image: url + "/img/icon-jare.gif", + onclick: function() { + + ed.execCommand("mceTypograf", false, "jare"); + + } + }); + }); + + return c; + + } + + return null; + + }, + + // INFO + + getInfo : function() { + return { + longname : "Typograf", + author : "DiS @ Nimax Studio", + authorurl : "http://dis.dj", + infourl : "http://nimax.ru", + version : "2.1.1" + }; + } + + }); + + tinymce.PluginManager.add("typograf", tinymce.plugins.Typograf); + +})(); \ No newline at end of file diff --git a/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-jare.gif b/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-jare.gif new file mode 100644 index 0000000000000000000000000000000000000000..7750bb58cb093bd23a8b84edc277153cce409062 GIT binary patch literal 78 zcmZ?wbhEHb6krfwXkcV;aB=_t|G(l-7DfgJMg|=QAOOiQFsb(RcQPEicZs`rUBu(o fm`CeV?z%O`rOPHs&eF`9v|48Mx@Aw?85yhra%>st literal 0 HcmV?d00001 diff --git a/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-lebedev.gif b/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-lebedev.gif new file mode 100644 index 0000000000000000000000000000000000000000..bd9ac83fd946f0b7e8a612187c376c03b31faada GIT binary patch literal 151 zcmZ?wbhEHb6krfw*v!CiOhR$5fW*Dx;^#}(-m7l8mRr~7_b4wpDbWu z9S{jJgMr26gM#PswdUcwO25gnS8*iqusKMy9+WzwGWXcVZTf{CYFYa&BhL#6FhuWi h=oH(rbAr>XR~*(1UN;2QPM>XaxW7KExPyVg8UWQ#F0uds literal 0 HcmV?d00001 diff --git a/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-spearance.gif b/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/icon-spearance.gif new file mode 100644 index 0000000000000000000000000000000000000000..1ab1eabbd2c35e7f0ea664993953492f5f042fd0 GIT binary patch literal 166 zcmZ?wbhEHb6krfw*v!Ci_Uu^$1A`??mT%=J ztOFuJW-zb>Uzp;#+VsVXv*rgQ)iW3hYCKM{E*20`Um>^d7!z yl;}QL_?(5MKeE%B)RuTN-Qp*7GYdSOWk;<2Q!@ literal 0 HcmV?d00001 diff --git a/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/typograf.gif b/assets/components/tinymce/jscripts/tiny_mce/plugins/typograf/img/typograf.gif new file mode 100644 index 0000000000000000000000000000000000000000..ee55a41049c29cee044e5d25c71b05d0f9352241 GIT binary patch literal 143 zcmZ?wbhEHb6k!ly*vtR||NsAg`0)PW!w0u)+2rl*t*fic&(9AO1WTe5ia%Kx85lSi zbU+dyGZ~47$rYfh#DRN0ItKDTzXbU>WB.*?)%si', trim($xml->text), -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); + + for ($i = 0, $m = count($text); $i < $m; $i++) { + + if (mb_substr(mb_strtolower($text[$i]), 0, 5) == "type == "spearance") { + + $params = array(); + $params[] = ""; + $params[] = ""; + $params[] = " 1"; // Теги + $params[] = " "; // Абзацы + $params[] = " ]]>"; + $params[] = " ]]>"; + $params[] = " "; + $params[] = " ]]>"; // Переводы строк + $params[] = " "; // Переводы строк

 

+ $params[] = " "; // DOS текст + $params[] = " "; // Неразрывные конструкции + $params[] = " ]]>"; + $params[] = " ]]>"; + $params[] = " "; + $params[] = " "; // Висячая пунктуация + $params[] = " "; // Удалять висячие слова + $params[] = " "; // Символ минус + $params[] = " "; // Переносы + $params[] = " "; // Акронимы + $params[] = " "; // Вывод символов 0 - буквами 1 - числами + $params[] = " "; // Параметры ссылок + $params[] = ""; + $params = implode("", $params); + + function post($host, $script, $data) { + + $fp = fsockopen($host,80,$errno, $errstr, 30 ); + + if ($fp) { + + fputs($fp, "POST $script HTTP/1.1\n"); + fputs($fp, "Host: $host\n"); + fputs($fp, "Content-type: application/x-www-form-urlencoded\n"); + fputs($fp, "Content-length: " . strlen($data) . "\n"); + fputs($fp, "User-Agent: PHP Script\n"); + fputs($fp, "Connection: close\n\n"); + fputs($fp, $data); + while(fgets($fp,2048) != "\r\n" && !feof($fp)); + unset($buf); + while(!feof($fp)) $buf .= fread($fp,2048); + fclose($fp); + + } else { + + return "Server not responding"; + + } + + return $buf; + + } + + $result = post("typograf.ru", "/webservice/", "chr=utf-8&text=" . urlencode($text) . '&xml=' . urlencode($params)); + + } elseif ($xml->type == "jare") { + + set_include_path(get_include_path() . PATH_SEPARATOR . MCETYPOGRAF_ENGINES); + require("Jare/Typograph.php"); + + $jareTypo = new Jare_Typograph($text); + $jareTypo->getTof("etc")->disableBaseParam("paragraphs")->disableParsing(true); + $result = $jareTypo->parse($jareTypo->getBaseTofsNames()); + + } else { + + // 1 — mixedEntities — буквенными и числовыми кодами (для универсального кода. Совместимо со всеми основыми новыми и старыми браузерами) + // 2 — xmlEntities — только буквенными кодами (хорошо для XML, плохо для старых браузеров) + // 3 — htmlEntities — только числовыми кодами (кому-то нужно. Плохо для старых браузеров) + // 4 — noEntities — готовыми символами (символы выдаются в том виде, в каком их видит в результате читатель) + + require(MCETYPOGRAF_ENGINES . "/remotetypograf.php"); + + $remoteTypograf = new RemoteTypograf ("UTF-8"); + $remoteTypograf->htmlEntities(); + $remoteTypograf->br(false); + $remoteTypograf->p(false); + $remoteTypograf->nobr(3); + + $result = $remoteTypograf->processText($text); + + } + + // ----------------------------------------------------------------------------------------------------------------------------------------------------------------// + // Reverting non-typographic areas // + // ----------------------------------------------------------------------------------------------------------------------------------------------------------------// + + print str_replace($patterns, $replaces, $result); + +?> \ No newline at end of file