Replace emoticons found in the text with their images

@param string $text to modify
@return string the modified result
489947
protected function replace_emoticons($text) {
        global $CFG, $OUTPUT, $PAGE;

        $lang = current_language();
        $theme = $PAGE->theme->name;

        if (!isset(self::$emoticontexts[$lang][$theme]) or !isset(self::$emoticonimgs[$lang][$theme])) {
            // prepare internal caches
            $manager = get_emoticon_manager();
            $emoticons = $manager->get_emoticons();
            self::$emoticontexts[$lang][$theme] = array();
            self::$emoticonimgs[$lang][$theme] = array();
            foreach ($emoticons as $emoticon) {
                self::$emoticontexts[$lang][$theme][] = $emoticon->text;
                self::$emoticonimgs[$lang][$theme][] = $OUTPUT->render($manager->prepare_renderable_emoticon($emoticon));
            }
            unset($emoticons);
        }

        if (empty(self::$emoticontexts[$lang][$theme])) { // No emoticons defined, nothing to process here.
            return $text;
        }

        // Detect all zones that we should not handle (including the nested tags).
        $processing = preg_split('/(<\/?(?:span|script)[^>]*>)/is', $text, 0, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);

        // Initialize the results.
        $resulthtml = "";
        $exclude = 0;

        // Define the patterns that mark the start of the forbidden zones.
        $excludepattern = array('/^<script/is', '/^<span[^>]+class="nolink[^"]*"/is');

        // Loop through the fragments.
        foreach ($processing as $fragment) {
            // If we are not ignoring, we MUST test if we should.
            if ($exclude == 0) {
                foreach ($excludepattern as $exp) {
                    if (preg_match($exp, $fragment)) {
                        $exclude = $exclude + 1;
                        break;
                    }
                }
            }
            if ($exclude > 0) {
                // If we are ignoring the fragment, then we must check if we may have reached the end of the zone.
                if (strpos($fragment, '</span') !== false || strpos($fragment, '</script') !== false) {
                    $exclude -= 1;
                    // This is needed because of a double increment at the first element.
                    if ($exclude == 1) {
                        $exclude -= 1;
                    }
                } else if (strpos($fragment, '<span') !== false || strpos($fragment, '<script') !== false) {
                    // If we find a nested tag we increase the exclusion level.
                    $exclude = $exclude + 1;
                }
            } else if (strpos($fragment, '<span') === false ||
                       strpos($fragment, '</span') === false) {
                // This is the meat of the code - this is run every time.
                // This code only runs for fragments that are not ignored (including the tags themselves).
                $fragment = str_replace(self::$emoticontexts[$lang][$theme], self::$emoticonimgs[$lang][$theme], $fragment);
            }
            $resulthtml .= $fragment;
        }

        return $resulthtml;
    }
98619
public function setText( $text ) {
    $this->textOriginal = $text;
    $this->text = preg_replace("/([^\w ]*)/iu", "", $text);
    return $this;
  }
1089580
public function replace($text)
    {
        preg_match_all($this->pattern, $text, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
        $delta = 0;
        foreach ($matches as $match)
        {
            $stringsOnly = array();
            foreach ($match as $info)
            {
                $stringsOnly []= $info[0];
            }
            $replace = call_user_func($this->callback, $stringsOnly);
            if (false === $replace || null === $replace)
            {
                continue;
            }

            $text = substr_replace($text, $replace, $match[0][1] + $delta, strlen($match[0][0]));
            $delta += strlen($replace) - strlen($match[0][0]);
        }

        return $text;
    }
1160399
public function replaceEmojiWithImages($string, $imageHtmlTemplate = null)
    {
        // NB: Named emoji should be replaced first as the string will then contain them in the image alt tags

        // Replace named emoji, e.g. ":smile:"
        $string = preg_replace_callback($this->getIndex()->getEmojiNameRegex(), function ($matches) use ($imageHtmlTemplate) {
            return $this->getEmojiImageByName($matches[1], $imageHtmlTemplate);
        }, $string);

        // Replace unicode emoji
        $string = preg_replace_callback($this->getIndex()->getEmojiUnicodeRegex(), function ($matches) use ($imageHtmlTemplate) {
            return $this->getEmojiImageByUnicode($matches[0], $imageHtmlTemplate);
        }, $string);

        return $string;
    }
455952
public function shortCode($text)
    {
        $patterns = [
            '/\[(FIGURE)[\s+](.+)\]/',
            '/\[(BASEURL)\]/',
            '/\[(RELURL)\]/',
            '/\[(ASSET)\]/',
        ];

        return preg_replace_callback(
            $patterns,
            function ($matches) {
                switch ($matches[1]) {

                    case 'FIGURE':
                        return CTextFilter::shortCodeFigure($matches[2]);
                        break;

                    case 'BASEURL':
                        return CTextFilter::shortCodeBaseurl();
                        break;

                    case 'RELURL':
                        return CTextFilter::shortCodeRelurl();
                        break;

                    case 'ASSET':
                        return CTextFilter::shortCodeAsset();
                        break;

                    default:
                        return "{$matches[1]} is unknown shortcode.";
                }
            },
            $text
        );
    }
1052897
public static function sanitizeText($text)
    {
        if (!$text) {
            return null;
        }

        $allowedTagNames = [ "b", "strong", "i", "em", "br" ];

        $marker = "\&8slkc7\\";

        // Create a one-to-one conversion array for easy replacing
        $allowedTagConversion = [];
        foreach($allowedTagNames as $allowedTagName) {
            $allowedTagConversion["<{$allowedTagName}>"] = "{$marker}{$allowedTagName}{$marker}";
            $allowedTagConversion["<{$allowedTagName}/>"] = "{$marker}{$allowedTagName}/{$marker}";
            $allowedTagConversion["<{$allowedTagName} />"] = "{$marker}{$allowedTagName} /{$marker}";
            $allowedTagConversion["</{$allowedTagName}>"] = "{$marker}/{$allowedTagName}{$marker}";
        }

        // Convert to BB-like tags before sanitizing and then revert
        $text = str_ireplace(array_keys($allowedTagConversion), array_values($allowedTagConversion), $text);

        $text = self::sanitizeString($text);

        if (!$text) {
            return null;
        }

        return str_ireplace(array_values($allowedTagConversion), array_keys($allowedTagConversion), $text);
    }
1047292
public function styleText($text)
    {
        if ($this->_outputAs == static::RAW) {
            return $text;
        }
        if ($this->_outputAs == static::PLAIN) {
            $tags = implode('|', array_keys(static::$_styles));

            return preg_replace('#</?(?:' . $tags . ')>#', '', $text);
        }

        return preg_replace_callback(
            '/<(?P<tag>[a-z0-9-_]+)>(?P<text>.*?)<\/(\1)>/ims',
            [$this, '_replaceTags'],
            $text
        );
    }
524068
protected function _replaceTags(&$text)
    {
        if (!empty($this->_stripped_tags)) {
            $text = str_replace($this->_stripped_tags[0], $this->_stripped_tags[1], $text);
        }
    }
558722
protected function replace($text, $replacements)
    {
        if (is_array($replacements)) {
            foreach ($replacements as $var => $replacement) {
                $regex = str_replace('key', preg_quote($var, '/'), $this->translateReplaceRegex);
                $text = preg_replace($regex, $replacement, $text);
            }
        }
        return $text;
    }
431267
public static function store($text)
    {
        foreach (Config::get('smiley.codes') as $key => $value) {
            $text = str_replace($key, $value, $text);
        }

        return $text;
    }
1276882
public static function cleanText(&$text)
    {
        $text = preg_replace("'<script[^>]*>.*?</script>'si", '', $text);
        $text = preg_replace('/<a\s+.*?href="([^"]+)"[^>]*>([^<]+)<\/a>/is', '\2 (\1)', $text);
        $text = preg_replace('/<!--.+?-->/', '', $text);
        $text = preg_replace('/{.+?}/', '', $text);
        $text = preg_replace('/&nbsp;/', ' ', $text);
        $text = preg_replace('/&amp;/', ' ', $text);
        $text = preg_replace('/&quot;/', ' ', $text);
        $text = strip_tags($text);
        $text = htmlspecialchars($text, ENT_COMPAT, 'UTF-8');

        return $text;
    }
975550
public function say($text)
    {
        $message = $this->getSpeechBubble($text);
        
        return str_replace(
          '{{bubble}}',
          $message,
          $this->character
        );
    }
957508
private function _convertTagsToEscapeSequences ( $text ) {
        list($patterns, $replacements) = $this->_getConvertingDictionary();
        $convertedText = preg_replace($patterns, $replacements, $text);
        return $convertedText;
    }
41409
public static function underscore($text) {
        $pregRule = '#[A-Z]+#';
        $text = preg_replace_callback($pregRule, function($match) { return "_" . strtolower($match[0]); }, $text);

        return self::slugify($text, '_');
    }
536570
private static function placeholder($text)
    {
        $image_manager = new ImageManager(['driver' => 'imagick']);

        $image = $image_manager->canvas(640, 480, '#efefef');

        $image->text($text, 320, 240 - (70 * substr_count($text, "\n")), function ($font) {
            $font->file(base_path('vendor/webfontkit/open-sans/fonts/opensans-regular.woff'));
            $font->size(60);
            $font->color('#cbcbcb');
            $font->align('center');
            $font->valign('center');
        });

        $image_data = (string) $image->encode('gif');

        return 'data:image/gif;base64,'.base64_encode($image_data);
    }
717050
public function replaceMacros($text)
    {
        $result = str_replace(
            array(
                '$(httpHost)',
                '$(httpPath)',
                '$(httpRoot)',
                '$(styleRoot)',
                '$(dataRoot)',

                '$(siteName)',
                '$(siteTitle)',
                '$(siteKeywords)',
                '$(siteDescription)',
            ),
            array(
                httpHost,
                httpPath,
                Eresus_CMS::getLegacyKernel()->root,
                styleRoot,
                dataRoot,

                siteName,
                siteTitle,
                siteKeywords,
                siteDescription,
            ),
            $text
        );
        $result = preg_replace_callback('/\$\(const:(.*?)\)/i', '__macroConst', $result);
        $result = preg_replace_callback('/\$\(var:(([\w]*)(\[.*?\]){0,1})\)/i', '__macroVar', $result);
        $result = preg_replace('/\$\(\w+(:.*?)*?\)/', '', $result);
        return $result;
    }
413618
protected function _stripTags(&$text)
    {
        $regexp = '@<(\w+)\b.*?>.*?</\1>@si';
        $matches = array();
        $replacements = array();

        if (preg_match_all($regexp, $text, $matches)) {
            $matches = $matches[0];

            foreach ($matches as $i => $tag) {
                $replacements[] = $i.'-'.md5($tag);
            }

            $text = str_replace($matches, $replacements, $text);
        }

        $this->_stripped_tags = array($replacements, $matches);
    }