Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.

@param string $text the Text to check
@param int $gradeid The grade ID which refers to the id in the gradebook
502075
private function rewrite_feedback_comments_urls(string $text, int $gradeid) {
        return file_rewrite_pluginfile_urls(
            $text,
            'pluginfile.php',
            $this->assignment->get_context()->id,
            ASSIGNFEEDBACK_COMMENTS_COMPONENT,
            ASSIGNFEEDBACK_COMMENTS_FILEAREA,
            $gradeid
        );
    }
720694
public function linkUrlsAndEscapeHtml($text)
	{
		// We can abort if there is no . in $text
		if ( strpos($text, '.') === false )
		{
			return $this->escapeHtml($text);
		}

		$html = '';

		$position = 0;

		$match = array();

		while (preg_match($this->buildRegex(), $text, $match, PREG_OFFSET_CAPTURE, $position))
		{
			list($url, $urlPosition) = $match[0];

			// Add the text leading up to the URL.
			$html .= $this->escapeHtml(substr($text, $position, $urlPosition - $position));

			$scheme      = $match[1][0];
			$username    = $match[2][0];
			$password    = $match[3][0];
			$domain      = $match[4][0];
			$afterDomain = $match[5][0]; // everything following the domain
			$port        = $match[6][0];
			$path        = $match[7][0];

			// Check that the TLD is valid or that $domain is an IP address.
			$tld = strtolower(strrchr($domain, '.'));

			$validTlds = $this->validTlds;

			if (preg_match('{^\.[0-9]{1,3}$}', $tld) || isset($validTlds[$tld]))
			{
				// Do not permit implicit scheme if a password is specified, as
				// this causes too many errors (e.g. "my email:foo@example.org").
				if ( ! $scheme && $password )
				{
					$html .= $this->escapeHtml($username);

					// Continue text parsing at the ':' following the "username".
					$position = $urlPosition + strlen($username);

					continue;
				}

				if ( ! $scheme && $username && ! $password && ! $afterDomain )
				{
					// Looks like an email address.
					$emailLinkCreator = $this->emailLinkCreator;

					// Add the hyperlink.
					$html .= $emailLinkCreator($url, $url);
				}
				else
				{
					// Prepend http:// if no scheme is specified
					$completeUrl = $scheme ? $url : "http://$url";
					$linkText = "$domain$port$path";

					$htmlLinkCreator = $this->htmlLinkCreator;

					// Add the hyperlink.
					$html .= $htmlLinkCreator($completeUrl, $linkText);
				}
			}
			else
			{
				// Not a valid URL.
				$html .= $this->escapeHtml($url);
			}

			// Continue text parsing from after the URL.
			$position = $urlPosition + strlen($url);
		}

		// Add the remainder of the text.
		$html .= $this->escapeHtml(substr($text, $position));

		return $html;
	}
749311
public static String urlEncode(final String text) {
        try {
            return URLEncoder.encode(text, StandardCharsets.UTF_8.name());
        } catch (final UnsupportedEncodingException e) {
            final String message = "Unable to encode text : " + text;
            throw new TechnicalException(message, e);
        }
    }
1307084
public function parse($text)
	{
		// Reset the parser and save the uid
		$this->reset($text);
		$uid = $this->uid;

		// Do the heavy lifting
		$this->executePluginParsers();
		$this->processTags();

		// Finalize the document
		$this->finalizeOutput();

		// Check the uid in case a plugin or a filter reset the parser mid-execution
		if ($this->uid !== $uid)
		{
			throw new RuntimeException('The parser has been reset during execution');
		}

		// Log a warning if the fixing cost limit was exceeded
		if ($this->currentFixingCost > $this->maxFixingCost)
		{
			$this->logger->warn('Fixing cost limit exceeded');
		}

		return $this->output;
	}
233512
public function sseMessageLine($text, $id = null)
    {
        if (!is_null($id)) {
            echo "id: $id\n";
        }

        $text = explode("\n", $text);
        $text = 'data: '.implode("\ndata: ", $text)."\n\n";
        echo $text;
        flush();
    }
580921
public function parse(string $text) : bool
    {
        $lower = strtolower($text);
        if (! in_array($lower, array_merge(self::TRUE_VALUES, self::FALSE_VALUES)))
            throw new ParseException($this, $text, 0, self::PARSE_ERROR);
        return in_array($lower, self::TRUE_VALUES);
    }
894420
public function text($text)
    {
        if (is_string($text) || settype($text, 'string') !== false) {
            return parent::text($this->encodeString($text));
        }
        throw new \InvalidArgumentException(get_class($this) . ':text - Cannot cast passed value to string (did you forget to define a __toString on your object?)');
    }
751942
public static function translateFromEditMode($text)
    {
        $app = Application::getFacadeApplication();
        $entityManager = $app->make(EntityManagerInterface::class);
        $resolver = $app->make(ResolverManagerInterface::class);
        $appUrl = Application::getApplicationURL();

        $text = preg_replace(
            [
                '/{CCM:BASE_URL}/i',
            ],
            [
                $appUrl,
            ],
            $text
        );

        //page links...
        $text = preg_replace(
            '/{CCM:CID_([0-9]+)}/i',
            $appUrl . '/' . DISPATCHER_FILENAME . '?cID=\\1',
            $text
        );

        //images...
        $dom = new HtmlDomParser();
        $r = $dom->str_get_html($text, true, true, DEFAULT_TARGET_CHARSET, false);
        if (is_object($r)) {
            foreach ($r->find('concrete-picture') as $picture) {
                $fID = $picture->fid;

                $attrString = "";
                foreach ($picture->attr as $attr => $val) {
                    if (!in_array($attr, self::$blackListImgAttributes)) {
                        $attrString .= "$attr=\"$val\" ";
                    }
                }

                $picture->outertext = '<img src="' . $resolver->resolve([
                        '/download_file',
                        'view_inline',
                        $fID
                    ]) . '" ' . $attrString . '/>';
            }

            $text = (string) $r->restore_noise($r);
        }

        // now we add in support for the links
        $text = static::replacePlaceholder(
            $text,
            '{CCM:FID_([0-9]+)}',
            function ($fID) use ($resolver) {
                if ($fID > 0) {
                    return $resolver->resolve(['/download_file', 'view_inline', $fID]);
                }
            }
        );

        //file downloads...
        $text = static::replacePlaceholder(
            $text,
            '{CCM:FID_DL_([0-9]+)}',
            function ($fID) use ($resolver) {
                if ($fID > 0) {
                    return $resolver->resolve(['/download_file', 'view', $fID]);
                }
            }
        );

        return $text;
    }
805408
public function pageTextContains($text)
    {
        $actual = $this->session->getPage()->getText();
        $actual = preg_replace('/\s+/u', ' ', $actual);
        $regex = '/'.preg_quote($text, '/').'/ui';
        $message = sprintf('The text "%s" was not found anywhere in the text of the current page.', $text);

        $this->assertResponseText((bool) preg_match($regex, $actual), $message);
    }
1305050
public static function parseExternalLinks( $text ) {
		static $urlProtocols = false;
		static $counter = 0;
		// @codeCoverageIgnoreStart
		if ( !$urlProtocols ) {
			if ( function_exists( 'wfUrlProtocols' ) ) {
				// Allow custom protocols
				$urlProtocols = wfUrlProtocols();
			} else {
				$urlProtocols = 'https?:\/\/|ftp:\/\/';
			}
		}
		// @codeCoverageIgnoreEnd

		$extLinkBracketedRegex = '/(?:(<[^>]*)|' .
			'\[(((?i)' . $urlProtocols . ')' .
				self::EXT_LINK_URL_CLASS .
				'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]|' .
			'(((?i)' . $urlProtocols . ')' .
				self::EXT_LINK_URL_CLASS .
				'+))/Su';

		return preg_replace_callback(
			$extLinkBracketedRegex,
			function ( array $bits ) use ( &$counter ) {
				// @codeCoverageIgnoreStart
				if ( $bits[1] != '' ) {
					return $bits[1];
				}
				// @codeCoverageIgnoreEnd

				if ( isset( $bits[4] ) && $bits[4] != '' ) {
					return '<a href="' . $bits[2] . '">' . $bits[4] . '</a>';
				} elseif ( isset( $bits[5] ) ) {
					return '<a href="' . $bits[5] . '">' . $bits[5] . '</a>';
				} else {
					return '<a href="' . $bits[2] . '">[' . ++$counter . ']</a>';
				}
			},
			$text
		);
	}
180038
function encode($text)
    {
        $amount_to_pad = PKCS7Encoder::$blockSize - (strlen($text) % PKCS7Encoder::$blockSize);
        if ($amount_to_pad == 0) {
            $amount_to_pad = PKCS7Encoder::$blockSize;
        }
        list($pad_chr, $tmp) = [chr($amount_to_pad), ''];
        for ($index = 0; $index < $amount_to_pad; $index++) {
            $tmp .= $pad_chr;
        }
        return $text . $tmp;
    }
1316461
public function write(&$text)
    {
        // All: Add the action if left empty
        if (preg_match_all('#<\s*form.*?action=""#im', $text, $matches, PREG_SET_ORDER)) {
            $view   = $this->getTemplate()->getView();
            $state  = $view->getModel()->getState();
            $action = $view->getRoute(http_build_query($state->getData($state->isUnique())));
            
            foreach ($matches as $match) {
                $str  = str_replace('action=""', 'action="'.$action.'"', $match[0]);
                $text = str_replace($match[0], $str, $text);
            }
        }
        
        // POST : Add token
        $matches = array();
        preg_match_all('/(<form.*method="post".*>)/i', $text, $matches, PREG_SET_ORDER);
       
        foreach ($matches as $match) {
            $input = PHP_EOL.'<input type="hidden" name="'.$this->_tokenName().'" value="'.$this->_tokenValue().'" />';
            $text = str_replace($match[0], $match[0].$input, $text, $count);
        }
       
        // GET : Add token to .-anahita-grid forms
        $matches = array();
        preg_match_all('#(<\s*?form\s+?.*?class=(?:\'|")[^\'"]*?-anahita-grid.*?(?:\'|").*?)#im', $text, $matches, PREG_SET_ORDER);
        
        foreach ($matches as $match) {
            $input = ' data-token-name="'.$this->_tokenName().'" data-token-value="'.$this->_tokenValue().'"';
            $text= str_replace($match[0], $match[0].$input, $text, $count);
        }
        
        // GET : Add query params
        $matches = array();
        if (preg_match_all('#<form.*action=".*\?(.*)".*method="get".*>#iU', $text, $matches)) {
            foreach ($matches[1] as $key => $query) {
                parse_str(str_replace('&amp;', '&', $query), $query);
                
                $input = $this->_renderQuery($query);
                $text  = str_replace($matches[0][$key], $matches[0][$key].$input, $text);
            }
        }
        
        return $this;
    }
72109
public function parse($text) {
        $parsedText = $this->parseGs1128($text);
        if($this->customLabelText!==false and CINBarcode1D::AUTO_LABEL!=$this->customLabelText){
            parent::setLabel($this->customLabelText);    
        }
        parent::parse($parsedText);
    }
277638
public function filter($text)
    {
        preg_match_all('/(articles|topics|photos|todos|notes)\/([0-9]+)[-]?/', $text, $matches);

        $ids = $matches[2];

        foreach ($ids as $id) {
            $id = (int) $id;

            $medium = AnService::get('repos:medium.medium')->getQuery()->disableChain()->id($id)->fetch();

            if (isset($medium->id) && $medium->authorize('access')) {
                if ($medium->getRepository()->hasBehavior('portraitable')) {
                    $caption = htmlspecialchars($medium->title, ENT_QUOTES);
                    $pattern = '/((?<!=\")[http]+[s]?:\/\/[^<>\s]+)\/photos\/'.$medium->id.'[-\w\-]*/';
                    $text = preg_replace($pattern,
                    '<div class="an-media-photo"><a data-trigger="MediaViewer" href="'.$medium->getPortraitURL('original').'" title="'.$caption.'" >'
                    .'<img alt="'.$caption.'" src="'.$medium->getPortraitURL('medium').'" />'
                    .'</a></div>',
                    $text);
                } else {
                    $pattern = '/((?<!=\")[http]+[s]?:\/\/[^<>\s]+)\/articles\/'.$medium->id.'[-\w\-]*/';

                    $template = '<div class="medium-preview">';

                    if ($medium->title) {
                        $template .= '<h4><a href="'.route($medium->getURL()).'">'.$medium->title.'</a></h4>';
                    }

                    if ($medium->excerpt) {
                        $template .= '<p>'.$medium->excerpt.'</p>';
                    }

                    $template .= '</div>';

                    $text = preg_replace($pattern, $template, $text);
                }
            }
        }

        return $text;
    }
660569
public function parse($text) {
        $this->text = $text;
        $this->checksumValue = false; // Reset checksumValue
        $this->validate();

        parent::parse($text);

        $this->addDefaultLabel();
    }
1094347
public function convertLinks(string $text, array $options = []): string
    {
        $text = $this->replaceProtocol($text);
        $ret  = ' '.$text;

        $attr = '';
        foreach ($options as $key => $value) {
            $attr .= ' '.$key.'="'.$value.'"';
        }

        // Replace Links with http://
        $ret = (string) preg_replace("#(^|[\n ])([\\w]+?://[\\w\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is", '\\1<a href="\\2"'.$attr.'>\\2</a>', $ret);

        // Replace Links without http://
        $ret = (string) preg_replace("#(^|[\n ])((www|ftp)\\.[\\w\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is", '\\1<a href="http://\\2"'.$attr.'>\\2</a>', $ret);

        // Replace Email Addresses
        $ret = (string) preg_replace("#(^|[\n ])([a-z0-9&\\-_.]+?)@([\\w\\-]+\\.([\\w\\-\\.]+\\.)*[\\w]+)#i", '\\1<a href="mailto:\\2@\\3"'.$attr.'>\\2@\\3</a>', $ret);

        return substr($ret, 1);
    }
1228064
public static function _text($text, $values = array()) {
		_t($text, static::getDomain(), is_array($values) ? $values : array_slice(func_get_args(), 1));
	}