Текстовое поле
$size - размерность поля или true для longtext
187789
public function addText($col, $size = false)
  {
    $opts = array('null' => true);
    if ($size) {
      $opts['limit'] = $size === true ? static::LONGTEXT : $size;
    }

    return $this->add($col, static::COL_TEXT, $opts);
  }
873482
function asCanonicalArray() {
		/** @var string $_this */
		$_this = spl_object_hash($this);
		if (!isset(self::$_canonicalArray[$_this])) {
			/**
			 * @uses \Magento\Framework\Simplexml\Element::asCanonicalArray()
			 * может возвращать строку в случае,
			 * когда структура исходных данных не соответствует массиву.
			 */
			self::$_canonicalArray[$_this] = df_result_array(parent::asCanonicalArray());
		}
		return self::$_canonicalArray[$_this];
	}
1102686
function getsize($size)
    {
        $last = strtolower($size{strlen($size) - 1});
        switch ($last) {
            case 'g':
                $size *= 1024;
            case 'm':
                $size *= 1024;
            case 'k':
                $size *= 1024;
        }

        return $size;
    }
814176
public function getHTML()
    {
        $this->parse();
        $xml = clone $this->xml;

        /* Удаляем расширенные теги */
        $tags = $xml->getElementsByTagNameNS(self::NS, '*');
        while ($tags->length > 0)
        {
            $node = $tags->item(0);
            $node->parentNode->removeChild($node);
        }

        // Есть ли поля для выбора файлов?
        $hasFileInputs = false;

        /*
         * Удаляем расширенные атрибуты
         * Ищем input[type=file]
         */
        $tags = $xml->getElementsByTagName('*');
        for ($i = 0; $i < $tags->length; $i++)
        {
            $node = $tags->item($i);

            $isElement = $node->nodeType == XML_ELEMENT_NODE;
            /** @var DOMElement $node */
            $hasAttributes = $isElement && $node->hasAttributes();

            if ($isElement && $hasAttributes)
            {
                /** @var DOMNamedNodeMap $attrs */
                $attrs = $node->attributes;
                for ($j = 0; $j < $attrs->length; $j++)
                {
                    /** @var DOMAttr $attr */
                    $attr = $attrs->item($j);
                    if ($attr->namespaceURI == self::NS)
                    {
                        $attr->ownerElement->removeAttributeNode($attr);
                        $j--;
                    }
                }

                if ($node->tagName == 'input' && $node->getAttribute('type') == 'file')
                {
                    $hasFileInputs = true;
                }
            }
        }

        if ($hasFileInputs)
        {
            /** @var DOMElement $element */
            $element = $xml->firstChild->nextSibling;
            $element->setAttribute('enctype', 'multipart/form-data');
        }

        // Предотвращаем схлопывание пустых textarea
        $tags = $xml->getElementsByTagName('textarea');
        for ($i = 0; $i < $tags->length; $i++)
        {
            $node = $tags->item($i);
            $cdata = $xml->createCDATASection('');
            $node->appendChild($cdata);
        }

        $xml->formatOutput = true;
        $html = $xml->saveXML($xml->firstChild->nextSibling);
        // Удаляем атрибуты пространств имён
        $html = preg_replace('/\s*xmlns:\w+=("|\').*?("|\')/', '', $html);
        // Удаляем пустые <![CDATA[]]>
        $html = str_replace('<![CDATA[]]>', '', $html);

        return $html;
    }
311856
public function getHTML()
    {
        // Открывающий тег
        $html = '<' . $this->tagName;

        /* Добавляем атрибуты */
        foreach ($this->attrs as $name => $value)
        {
            $html .= ' ' . $name;

            if ($value !== true)
            {
                $html .= '="' . $value . '"';
            }
        }

        $html .= '>';

        /* Если есть содержимое, то добавляем его и закрывающий тег */
        if ($this->contents !== null)
        {
            $html .= $this->contents . '</' . $this->tagName . '>';
        }

        return $html;
    }
1351910
function onFormInitialized() {
		parent::onFormInitialized();
		$this->addClass('df-font'); // 2016-07-30 This CSS class will be applied to the <fieldset> DOM node.
		$this->checkbox(O::enabled, 'Setup?');
		$row1 = $this->fieldsetInline('df-checkboxes')->hide(); /** @var FInline $row1 */
		$row1->checkbox(O::bold, 'B', ['title' => 'Bold']);
		$row1->checkbox(O::italic, 'I', ['title' => 'Italic']);
		$row1->checkbox(O::underline, 'U', ['title' => 'Underline']);
		$row1->color(O::color, null, ['title' => 'Font Color']);
		$row2 = $this->fieldsetInline('df-family')->hide(); /** @var FInline $row2 */
		$row2->field(O::family, GoogleFont::class, null, ['title' => 'Font Family']);
		/** @var array(array(string => string)) $sizeValues */
		$sizeValues = [Q::P__VALUES => SizeUnit::s()->toOptionArray()];
		$row2->quantity(O::size, null, $sizeValues + ['title' => 'Font Size']);
		$row3 = $this->fieldsetInline('row3')->hide(); /** @var FInline $row3 */
		// 2015-12-13
		// Намеренно указываем в качестве подписи пустую строку, а не null,
		// чтобы получить пустые теги <label><span></span></label>
		// и потом стилизовать их своей иконкой.
		$row3->quantity(O::letter_spacing, '', $sizeValues + ['title' => 'Letter Spacing']);
		/**
		 * 2015-12-13
		 * Передаём в качестве подписи название класса Font Awesome.
		 * Такое стало возможным благодаря моему плагину
		 * @used-by \Df\Framework\Plugin\Data\Form\Element\AbstractElement::aroundGetLabelHtml()
		 * https://github.com/mage2pro/core/tree/73bed4fbb751ab47ad1bb70a8d90f455da26b500/Framework/Data/Form/Element/AbstractElementPlugin.php#L53
		 */
		/**
		 * 2015-12-13
		 *	.test {
		 *		transform : scale(1,1.5);
		 *		-webkit-transform:scale(1,1.5); // Safari and Chrome
		 *		-moz-transform:scale(1,1.5); // Firefox
		 *		-ms-transform:scale(1,1.5); // IE 9+
		 *		-o-transform:scale(1,1.5); // Opera
		 *		letter-spacing: 10px;
		 *	}
		 * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#scale()
		 * http://stackoverflow.com/a/16447826
		 */
		$row3->percent(O::scale_horizontal, 'fa-text-width', 100, ['title' => 'Horizontal Scale']);
		$row3->percent(O::scale_vertical, 'fa-text-height', 100, ['title' => 'Vertical Scale']);
		/**
		 * 2015-12-13
		 * Намеренно указываем в качестве подписи пустую строку, а не null,
		 * чтобы получить пустые теги <label><span></span></label>
		 * и потом стилизовать их своей иконкой.
		 */
		df_hide($this->select(O::letter_case, '', LetterCase::s(), ['title' => 'Letter Case']));
		df_fe_init($this, __CLASS__, df_fa());
	}
1049012
public static function check()
    {
        // Проверим значение установленной текущей локализации, если оно не входит в список доступных локализаций
        // установим локализацию по умолчанию
        if (!in_array(strtolower(self::$current_locale), self::$locales)) self::$current_locale = self::DEF;
    }
151727
static function string($value, &$error, $args)
    {
        if (isset($value) && is_scalar($value)){
            return strval($value);
        }
        $error = new Error('Должно быть строкой', 'string');
        return '';
    }
385873
function ezText( $text, $size = 0, $options = array(), $test = 0 )
    {
        // this will add a string of text to the document, starting at the current drawing
        // position.
        // it will wrap to keep within the margins, including optional offsets from the left
        // and the right, if $size is not specified, then it will be the last one used, or
        // the default value (12 I think).
        // the text will go to the start of the next line when a return code "\n" is found.
        // possible options are:
        // 'left'=> number, gap to leave from the left margin
        // 'right'=> number, gap to leave from the right margin
        // 'aleft'=> number, absolute left position (overrides 'left')
        // 'aright'=> number, absolute right position (overrides 'right')
        // 'justification' => 'left','right','center','centre','full'
        // 'top_margin' => set top margin manualy

        // only set one of the next two items (leading overrides spacing)
        // 'leading' => number, defines the total height taken by the line, independent of the font height.
        // 'spacing' => a real number, though usually set to one of 1, 1.5, 2 (line spacing as used in word processing)

        // if $test is set then this should just check if the text is going to flow onto a new page or not, returning true or false

        // apply the filtering which will make the underlining function.
        if ( strlen( $text ) == 0 )
            return $this->y;

        $text = $this->ezProcessText( $text );

        $newPage = false;
        $store_y = $this->y;
        $left = $angle = $adjust = 0;

        if ( is_array( $options ) && isset( $options['aright'] ) )
        {
            $right = $options['aright'];
        }
        else
        {
            $right = $this->ez['pageWidth'] - $this->rightMargin() - ( ( is_array( $options ) && isset( $options['right'] ) ) ? $options['right'] : 0 );
        }
        if ( $size <= 0 )
        {
            $size = $this->ez['fontSize'];
        }
        else
        {
            $this->ez['fontSize'] = $size;
        }

        if ( is_array( $options ) && isset( $options['top_margin'] ) )
        {
            $this->y = $this->ez['pageHeight'] - $options['top_margin'];
        }

        if ( is_array( $options ) && isset( $options['justification'] ) )
        {
            $just = $options['justification'];
        }
        else
        {
            $just = $this->ez['justification'];
        }

        // modifications to give leading and spacing based on those given by Craig Heydenburg 1/1/02
        if ( is_array( $options ) && isset( $options['leading'] ) )
        { // use leading instead of spacing
            $height = $options['leading'];
        }
        else if ( is_array( $options ) && isset( $options['spacing'] ) )
        {
            $height = $this->getFontHeight( $size ) * $options['spacing'];
        }
        else
        {
            $height = $this->getFontHeight( $size );
        }

        $lastOnlyDirective = false;
        $lines = explode( "\n", $text );
        if ( $text == "\n" )
        {
            $lines = array( "" );
        }
        foreach ( array_keys( $lines ) as $key )
        {
            $line = $lines[$key];
            if ( ( $key > 0 || strlen( $line ) == 0 ) &&
                 !$lastOnlyDirective )
            {
                $this->y = $this->y - $height;
                $this->ez['xOffset'] = 0;
            }
            $lastOnlyDirective = false;
            while ( strlen( $line ) )
            {
                $noClose = 1;
                while ( $noClose )
                {
                    $f = 1;
                    $directiveArray = $this->PRVTcheckTextDirective( $line, 0, $f );
                    $noClose = $directiveArray['noClose'];
                    if ( $noClose )
                    {
                        if ( $this->ez['xOffset'] != 0 )
                        {
                            $left = $this->ez['xOffset'];
                        }
                        else
                        {
                            $left = $this->leftMargin() + ( (is_array( $options ) && isset( $options['left'] ) ) ? $options['left'] : 0 );
                        }

                        $textInfo = $this->addText( $left, $this->y, $size, substr( $line, 0, $directiveArray['directive'] ), $angle, $adjust );
                        $line = substr( $line, $directiveArray['directive'] );
                        if ( isset( $textInfo['width'] ) && $textInfo['width'] != 0 )
                        {
                            $this->setXOffset( $left + $textInfo['width'] );
                        }
                    }
                }

                if ( $this->y < $this->ez['bottomMargin'] )
                {
                    if ( $test )
                    {
                        $newPage = true;
                    }
                    else if ( strlen( trim( $line ) ) )
                    {
                        $this->ezNewPage();
                        // and then re-calc the left and right, in case they have changed due to columns
                    }
                }
                if ( $this->ez['xOffset'] != 0 )
                {
                    $left = $this->ez['xOffset'];
                }
                else
                {
                    $left = $this->leftMargin() + ( ( is_array( $options ) && isset( $options['left'] ) ) ? $options['left'] : 0 );
                }

                if ( is_array( $options ) && isset( $options['aleft'] ) )
                {
                    $left=$options['aleft'];
                }
                if ( is_array( $options ) && isset( $options['aright'] ) )
                {
                    $right = $options['aright'];
                }
                else
                {
                    $right = $this->ez['pageWidth'] - $this->rightMargin() - ( ( is_array( $options ) && isset( $options['right'] ) ) ? $options['right'] : 0 );
                }

                $textInfo = $this->addTextWrap( $left, $this->y, $right - $left, $size, $line, $just, 0, $test );
                if ( isset( $textInfo['only_directive'] ) &&
                     $textInfo['only_directive'] === true )
                {
                    $lastOnlyDirective = true;
                    $line = '';
                    continue;
                }
                $line = $textInfo['text'];
                if ( strlen( $line ) || $textInfo['width'] == 0 )
                {
                    $this->y = $this->y - $height;
                    $this->ez['xOffset'] = 0;
                }
                else if ( $textInfo['width'] != 0 )
                {
                    $this->setXOffset( $left + $textInfo['width'] );
                }
            }
        }

        if ( $test )
        {
            $this->y = $store_y;
            return $newPage;
        }
        else
        {
            return $this->y;
        }
    }
1317518
function module_ex($module_name, $attrs)
	{
		$class_name = $this->class_name();
		$class_name = preg_replace('/_(main|edit|view)$/', '', $class_name);
		$module_class = \blib_grammar::plural($class_name).'_modules_'.$module_name;
		set_def($attrs, 'model', $this);
		$mod = bors_load_ex($module_class, $this, $attrs);
		if(!$mod)
			bors_throw(ec("Не могу загрузить модуль '$module_class'"));

		return $mod;
	}
275679
static function parse($text, $vars=[], $tpl_left = '{', $tpl_right = '}', $filter = FILTER_SANITIZE_SPECIAL_CHARS)
    {
        if ($filter) $vars = filter_var_array($vars, $filter);
        // По циклу проходимся по всем переменным заменяя значения в {} на значения в массиве
        if (is_array($vars)){
            foreach ($vars as $key => $value){
                if (is_scalar($value)) $text = str_replace($tpl_left.$key.$tpl_right, $value, $text);
            }
        }
        return $text;
    }
1053282
public function summary($size = null, $textOnly = false)
    {
        $config = (array)Grav::instance()['config']->get('site.summary');
        if (isset($this->header->summary)) {
            $config = array_merge($config, $this->header->summary);
        }

        // Return summary based on settings in site config file
        if (!$config['enabled']) {
            return $this->content();
        }

        // Set up variables to process summary from page or from custom summary
        if ($this->summary === null) {
            $content = $textOnly ? strip_tags($this->content()) : $this->content();
            $summary_size = $this->summary_size;
        } else {
            $content = strip_tags($this->summary);
            // Use mb_strwidth to deal with the 2 character widths characters
            $summary_size = mb_strwidth($content, 'utf-8');
        }

        // Return calculated summary based on summary divider's position
        $format = $config['format'];
        // Return entire page content on wrong/ unknown format
        if (!in_array($format, ['short', 'long'])) {
            return $content;
        }
        if (($format === 'short') && isset($summary_size)) {
            // Use mb_strimwidth to slice the string
            if (mb_strwidth($content, 'utf8') > $summary_size) {
                return mb_substr($content, 0, $summary_size);
            }

            return $content;
        }

        // Get summary size from site config's file
        if ($size === null) {
            $size = $config['size'];
        }

        // If the size is zero, return the entire page content
        if ($size === 0) {
            return $content;
            // Return calculated summary based on defaults
        }
        if (!is_numeric($size) || ($size < 0)) {
            $size = 300;
        }

        // Only return string but not html, wrap whatever html tag you want when using
        if ($textOnly) {
            if (mb_strwidth($content, 'utf-8') <= $size) {
                return $content;
            }

            return mb_strimwidth($content, 0, $size, '...', 'utf-8');
        }

        $summary = Utils::truncateHtml($content, $size);

        return html_entity_decode($summary);
    }
410332
protected function parseExtended()
	{

		$this->addFormMessagesNode();

		$this->xml->firstChild->nextSibling->setAttribute('method', 'post');

		$this->processBranch($this->xml->firstChild->nextSibling);

		/*
		 * Обработка тегов:
		 * 1. Удаление расширенных атрибутов
		 * 2. Предотвращение схлопывания пустых тегов
		 */
		$tags = $this->xml->getElementsByTagName('*');
		$collapsable = array('br', 'hr', 'input');

		for ($i = 0; $i < $tags->length; $i++)
		{
			$node = $tags->item($i);

			$isElement = $node->nodeType == XML_ELEMENT_NODE;

			if ($isElement)
			{
				$hasAttributes = $isElement && $node->hasAttributes();
				if ($hasAttributes)
				{
					$attrs = $node->attributes;
					for ($j = 0; $j < $attrs->length; $j++)
					{
						/* @var DOMAttr $attr */
						$attr = $attrs->item($j);
						if ($attr->namespaceURI == self::NS)
						{
							$this->extendedAttr($node, $attr);
							/*
							 * в extendedAttr текущий атрибут удаляется, поэтому следующим шагом рассматривается
							 * элемент с тем же индексом
							 */
							$j--;
						}
					}
				}

				if ($node->textContent === '' && !in_array($node->nodeName, $collapsable))
				{
					$cdata = $this->xml->createCDATASection('');
					$node->appendChild($cdata);
				}
			}
		}

		$id = $this->xml->firstChild->nextSibling->getAttribute('id');
		// инициализация объекта формы
		$scriptContents = "\n\$(document).ready(function () {window.$id = new EresusForm('$id');\n";

		/*
		 * Если в сессии установлен флаг isInvalid, вызываем перепроверку формы
		 */
		if ($this->mode == self::INPUT && $this->isInvalid)
		{
			$this->js []= 'validate(true);';
		}

		// необходимо для отображения сообщений об ошибках, найденных на сервере
		$this->js []= 'showFormMessages();';
		if ($this->js)
		{
			foreach ($this->js as $command)
			{
				$scriptContents .= "$id.$command\n";
			}
		}
		$scriptContents .= "});";
		$script = $this->xml->createElement('script', $scriptContents);
		$script->setAttribute('type', 'text/javascript');
		$this->xml->firstChild->nextSibling->appendChild($script);

		$this->xml->formatOutput = true;
		$html = $this->xml->saveXML($this->xml->firstChild->nextSibling); # This exclude xml declaration
		$html = preg_replace('/\s*xmlns:\w+=("|\').*?("|\')/', '', $html); # Remove ns attrs
		/*$html = preg_replace('/<\?.*\?>/', '', $html);*/
		$html = str_replace('<![CDATA[]]>', '', $html); # Remove empty <![CDATA[]]> sections

		return $html;
	}
664421
function sectionIndex()
    {
        /** @var TAdminUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $root = Eresus_CMS::getLegacyKernel()->root.'admin.php?mod=pages&amp;';
        $this->cache['index_controls'] =
            $page->control('setup', $root.'id=%d') . ' ' .
            $page->control('position',
                array($root.'action=up&amp;id=%d',$root.'action=down&amp;id=%d')) . ' ' .
            $page->control('add', $root.'action=create&amp;owner=%d') . ' ' .
            $page->control('move', $root.'action=move&amp;id=%d') . ' ' .
            $page->control('delete', $root.'action=delete&amp;id=%d');
        $types = $this->loadContentTypes();
        for ($i=0; $i<count($types[0]); $i++)
        {
            $this->cache['content_types'][$types[1][$i]] = $types[0][$i];
        }
        $table = new AdminList;
        $table->setHead(array('text'=>'Раздел', 'align'=>'left'), 'Имя', 'Тип', 'Доступ', '');
        $table->addRow(array(admPagesRoot, '', '', '',
            array($page->control('add', $root.'action=create&amp;owner=0'), 'align' => 'center')));
        $table->addRows($this->sectionIndexBranch(0, 1));
        $result = $table->render();
        return $result;
    }
680914
static function size($filename, $returnFormatted = false) {
        if ($returnFormatted && self::isReadable($filename)) {
            return Number::readableSize((double)filesize($filename));
        }

        return file_exists($filename) ? filesize($filename) : 0;
    }
876645
private function actionAddDialog()
    {
        $form = array(
            'name' => 'add',
            'caption' => 'Добавление формы',
            'width' => '100%',
            'fields' => array(
                array('type' => 'hidden', 'name' => 'action', 'value' => 'create'),
                array('type' => 'edit', 'name' => 'title', 'label' => 'Описание',
                    'width' => '99%', 'value' => arg('title')),
                array('type' => 'edit', 'name' => 'name', 'label' => 'Имя',
                    'width' => '16em', 'value' => arg('name'), 'comment' =>
                'только латинские буквы, цифры, символы минус и подчёркивание',
                    'pattern' => '/^[\w\-]+$/i',
                    'errormsg' =>
                    'Имя формы может содержать только латинские буквы, цифры, символы минус и подчёркивание'),
                array('type' => 'text',
                    'value' =>
                    '&raquo; <b><a href="https://github.com/Eresus/EForms/wiki/%D0%AF%D0%B7%D1%8B%D0%BA-%D1%84%D0%BE%D1%80%D0%BC">' .
                    'Синтаксис форм</a></b>'),
                array('type' => 'memo', 'name' => 'code', 'height' => '30', 'syntax' => 'html',
                    'value' => arg('code') ? arg('code') :
                        '<form xmlns:ef="http://procreat.ru/eresus2/ext/eforms" method="post">' . "\n</form>"),
            ),
            'buttons' => array('ok', 'cancel'),
        );
        /** @var TAdminUI $page */
        $page = Eresus_Kernel::app()->getPage();
        return $page->renderForm($form);
    }
587030
public function parse()
	{
		$matches = array();

		// строка вида {env._SERVER.LC_NAME}
		if (preg_match_all('/\{env\.([\w\.]+)\}/im', $this->record->formatted, $macrosList) > 0)
		{
			foreach ($macrosList[1] as $match)
			{
				$parts = explode(".", $match);
				$array = @$GLOBALS[$parts[0]];
				array_shift($parts);
				$val = $array;

				foreach ($parts as $i => $key)
				{
					if (is_array($val))
						$val = @$val[$key];
					else if (is_object($val))
						$val = $val->{$key};
				}

				if (is_array($val) || is_object($val))
					$val = print_r($val, 1);

				$this->record->formatted = str_replace("{env." . $match . "}", $val, $this->record->formatted);
			}
		}

		return $this->record;
	}