Processes text with a link markup

@param string $text text with a link
@param string $link the link gathered from preg_match()
@return string
545643
private function processLink($text, $link) {
        $link = rtrim($link, '.');
        $pipe = explode('|', $text);

        if (mb_strlen($pipe[0]) !== mb_strlen($text)) {
            $pipe = explode('[', $pipe[0]);
            $linkText = $pipe[1];
            $search = '[' . $linkText . '|' . $link . ']';
            $replace = sprintf('<a href="%s">%s</a>', $link, $linkText);
        } else {
            $search = $link;
            $replace = sprintf('<a href="%s">%s</a>', $link, $link);
        }

        $this->writeRaw(str_replace($search, $replace, $text));

        return '';
    }
1033042
function parseLink (text) {
  if (!text) return ''
  var results = []
  var matches = null
  var link1 = /{@link (\S+?)}/g // {@link someSymbol}
  var link2 = /\[(.+?)\]{@link (\S+?)}/g // [caption here]{@link someSymbol}
  var link3 = /{@link ([^\s}]+?)\|(.+?)}/g // {@link someSymbol|caption here}
  var link4 = /{@link ([^\s}\|]+?) (.+?)}/g // {@link someSymbol Caption Here}

  while ((matches = link4.exec(text)) !== null) {
    results.push({
      original: matches[0],
      caption: matches[2],
      url: matches[1]
    })
    text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString())
  }

  while ((matches = link3.exec(text)) !== null) {
    results.push({
      original: matches[0],
      caption: matches[2],
      url: matches[1]
    })
    text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString())
  }

  while ((matches = link2.exec(text)) !== null) {
    results.push({
      original: matches[0],
      caption: matches[1],
      url: matches[2]
    })
    text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString())
  }

  while ((matches = link1.exec(text)) !== null) {
    results.push({
      original: matches[0],
      caption: matches[1],
      url: matches[1]
    })
    text = text.replace(matches[0], Buffer(matches[0].length).fill(' ').toString())
  }
  return results
}
1070845
protected function processBlock($text)
    {
        if (preg_match(self::MATCH_HEADING, $text, $matches)) {
            return $this->addHeading($matches[1], $matches[2]);
        }

        if (strpos($text, self::MATCH_HR) !== false) {
            return $this->addHorizontalRule($text);
        }

        if (mb_substr($text, 0, strlen(self::BLOCKQUOTE_BLOCK_START)) === self::BLOCKQUOTE_BLOCK_START) {
            return $this->processBlockquote($text);
        }

        if (mb_substr($text, 0, strlen(self::BLOCKQUOTE_INLINE_START)) === self::BLOCKQUOTE_INLINE_START) {
            return $this->processBlockquote($text, true);
        }

        // nothing found wrap in paragraph
        return $this->processParagraph($text);
    }
205657
public static function read(string $link = ''): string
    {
        $link = static::normalizePath($link);
        if (static::exists($link)) {
            return @\readlink($link);
        }
        return '';
    }
264056
public function text($doclet)
    {
        $link = parent::text($doclet);
        if (!$link || $link == "\n") {
            $link = $this->_link;
        }

        return $this->_linkText($link, $doclet);
    }
506923
public function url($text)
    {
        return preg_replace_callback($this->pattern['url'], function ($matches) {
            return $this->Html->link($matches[2], $matches[1]);
        }, $text);
    }
1289491
public static function cleanText(string $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);

        return $text;
    }
1150116
public static function ctype_graph($text)
    {
        $text = self::convert_int_to_char_for_ctype($text);

        return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text);
    }
661940
protected function convert_urls_into_links(&$text) {
        //I've added img tags to this list of tags to ignore.
        //See MDL-21168 for more info. A better way to ignore tags whether or not
        //they are escaped partially or completely would be desirable. For example:
        //<a href="blah">
        //&lt;a href="blah"&gt;
        //&lt;a href="blah">
        $filterignoretagsopen  = array('<a\s[^>]+?>', '<span[^>]+?class="nolink"[^>]*?>');
        $filterignoretagsclose = array('</a>', '</span>');
        $ignoretags = [];
        filter_save_ignore_tags($text,$filterignoretagsopen,$filterignoretagsclose,$ignoretags);

        // Check if we support unicode modifiers in regular expressions. Cache it.
        // TODO: this check should be a environment requirement in Moodle 2.0, as far as unicode
        // chars are going to arrive to URLs officially really soon (2010?)
        // Original RFC regex from: http://www.bytemycode.com/snippets/snippet/796/
        // Various ideas from: http://alanstorm.com/url_regex_explained
        // Unicode check, negative assertion and other bits from Moodle.
        static $unicoderegexp;
        if (!isset($unicoderegexp)) {
            $unicoderegexp = @preg_match('/\pL/u', 'a'); // This will fail silently, returning false,
        }

        // TODO MDL-21296 - use of unicode modifiers may cause a timeout
        $urlstart = '(?:http(s)?://|(?<!://)(www\.))';
        $domainsegment = '(?:[\pLl0-9][\pLl0-9-]*[\pLl0-9]|[\pLl0-9])';
        $numericip = '(?:(?:[0-9]{1,3}\.){3}[0-9]{1,3})';
        $port = '(?::\d*)';
        $pathchar = '(?:[\pL0-9\.!$&\'\(\)*+,;=_~:@-]|%[a-f0-9]{2})';
        $path = "(?:/$pathchar*)*";
        $querystring = '(?:\?(?:[\pL0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)';
        $fragment = '(?:\#(?:[\pL0-9\.!$&\'\(\)*+,;=_~:@/?-]|%[a-fA-F0-9]{2})*)';

        // Lookbehind assertions.
        // Is not HTML attribute or CSS URL property. Unfortunately legit text like "url(http://...)" will not be a link.
        $lookbehindend = "(?<![]),.;])";

        $regex = "$urlstart((?:$domainsegment\.)+$domainsegment|$numericip)" .
                "($port?$path$querystring?$fragment?)$lookbehindend";
        if ($unicoderegexp) {
            $regex = '#' . $regex . '#ui';
        } else {
            $regex = '#' . preg_replace(array('\pLl', '\PL'), 'a-z', $regex) . '#i';
        }

        // Locate any HTML tags.
        $matches = preg_split('/(<[^<|>]*>)/i', $text, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

        // Iterate through the tokenized text to handle chunks (html and content).
        foreach ($matches as $idx => $chunk) {
            // Nothing to do. We skip completely any html chunk.
            if (strpos(trim($chunk), '<') === 0) {
                continue;
            }

            // Nothing to do. We skip any content chunk having any of these attributes.
            if (preg_match('#(background=")|(action=")|(style="background)|(href=")|(src=")|(url [(])#', $chunk)) {
                continue;
            }

            // Arrived here, we want to process every word in this chunk.
            $text = $chunk;
            $words = explode(' ', $text);

            foreach ($words as $idx2 => $word) {
                // ReDoS protection. Stop processing if a word is too large.
                if (strlen($word) < 4096) {
                    $words[$idx2] = preg_replace($regex, '<a href="http$1://$2$3$4" class="_blanktarget">$0</a>', $word);
                }
            }
            $text = implode(' ', $words);

            // Copy the result back to the array.
            $matches[$idx] = $text;
        }

        $text = implode('', $matches);

        if (!empty($ignoretags)) {
            $ignoretags = array_reverse($ignoretags); /// Reversed so "progressive" str_replace() will solve some nesting problems.
            $text = str_replace(array_keys($ignoretags),$ignoretags,$text);
        }

        if (get_config('filter_urltolink', 'embedimages')) {
            // now try to inject the images, this code was originally in the mediapluing filter
            // this may be useful only if somebody relies on the fact the links in FORMAT_MOODLE get converted
            // to URLs which in turn change to real images
            $search = '/<a href="([^"]+\.(jpg|png|gif))" class="_blanktarget">([^>]*)<\/a>/is';
            $text = preg_replace_callback($search, 'filter_urltolink_img_callback', $text);
        }
    }
1294792
public function linkPlainTag($text, &$data, &$root)
    {
        $explode = preg_split('/[ \t]+/', $text);
        $link = array_shift($explode);
        if ($link) {
            $this->_link = $link;
            $text = join(' ', $explode);
        } else {
            $this->_link = NULL;
        }
        parent::tag('@linkplain', $text, $root);
    }
875708
public static function routeLink($text, $route, $parameters = [], $link_attributes = [], $extra_link = '')
    {
        $element = self::createElement('a')->text($text)
            ->href(route($route, $parameters).$extra_link);

        foreach ($link_attributes as $method_name => $value) {
            if (method_exists($element, $method_name)) {
                if (!is_array($value)) {
                    $value = [$value];
                }
                $element->$method_name(...$value);
            }
        }

        return $element;
    }
666076
public function makeLinks($text)
    {
        $pattern = '~(?xi)
              (?:
                ((ht|f)tps?://)                    # scheme://
                |                                  #   or
                www\d{0,3}\.                       # "www.", "www1.", "www2." ... "www999."
                |                                  #   or
                www\-                              # "www-"
                |                                  #   or
                [a-z0-9.\-]+\.[a-z]{2,4}(?=/)      # looks like domain name followed by a slash
              )
              (?:                                  # Zero or more:
                [^\s()<>]+                         # Run of non-space, non-()<>
                |                                  #   or
                \(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
              )*
              (?:                                  # End with:
                \(([^\s()<>]+|(\([^\s()<>]+\)))*\) # balanced parens, up to 2 levels
                |                                  #   or
                [^\s`!\-()\[\]{};:\'".,<>?«»“”‘’]  # not a space or one of these punct chars
              )
        ~';

        $callback = function ($urlMatch) {
            $url = $urlMatch[0];

            // Look for protocol
            preg_match('~^(ht|f)tps?://~', $url, $protocolMatch);

            if ($protocolMatch) {
                $protocol = $protocolMatch[0];
            } else {
                $protocol = 'http://';
                $url = $protocol.$url;
            }

            // Start building caption, remove protocol from url
            $noProtocol = substr($url, strlen($protocol));

            // Check for a variation of www
            preg_match('/www\d{0,3}\./', $noProtocol, $wwwMatch);

            if ($wwwMatch) {
                // Remove www
                $noProtocol = substr($noProtocol, strlen($wwwMatch[0]));
            }

            // Only use domain name as caption
            $caption = explode('/', $noProtocol)[0];

            return $this->generateTag('a', $this->linkAttributes + ['href' => $url, $this->externalKey => $caption]);
        };

        return preg_replace_callback($pattern, $callback, $text);
    }
448243
public function link($text, $href, $label=false, array $attr=[]){
		$field = $this->factory('link', false, $label, array_merge(array('text' => $text, 'href' => $href), $attr));
		return $this->addField($field);
	}
474856
public function addHelpText(string $text, string $link = null, $critical = false)
    {
        if(!$link) {
            $this->help_texts[] = $text;
        }else{
            $this->help_texts[] = [$text, $link];
        }
        if($critical)
            $this->critical_help_texts = true;

        return $this;
    }
1030527
public static function parse($text, $context = null)
    {
        if (!static::$_enabled || strpos($text, '{') === false) {
            return $text;
        }

        if ($context === null) {
            $context = static::_getDefaultContext();
        }

        static::cache('context', $context);
        $pattern = static::_regex();

        return preg_replace_callback("/{$pattern}/s", 'static::_doShortcode', $text);
    }
1319244
public function linkTo($text, $urlOptions, array $attrs = [])
    {
        $url = $this->parseUrlOptions($urlOptions);
        return $this->contentTag('a', $text, array_merge(['href' => $url], $attrs));
    }
651046
public static function urlize($text, $separator = '-')
    {
        $text = self::unaccent($text);

        return self::postProcessText($text, $separator);
    }