read as text value

@api
@param   \stubbles\input\filter\range\StringLength  $length       optional  allowed length of text
@param   string[]                                   $allowedTags  optional  list of allowed tags
@return  string
505320
public function asText(StringLength $length = null, array $allowedTags = [])
    {
        return $this->handleFilter(
                function() use($length, $allowedTags)
                {
                    $textFilter = new filter\TextFilter();
                    return filter\RangeFilter::wrap(
                            $textFilter->allowTags($allowedTags),
                            $length
                    );
                }
        );
    }
1281028
private static function sanitizeTag($tag, $allowed = null, $resetStack = false)
    {
        static $stack = [];
        if ($resetStack) {
            $ret = $stack;
            $stack = [];
            return $ret;
        }

        $tag = substr($tag, 1, -1); // strip off leading '<' and trailing '>'
        if ($tag[0] == '/') {
            preg_match('/^\w+/', substr($tag, 1), $m);
            $closingTag = strtolower($m[0]);
            $localStack = [];

            if (null !== $allowed
                && (is_array($allowed) && !array_key_exists($closingTag, $allowed))
                || (is_callable($allowed) && !call_user_func($allowed, $closingTag))
            ) {
                return '<!-- ' . htmlspecialchars($tag) . ' -->';
            }

            do {
                if (!count($stack)) {
                    $stack = array_reverse($localStack);
                    // tag was never opened. Drop closing tag
                    return '';
                }
                $top = array_pop($stack);
                $localStack[] = $top;
            } while (strtolower($top) != $closingTag);
            $ret = '';
            foreach ($localStack as $needClose) {
                $ret .= '</' . $needClose . '>';
            }

            return $ret;
        } else {
            $ret = '';
            $attributes = [];
            preg_match('/^[\w-:]+/', $tag, $m);
            $tagName = strtolower($m[0]);
            if (null !== $allowed
                && (is_array($allowed) && !array_key_exists($tagName, $allowed))
                || (is_callable($allowed) && !call_user_func($allowed, $tagName))
            ) {
                return '<!-- ' . htmlspecialchars($tag) . ' -->';
            }

            $paragraphLevelElements = ['p', 'h6', 'h5', 'h4', 'h3', 'h2', 'h1', 'table', 'ul', 'div'];
            $inlineElements = ['span', 'b', 'i', 'u', 'span', 'strong', 'em', 'a', 'sup', 'sub'];
            $selfClosingElements = ['li', 'td', 'th', 'tr'];
            $forcedParents = ['li' => ['ul', 'ol']];

            if (count($stack) && in_array($tagName, $paragraphLevelElements)) {
                while (in_array(end($stack), array_merge($paragraphLevelElements, $inlineElements))) {
                    $ret .= '</' . array_pop($stack) . '>';
                }
            }
            if (count($stack) && in_array($tagName, $selfClosingElements)) {
                while (in_array(end($stack), $inlineElements)) {
                    $ret .= '</' . array_pop($stack) . '>';
                }
                if (end($stack) === $tagName) {
                    $ret .= '</' . array_pop($stack) . '>';
                }
            }

            if (array_key_exists($tagName, $forcedParents) && !in_array(end($stack), $forcedParents[$tagName])) {
                // if the parent would close paragraph or inline elements, do it now.
                if (count($stack) && in_array($forcedParents[$tagName][0], $paragraphLevelElements)) {
                    while (in_array(end($stack), array_merge($paragraphLevelElements, $inlineElements))) {
                        $ret .= '</' . array_pop($stack) . '>';
                    }
                }
                $ret .= '<' . $forcedParents[$tagName][0] . '>';
                $stack[] = $forcedParents[$tagName][0];
            }

            if (substr($tag, -1) == '/') {
                $isEmpty = true;
            } else {
                $isEmpty = in_array($tagName, ['br', 'img', 'input', 'param', 'isindex', 'area']);
            }
            for ($i = strlen($m[0]); $i < strlen($tag); true) {
                $preI = $i;

                $chunk = substr($tag, $i);

                if (preg_match('/^([\w-]+)\s*=\s*\"([^"]*)\"?/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[2];
                    $i += strlen($m[0]);
                } elseif (preg_match('/^([\w-]+)\s*=\s*\'([^\']*)\'?/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[2];
                    $i += strlen($m[0]);
                } elseif (preg_match('/^([\w-]+)=(\S+)/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[2];
                    $i += strlen($m[0]);
                } elseif (preg_match('/^(\w+)/', $chunk, $m)) {
                    $attributes[$m[1]] = $m[1];
                    $i += strlen($m[0]);
                } else {
                    // drop character
                    $i++;
                }
                assert($i != $preI);
            }

            $ret .= '<';
            $ret .= $tagName;
            if (count($attributes)) {
                foreach ($attributes as $attrName => $value) {
                    $callback = null;
                    if (is_callable($allowed)) {
                        $callback = $allowed;
                    } elseif (is_array($allowed) && isset($allowed[$tagName]) && is_callable($allowed[$tagName])) {
                        $callback = $allowed[$tagName];
                    } elseif (is_array($allowed[$tagName]) && isset($allowed[$tagName][$attrName])) {
                        $callback = $allowed[$tagName][$attrName];
                    }
                    if (null !== $callback) {
                        $value = call_user_func($callback, $tagName, $attrName, $value);
                    }
                    if (false === $value) {
                        continue;
                    }
                    if (!preg_match('/^[a-z_-]/', $attrName)) {
                        // drop malformed attribute name
                        continue;
                    }
                    $ret .= ' ';
                    $ret .= sprintf('%s="%s"', $attrName, str_replace('"', '&quot;', $value));
                }
            }
            if ($isEmpty) {
                $ret .= ' /';
            } else {
                $stack[] = $tagName;
            }
            $ret .= '>';
            return $ret;
        }
    }
717713
public function read($length)
    {
        if ($length < 1) {
            return '';
        }

        $buffer = fread($this->stream, $length);

        if ($buffer === false) {
            throw new RuntimeException('Failed to read ' . $length . ' bytes');
        }

        return $buffer;
    }
246015
public function readBytes($length)
    {
        $read = $this->read($length);
        if (false !== $read) {
            $ret = array_map('ord', str_split($read, 1));

            return $ret;
        }

        return false;
    }
1070114
public function readSequence(array $allowedTokenTypes)
	{
		$tokens = [];

		while($this->valid())
		{
			$token = $this->current();

			if(!$token->isOneOf($allowedTokenTypes))
			{
				break;
			}

			$tokens[] = $token;

			$this->next();
		}

		return $this->createTokenSequence($tokens);
	}
592515
public static function read($source, $length = 0)
    {
        if (!is_file($source) || !is_readable($source)) {
            return false;
        }
        try {
            if ($length <= 0 || $length > filesize($source)) {
                return file_get_contents($source);
            }

            $file = @fopen($source, 'r');
            $content = @fread($file, $length);
            @fclose($file);
            return $content;
        } catch (\Exception $e) {
            return false;
        }
    }
395212
protected function select(string $query, array $parameters = [], string $allowedTags = ""): array
    {
        if (!is_null($this->pager)) {
            $query .= $this->pager->getSqlLimit();
        }
        $statement = $this->query($query, $parameters);
        $statement->setAllowedHtmlTags($allowedTags);
        $results = [];
        while ($row = $statement->next($this->fetchStyle)) {
            $results[] = $row;
        }
        return $results;
    }
222946
public function format($tags, $type)
    {
        $formattedTags = array();
        if ($type === 'user'){
            $formattedTags['tags'] = array();
            foreach($tags as $tag){
                $formattedTags['tags'][$tag['_id']] = array(
                    'mode' => 'readWrite'
                );
            }
        } else if ($type === 'other'){
            foreach($tags as $tag){
                $formattedTags['tags'][] = $tag['_id'];
            }
        } else {
            throw ErrorException("Only 'user' and 'other' are allowed types");
        }

        return $formattedTags;
    }
334009
private function forceRead($length)
    {
        $read = '';

        do {
            $read .= $this->stream->read($length - \strlen($read));
        } while (\strlen($read) < $length && !$this->stream->eof());

        return $read;
    }
943988
static function stringToTags( $tags ) {

		$tags = mb_split( ',', $tags );

		foreach ( $tags as $key => &$val ) {
			$val = strip_tags( $val );
			$val = mb_convert_case( $val, MB_CASE_TITLE, 'UTF-8' );
			$val = mb_split( '\W', $val ); // Split on negated \w
			$val = implode( ' ', $val ); // Put back together with spaces
			$val = trim( $val );
			if ( ! $val ) {
				unset( $tags[ $key ] );
			}
		}

		return $tags;
	}
190962
private function allowed_tags_message($badtag) {
        $a = new stdClass();
        $a->tag = htmlspecialchars($badtag);
        $a->allowed = $this->get_list_of_printable_allowed_tags($this->allowedhtmltags);
        if ($a->allowed) {
            return get_string('tagsnotallowed', 'qtype_gapselect', $a);
        } else {
            return get_string('tagsnotallowedatall', 'qtype_gapselect', $a);
        }
    }
185374
public function purify($html, $allowedTags = null, $allowedAttributes = null)
    {
        $html = (string)preg_replace('@<script.*>.*</script>@isU', '', $html);
        if ($html === '') {
            return '';
        }

        if (strpos($html, '<body>') === false) {
            $html = '<!doctype html><html><body>' . $html . '</body></html>';
        }

        $doc = new \DOMDocument();
        try {
            @$doc->loadHTML($html);
        } catch (\Exception $e) {
            return '';
        }

        $body = $doc->getElementsByTagName('body');
        if ($allowedTags !== null) {
            $tags = ',' . implode(',', $allowedTags) . ',';
        } else {
            $tags = $this->_allowedTags;
        }

        if ($allowedAttributes !== null) {
            $attributes = ',' . implode(',', $allowedAttributes) . ',';
        } else {
            $attributes = $this->_allowedAttributes;
        }

        $this->_purify(iterator_to_array($body->item(0)->childNodes), $tags, $attributes);
        $body = $doc->getElementsByTagName('body');
        return substr($doc->saveHTML($body->item(0)), 6, -7);
    }
572616
public static function stripTags($html, $allowable = [])
    {
        if (!is_array($allowable)) {
            $allowable = preg_split("/, */", $allowable, -1, PREG_SPLIT_NO_EMPTY);
        }

        if ($allowable) {
            return strip_tags($html, '<' . implode('><', $allowable) . '>');
        }

        return strip_tags($html);
    }
16711
protected function readTag(string $data, int $tagLength): string
    {
        $tag  = substr($data, 0, $tagLength);
        $isOk = $tag !== false && strlen($tag) === $tagLength;

        $isOk === true ?: $this->throwException(new CryptException($this->getReadTagErrorMessage()));

        return $tag;
    }
863552
public function allowTags(array $allowedTags):BBCode{
		$this->allowed = [];

		foreach($allowedTags as $tag){
			$tag = strtolower($tag);

			if(in_array($tag, $this->tags, true)){
				$this->allowed[] = $tag;
			}
		}

		return $this;
	}
805690
public static function stripTagsDeep($arr, $allowTags = '') {
		if (is_array($arr)) {
			foreach ($arr as $key => $val) {
				$arr[$key] = stripTagsDeep($val, $allowTags);
			}
		} else {
			$arr = static::stripTags($arr, $allowTags);
		}

		return $arr;
	}
714216
public static function stripTags($text, array $allowed = array())
    {
        // Based on [fernando at zauber dot es]'s solution
        $allowed = array_map('strtolower', $allowed);

        return preg_replace_callback('/<\/?([^>\s]+)[^>]*>/i', function ($matches) use (&$allowed) {
            return in_array(strtolower($matches[1]), $allowed) ? $matches[0] : '';
        }, $text);
    }