/** * User handler for code block * * @param TexyHandlerInvocation handler invocation * @param string block type * @param string text to highlight * @param string language * @param TexyModifier modifier * @return TexyHtml */ function blockHandler($invocation, $blocktype, $content, $lang, $modifier) { if ($blocktype !== 'block/code') { return $invocation->proceed(); } $lang = strtoupper($lang); if ($lang == 'JAVASCRIPT') { $lang = 'JS'; } $fshl = new fshlParser('HTML_UTF8', P_TAB_INDENT); if (!$fshl->isLanguage($lang)) { return $invocation->proceed(); } $texy = $invocation->getTexy(); $content = Texy::outdent($content); $content = $fshl->highlightString($lang, $content); $content = $texy->protect($content, Texy::CONTENT_BLOCK); $elPre = TexyHtml::el('pre'); if ($modifier) { $modifier->decorate($texy, $elPre); } $elPre->attrs['class'] = strtolower($lang); $elCode = $elPre->create('code', $content); return $elPre; }
/** * @param array $values * @return Comment * @throws ActionFailedException */ public function save(array $values) { $numberOfComments = $this->getNumberOfComments($values['page']); $repliesReferences = $this->findRepliesReferences($values['text']); try { $this->em->beginTransaction(); // no replies references found if (empty($repliesReferences)) { $comment = new Comment($values['author'], $this->texy->process($values['text']), $values['page'], $numberOfComments + 1, $this->request->getRemoteAddress()); $this->em->persist($comment)->flush(); $this->em->commit(); return $comment; } $commentsToReply = $this->findCommentsToReply($values['page'], $repliesReferences); $values['text'] = $this->replaceReplyReferencesByAuthors($values['text'], $commentsToReply); $comment = new Comment($values['author'], $this->texy->process($values['text']), $values['page'], $numberOfComments + 1); $this->em->persist($comment); /** @var Comment $comment */ foreach ($commentsToReply as $commentToReply) { $commentToReply->addReaction($comment); $this->em->persist($commentToReply); } $this->em->flush(); $this->em->commit(); } catch (\Exception $e) { $this->em->rollback(); $this->em->close(); throw new ActionFailedException(); } return $comment; }
public function __construct(Texy $texy, HtmlElement $element, $indented) { $this->texy = $texy; $this->element = $element; $this->indented = (bool) $indented; $this->patterns = $texy->getBlockPatterns(); }
protected function createTemplate($class = NULL) { $template = parent::createTemplate($class); $texy = new \Texy(); $texy->encoding = 'utf-8'; $texy->setOutputMode(\Texy::HTML5); // config as in \TexyConfigurator::safeMode($texy); $safeTags = array('a' => array('href', 'title'), 'acronym' => array('title'), 'b' => array(), 'br' => array(), 'cite' => array(), 'code' => array(), 'em' => array(), 'i' => array(), 'strong' => array(), 'sub' => array(), 'sup' => array(), 'q' => array(), 'small' => array()); $texy->allowedClasses = \Texy::NONE; // no class or ID are allowed $texy->allowedStyles = \Texy::NONE; // style modifiers are disabled $texy->allowedTags = $safeTags; // only some "safe" HTML tags and attributes are allowed $texy->urlSchemeFilters[\Texy::FILTER_ANCHOR] = '#https?:|ftp:|mailto:#A'; $texy->urlSchemeFilters[\Texy::FILTER_IMAGE] = '#https?:#A'; $texy->allowed['image'] = FALSE; // disable images $texy->allowed['link/definition'] = FALSE; // disable [ref]: URL reference definitions $texy->allowed['html/comment'] = FALSE; // disable HTML comments # zakázaní nadpisů $texy->allowed['heading/surrounded'] = FALSE; $texy->allowed['heading/underlined'] = FALSE; # zalamování textu v odstavcích po enteru # false => nebude spojovat řádky, vloží místo enteru <br> # true => řádky po jednom enteru spojí $texy->mergeLines = false; $texy->linkModule->forceNoFollow = TRUE; // force rel="nofollow" $template->registerHelper('texy', callback($texy, 'process')); return $template; }
public function commentTexy($text) { if (!isset($this->commentTexy)) { $this->commentTexy = $this->texyFactory->createTexyForComment(); } return $this->commentTexy->process($text); }
protected function createTemplate($class = NULL) { $template = parent::createTemplate($class); $texy = new \Texy(); $texy->encoding = 'utf-8'; $texy->setOutputMode(\Texy::HTML5); // config as in \TexyConfigurator::safeMode($texy); $safeTags = array('a' => array('href', 'title'), 'acronym' => array('title'), 'b' => array(), 'br' => array(), 'cite' => array(), 'code' => array(), 'em' => array(), 'i' => array(), 'strong' => array(), 'sub' => array(), 'sup' => array(), 'q' => array(), 'small' => array()); $texy->allowedClasses = \Texy::NONE; // no class or ID are allowed $texy->allowedStyles = \Texy::NONE; // style modifiers are disabled $texy->allowedTags = $safeTags; // only some "safe" HTML tags and attributes are allowed $texy->urlSchemeFilters[\Texy::FILTER_ANCHOR] = '#https?:|ftp:|mailto:#A'; $texy->urlSchemeFilters[\Texy::FILTER_IMAGE] = '#https?:#A'; $texy->allowed['image'] = FALSE; // disable images $texy->allowed['link/definition'] = FALSE; // disable [ref]: URL reference definitions $texy->allowed['html/comment'] = FALSE; // disable HTML comments $texy->linkModule->forceNoFollow = TRUE; // force rel="nofollow" $template->registerHelper('texy', callback($texy, 'process')); return $template; }
/** * @param null $class * @return Nette\Templating\ITemplate */ protected function createTemplate($class = NULL) { $template = parent::createTemplate($class); $template->registerHelper('texy', function ($input) { $texy = new \Texy(); $html = new Nette\Utils\Html(); return $html::el()->setHtml($texy->process($input)); }); $template->registerHelper('vlna', function ($string) { $string = preg_replace('<([^a-zA-Z0-9])([ksvzaiou])\\s([a-zA-Z0-9]{1,})>i', "\$1\$2 \$3", $string); // === \xc2\xa0 return $string; }); $template->registerHelper('dateInWords', function ($time) { $time = Nette\Utils\DateTime::from($time); $months = [1 => 'leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec']; return $time->format('j. ') . $months[$time->format('n')] . $time->format(' Y'); }); $template->registerHelper('timeAgoInWords', function ($time) { $time = Nette\Utils\DateTime::from($time); $delta = round((time() - $time->getTimestamp()) / 60); if ($delta == 0) { return 'před okamžikem'; } if ($delta == 1) { return 'před minutou'; } if ($delta < 45) { return "před {$delta} minutami"; } if ($delta < 90) { return 'před hodinou'; } if ($delta < 1440) { return 'před ' . round($delta / 60) . ' hodinami'; } if ($delta < 2880) { return 'včera'; } if ($delta < 43200) { return 'před ' . round($delta / 1440) . ' dny'; } if ($delta < 86400) { return 'před měsícem'; } if ($delta < 525960) { return 'před ' . round($delta / 43200) . ' měsíci'; } if ($delta < 1051920) { return 'před rokem'; } return 'před ' . round($delta / 525960) . ' lety'; }); return $template; }
public static function prepareTemplate(Template $template) { $texy = new \Texy(); $latte = $template->getLatte(); $latte->addFilter('texy', function ($text) use($texy) { return Html::el('')->setHtml($texy->process($text)); }); $latte->addFilter('time', function ($text) { return date('j.n.Y G:i:s', $text); }); }
protected function createTemplate() { $template = parent::createTemplate(); $template->addFilter('texy', function ($text) { $texy = new \Texy(); $texy->setOutputMode(\Texy::HTML4_TRANSITIONAL); $texy->encoding = 'utf-8'; $texy->allowedTags = array('strong' => \Texy::NONE, 'b' => \Texy::NONE, 'a' => array('href'), 'em' => \Texy::NONE, 'p' => \Texy::NONE); //$texy->allowedTags = \Texy::NONE; return $texy->process($text); }); return $template; }
/** * User handler for images * * @param TexyHandlerInvocation handler invocation * @param TexyImage * @param TexyLink * @return TexyHtml|string|FALSE */ function imageHandler($invocation, $image, $link) { $texy = $invocation->getTexy(); if (substr($image->URL, -4) === '.swf') { $movie = Texy::prependRoot($image->URL, $texy->imageModule->root); $dimensions = ($image->width ? 'width="' . $image->width . '" ' : '') . ($image->height ? 'width="' . $image->height . '" ' : ''); $movie = htmlSpecialChars($movie); $altContent = htmlSpecialChars($image->modifier->title); // @see http://phpfashion.com/how-to-correctly-insert-a-flash-into-xhtml $code = ' <!--[if !IE]> --> <object type="application/x-shockwave-flash" data="' . $movie . '" ' . $dimensions . '> <!-- <![endif]--> <!--[if IE]> <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" ' . $dimensions . ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,0,0"> <param name="movie" value="' . $movie . '" /> <!--><!--dgx--> <p>' . $altContent . '</p> </object> <!-- <![endif]--> '; return $texy->protect($code, Texy::CONTENT_BLOCK); } return $invocation->proceed(); }
public function processTypo($text) { $key = $this->cacheKey($text); if (!($html = $this->cache->load($key))) { $html = parent::processTypo($text); $this->cache->save($html); } return $html; }
function wiki_texy_phraseHandler($invocation, $phrase, $content, $modifier, $link) { if (!$link) { return $invocation->proceed(); } if (Texy::isRelative($link->URL)) { $link->URL = '?page=' . urlencode($link->URL); } elseif (substr($link->URL, 0, 5) === 'wiki:') { $link->URL = 'http://en.wikipedia.org/wiki/Special:Search?search=' . urlencode(substr($link->URL, 5)); } elseif (substr($link->URL, 0, 4) === 'url:') { $link->URL = substr($link->URL, 4); } return $invocation->proceed(); }
public function processNewMessageForm(Form $form) { $values = $form->getValues(); $recipients = is_array($values->recipients) ? $values->recipients : [$values->recipients]; if (!$this->authorizator->isAllowed($this->user, 'message', 'sent_to_restricted_recipients')) { $s = $this->messagesFacade->canMessageBeSentTo($values->recipients, $this->restrictedUsers, $this->users); if ($s === false) { $form->addError('Nelze odeslat zprávu vybranému příjemci.'); return; } } if ($values['isSendAsAdmin'] == true and !$this->authorizator->isAllowed($this->user, 'message', 'send_as_admin')) { $form->addError('Nemáte dostatečná oprávnění k akci.'); return; } $texy = new \Texy(); $texy->setOutputMode(\Texy::HTML4_TRANSITIONAL); $texy->encoding = 'utf-8'; $texy->allowedTags = \Texy::ALL; $text = $texy->process($values->text); $message = new SentMessage($values->subject, $text, $this->user); if ($values['isSendAsAdmin']) { $message->sendByAuthorRole(); } try { $this->messagesFacade->sendMessage($message, $recipients); } catch (MessageLengthException $ml) { $form->addError('Zprávu nelze uložit, protože je příliš dlouhá.'); return; } catch (DBALException $e) { $this->flashMessage('Zpráva nemohla být odeslána. Zkuste akci opakovat později.', 'errror'); $this->redirect('this'); } $this->presenter->flashMessage('Zpráva byla úspěšně odeslána', 'success'); $this->presenter->redirect('MailBox:sent'); }
/** * @param TexyHandlerInvocation handler invocation * @param string * @param string * @param TexyModifier * @param TexyLink * @return TexyHtml|string|FALSE */ function phraseHandler($invocation, $phrase, $content, $modifier, $link) { // is there link? if (!$link) { return $invocation->proceed(); } if (Texy::isRelative($link->URL)) { // modifiy link $link->URL = 'index?page=' . urlencode($link->URL); } elseif (substr($link->URL, 0, 5) === 'wiki:') { // modifiy link $link->URL = 'http://en.wikipedia.org/wiki/Special:Search?search=' . urlencode(substr($link->URL, 5)); } return $invocation->proceed(); }
public function __construct() { parent::__construct(); // safe mode \TexyConfigurator::safeMode($this); // output $this->setOutputMode(self::HTML4_TRANSITIONAL); $this->htmlOutputModule->removeOptional = false; self::$advertisingNotice = false; $this->allowed['heading/surrounded'] = false; $this->allowed['heading/underlined'] = false; $this->allowed['link/definition'] = false; $this->allowed['image/definition'] = false; $this->mergeLines = false; $this->addHandler('phrase', array(__CLASS__, 'linkHandler')); }
/** * Callback for: <tag attr="...">. * * @param TexyLineParser * @param array regexp matches * @param string pattern name * @return TexyHtml|string|FALSE */ public function patternTag($parser, $matches) { list(, $mEnd, $mTag, $mAttr, $mEmpty) = $matches; // [1] => / // [2] => tag // [3] => attributes // [4] => / $tx = $this->texy; $isStart = $mEnd !== '/'; $isEmpty = $mEmpty === '/'; if (!$isEmpty && substr($mAttr, -1) === '/') { // uvizlo v $mAttr? $mAttr = substr($mAttr, 0, -1); $isEmpty = TRUE; } // error - can't close empty element if ($isEmpty && !$isStart) { return FALSE; } // error - end element with atttrs $mAttr = trim(strtr($mAttr, "\n", ' ')); if ($mAttr && !$isStart) { return FALSE; } $el = TexyHtml::el($mTag); if ($isStart) { // parse attributes $matches2 = NULL; preg_match_all('#([a-z0-9:-]+)\\s*(?:=\\s*(\'[^\']*\'|"[^"]*"|[^\'"\\s]+))?()#isu', $mAttr, $matches2, PREG_SET_ORDER); foreach ($matches2 as $m) { $key = strtolower($m[1]); $value = $m[2]; if ($value == NULL) { $el->attrs[$key] = TRUE; } elseif ($value[0] === '\'' || $value[0] === '"') { $el->attrs[$key] = Texy::unescapeHtml(substr($value, 1, -1)); } else { $el->attrs[$key] = Texy::unescapeHtml($value); } } } $res = $tx->invokeAroundHandlers('htmlTag', $parser, array($el, $isStart, $isEmpty)); if ($res instanceof TexyHtml) { return $tx->protect($isStart ? $res->startTag() : $res->endTag(), $res->getContentType()); } return $res; }
public function __construct() { parent::__construct(); // output $this->setOutputMode(self::HTML4_TRANSITIONAL); $this->htmlOutputModule->removeOptional = false; self::$advertisingNotice = false; // safe mode TexyConfigurator::safeMode($this); $this->allowed['heading/surrounded'] = false; $this->allowed['heading/underlined'] = false; $this->allowed['link/definition'] = false; $this->allowed['image/definition'] = false; // spojování textu v odstavcích po enteru $this->mergeLines = true; // přidání target="_blank" k odkazům // $this->addHandler('phrase', array(__CLASS__, 'addTargetHandler')); }
/** * @param array $values * @param Page $page * @throws PagePublicationTimeException * @throws PageIntroHtmlLengthException */ private function fillPageEntity(array $values, Page $page) { $page->setTitle($values['title']); $page->setMetaDescription($values['description']); $page->setMetaKeywords($values['keywords']); $page->setIntro($values['intro']); $page->setIntroHtml($this->texy->process($values['intro'])); $page->setText($values['text']); if ($values['text'] === null) { $page->setTextHtml(null); } else { $page->setTextHtml($this->texy->process($values['text'])); } $page->setPublishedAt($values['publishedAt']); $page->setAllowedComments($values['allowedComments']); if ($page->isDraft() and $values['saveAsDraft'] === false) { $page->setAsPublished($values['publishedAt']); } }
/** * Callback for self::texyBlocks. * @ignore internal */ public static function texyCb($m) { list(, $mAttrs, $mContent) = $m; // parse attributes $attrs = array(); if ($mAttrs) { foreach (String::matchAll($mAttrs, '#([a-z0-9:-]+)\\s*(?:=\\s*(\'[^\']*\'|"[^"]*"|[^\'"\\s]+))?()#isu') as $m) { $key = strtolower($m[1]); $val = $m[2]; if ($val == NULL) { $attrs[$key] = TRUE; } elseif ($val[0] === '\'' || $val[0] === '"') { $attrs[$key] = html_entity_decode(substr($val, 1, -1), ENT_QUOTES, 'UTF-8'); } else { $attrs[$key] = html_entity_decode($val, ENT_QUOTES, 'UTF-8'); } } } return self::$texy->process($m[2]); }
/** * Finish invocation. * * @param TexyHandlerInvocation handler invocation * @param string * @param string * @return TexyHtml|FALSE */ public function solve($invocation, $emoticon, $raw) { $tx = $this->texy; $file = $this->icons[$emoticon]; $el = TexyHtml::el('img'); $el->attrs['src'] = Texy::prependRoot($file, $this->root === NULL ? $tx->imageModule->root : $this->root); $el->attrs['alt'] = $raw; $el->attrs['class'][] = $this->class; // file path $file = rtrim($this->fileRoot === NULL ? $tx->imageModule->fileRoot : $this->fileRoot, '/\\') . '/' . $file; if (@is_file($file)) { // intentionally @ $size = @getImageSize($file); // intentionally @ if (is_array($size)) { $el->attrs['width'] = $size[0]; $el->attrs['height'] = $size[1]; } } $tx->summary['images'][] = $el->attrs['src']; return $el; }
/** * User handler for code block. * * @param TexyHandlerInvocation handler invocation * @param string block type * @param string text to highlight * @param string language * @param TexyModifier modifier * @return TexyHtml */ public static function blockHandler($invocation, $blocktype, $content, $lang, $modifier) { if (preg_match('#^block/(php|neon|javascript|js|css|html|htmlcb|latte)$#', $blocktype)) { list(, $lang) = explode('/', $blocktype); } elseif ($blocktype !== 'block/code') { return $invocation->proceed(); } $lang = strtolower($lang); if ($lang === 'htmlcb' || $lang === 'latte') { $lang = 'html'; } elseif ($lang === 'javascript') { $lang = 'js'; } if ($lang === 'html') { $langClass = 'FSHL\\Lexer\\LatteHtml'; } elseif ($lang === 'js') { $langClass = 'FSHL\\Lexer\\LatteJavascript'; } else { $langClass = 'FSHL\\Lexer\\' . ucfirst($lang); } $texy = $invocation->getTexy(); $content = Texy::outdent($content); if (class_exists($langClass)) { $fshl = new FSHL\Highlighter(new FSHL\Output\Html(), FSHL\Highlighter::OPTION_TAB_INDENT); $content = $fshl->highlight($content, new $langClass()); } else { $content = htmlSpecialChars($content); } $content = $texy->protect($content, Texy::CONTENT_BLOCK); $elPre = TexyHtml::el('pre'); if ($modifier) { $modifier->decorate($texy, $elPre); } $elPre->attrs['class'] = 'src-' . strtolower($lang); $elCode = $elPre->create('code', $content); return $elPre; }
function process($text, $useCache = TRUE) { $this->time = -microtime(TRUE); if ($useCache) { $md5 = md5($text); // md5 is key for caching // check, if cached file exists $cacheFile = $this->cachePath . $md5 . '.html'; $content = is_file($cacheFile) ? unserialize(file_get_contents($cacheFile)) : NULL; if ($content) { // read from cache list($html, $this->styleSheet, $this->headingModule->title) = $content; } else { // doesn't exists $html = parent::process($text); file_put_contents($cacheFile, serialize(array($html, $this->styleSheet, $this->headingModule->title))); } } else { // if caching is disabled $html = parent::process($text); } $this->time += microtime(TRUE); return $html; }
/** * User handler for code block * * @param TexyHandlerInvocation handler invocation * @param string block type * @param string text to highlight * @param string language * @param TexyModifier modifier * @return TexyHtml */ function blockHandler($invocation, $blocktype, $content, $lang, $modifier) { if ($blocktype !== 'block/code') { return $invocation->proceed(); } $texy = $invocation->getTexy(); global $geshiPath; if ($lang == 'html') { $lang = 'html4strict'; } $content = Texy::outdent($content); $geshi = new GeSHi($content, $lang, $geshiPath . 'geshi/'); // GeSHi could not find the language if ($geshi->error) { return $invocation->proceed(); } // do syntax-highlighting $geshi->set_encoding('UTF-8'); $geshi->set_header_type(GESHI_HEADER_PRE); $geshi->enable_classes(); $geshi->set_overall_style('color: #000066; border: 1px solid #d0d0d0; background-color: #f0f0f0;', true); $geshi->set_line_style('font: normal normal 95% \'Courier New\', Courier, monospace; color: #003030;', 'font-weight: bold; color: #006060;', true); $geshi->set_code_style('color: #000020;', 'color: #000020;'); $geshi->set_link_styles(GESHI_LINK, 'color: #000060;'); $geshi->set_link_styles(GESHI_HOVER, 'background-color: #f0f000;'); // save generated stylesheet $texy->styleSheet .= $geshi->get_stylesheet(); $content = $geshi->parse_code(); // check buggy GESHI, it sometimes produce not UTF-8 valid code :-(( $content = iconv('UTF-8', 'UTF-8//IGNORE', $content); // protect output is in HTML $content = $texy->protect($content, Texy::CONTENT_BLOCK); $el = TexyHtml::el(); $el->setText($content); return $el; }
*/ function imageHandler($invocation, $image, $link) { $parts = explode(':', $image->URL); if (count($parts) !== 2) { return $invocation->proceed(); } switch ($parts[0]) { case 'youtube': $video = htmlSpecialChars($parts[1]); $dimensions = 'width="' . ($image->width ? $image->width : 425) . '" height="' . ($image->height ? $image->height : 350) . '"'; $code = '<div><object ' . $dimensions . '>' . '<param name="movie" value="http://www.youtube.com/v/' . $video . '" /><param name="wmode" value="transparent" />' . '<embed src="http://www.youtube.com/v/' . $video . '" type="application/x-shockwave-flash" wmode="transparent" ' . $dimensions . ' /></object></div>'; $texy = $invocation->getTexy(); return $texy->protect($code, Texy::CONTENT_BLOCK); } return $invocation->proceed(); } $texy = new Texy(); $texy->addHandler('image', 'imageHandler'); // processing $text = file_get_contents('sample.texy'); $html = $texy->process($text); // that's all folks! // echo formated output header('Content-type: text/html; charset=utf-8'); echo $html; // echo generated HTML code echo '<hr />'; echo '<pre>'; echo htmlSpecialChars($html); echo '</pre>';
public function process($text, $singleLine = FALSE) { if ($this->processing) { throw new InvalidStateException('Processing is in progress yet.'); } $this->marks = array(); $this->processing = TRUE; if (is_array($this->allowedClasses)) { $this->_classes = array_flip($this->allowedClasses); } else { $this->_classes = $this->allowedClasses; } if (is_array($this->allowedStyles)) { $this->_styles = array_flip($this->allowedStyles); } else { $this->_styles = $this->allowedStyles; } $text = TexyUtf::toUtf($text, $this->encoding); if ($this->removeSoftHyphens) { $text = str_replace("Β", '', $text); } $text = self::normalize($text); $this->tabWidth = max(1, (int) $this->tabWidth); while (strpos($text, "\t") !== FALSE) { $text = preg_replace_callback('#^(.*)\\t#mU', array($this, 'tabCb'), $text); } $this->invokeHandlers('beforeParse', array($this, &$text, $singleLine)); $this->_linePatterns = $this->linePatterns; $this->_blockPatterns = $this->blockPatterns; foreach ($this->_linePatterns as $name => $foo) { if (empty($this->allowed[$name])) { unset($this->_linePatterns[$name]); } } foreach ($this->_blockPatterns as $name => $foo) { if (empty($this->allowed[$name])) { unset($this->_blockPatterns[$name]); } } $this->DOM = TexyHtml::el(); if ($singleLine) { $this->DOM->parseLine($this, $text); } else { $this->DOM->parseBlock($this, $text); } $this->invokeHandlers('afterParse', array($this, $this->DOM, $singleLine)); $html = $this->DOM->toHtml($this); if (self::$advertisingNotice) { $html .= "\n<!-- by Texy2! -->"; if (self::$advertisingNotice === 'once') { self::$advertisingNotice = FALSE; } } $this->processing = FALSE; return TexyUtf::utf2html($html, $this->encoding); }
/** * Finish invocation. * * @param TexyHandlerInvocation handler invocation * @param string * @param string * @param TexyModifier * @param TexyLink * @return TexyHtml */ public function solve($invocation, $phrase, $content, $mod, $link) { $tx = $this->texy; $tag = isset($this->tags[$phrase]) ? $this->tags[$phrase] : NULL; if ($tag === 'a') { $tag = $link && $this->linksAllowed ? NULL : 'span'; } if ($phrase === 'phrase/code') { $content = $tx->protect(Texy::escapeHtml($content), Texy::CONTENT_TEXTUAL); } if ($phrase === 'phrase/strong+em') { $el = TexyHtml::el($this->tags['phrase/strong']); $el->create($this->tags['phrase/em'], $content); $mod->decorate($tx, $el); } elseif ($tag) { $el = TexyHtml::el($tag)->setText($content); $mod->decorate($tx, $el); if ($tag === 'q') { $el->attrs['cite'] = $mod->cite; } } else { $el = $content; // trick } if ($link && $this->linksAllowed) { return $tx->linkModule->solve(NULL, $link, $el); } return $el; }
/** * Converts document in Texy! to (X)HTML code. * * @param string input text * @param bool is single line? * @return string output HTML code */ public function process($text, $singleLine = FALSE) { if ($this->processing) { throw new InvalidStateException('Processing is in progress yet.'); } // initialization $this->marks = array(); $this->processing = TRUE; // speed-up if (is_array($this->allowedClasses)) { $this->_classes = array_flip($this->allowedClasses); } else { $this->_classes = $this->allowedClasses; } if (is_array($this->allowedStyles)) { $this->_styles = array_flip($this->allowedStyles); } else { $this->_styles = $this->allowedStyles; } // convert to UTF-8 (and check source encoding) $text = TexyUtf::toUtf($text, $this->encoding); if ($this->removeSoftHyphens) { $text = str_replace("", '', $text); } // standardize line endings and spaces $text = self::normalize($text); // replace tabs with spaces $this->tabWidth = max(1, (int) $this->tabWidth); while (strpos($text, "\t") !== FALSE) { $text = preg_replace_callback('#^(.*)\\t#mU', array($this, 'tabCb'), $text); } // user before handler $this->invokeHandlers('beforeParse', array($this, &$text, $singleLine)); // select patterns $this->_linePatterns = $this->linePatterns; $this->_blockPatterns = $this->blockPatterns; foreach ($this->_linePatterns as $name => $foo) { if (empty($this->allowed[$name])) { unset($this->_linePatterns[$name]); } } foreach ($this->_blockPatterns as $name => $foo) { if (empty($this->allowed[$name])) { unset($this->_blockPatterns[$name]); } } // parse Texy! document into internal DOM structure $this->DOM = TexyHtml::el(); if ($singleLine) { $this->DOM->parseLine($this, $text); } else { $this->DOM->parseBlock($this, $text); } // user after handler $this->invokeHandlers('afterParse', array($this, $this->DOM, $singleLine)); // converts internal DOM structure to final HTML code $html = $this->DOM->toHtml($this); // this notice should remain if (self::$advertisingNotice) { $html .= "\n<!-- by Texy2! -->"; if (self::$advertisingNotice === 'once') { self::$advertisingNotice = FALSE; } } $this->processing = FALSE; return TexyUtf::utf2html($html, $this->encoding); }
return FALSE; // it's not my job } $name = $names[$refName]; $el = new Texy\HtmlElement('a'); $el->attrs['href'] = '#comm-' . $refName; // set link destination $el->attrs['class'][] = 'comment'; // set class name $el->attrs['rel'] = 'nofollow'; // enable rel="nofollow" $el->setText("[{$refName}] {$name}:"); // set link label (with Texy formatting) return $el; } $texy = new Texy(); // references link [1] [2] will be processed through user function $texy->addHandler('newReference', 'newReferenceHandler'); // configuration Texy\Configurator::safeMode($texy); // safe mode prevets attacker to inject some HTML code and disable images // how generally disable links or enable images? here is a way: // $disallow = array('image', 'figure', 'linkReference', 'linkEmail', 'linkURL', 'linkQuick'); // foreach ($diallow as $item) // $texy->allowed[$item] = FALSE; // processing $text = file_get_contents('sample.texy'); $html = $texy->process($text); // that's all folks! // echo formated output header('Content-type: text/html; charset=utf-8');
<?php /** * TEXY! USER HANDLER DEMO */ // include Texy! require_once dirname(__FILE__) . '/../../src/texy.php'; $texy = new Texy(); $texy->addHandler('emoticon', array('myHandler', 'emoticon')); $texy->addHandler('image', array('myHandler', 'image')); $texy->addHandler('linkReference', array('myHandler', 'linkReference')); $texy->addHandler('linkEmail', array('myHandler', 'linkEmail')); $texy->addHandler('linkURL', array('myHandler', 'linkURL')); $texy->addHandler('phrase', array('myHandler', 'phrase')); $texy->addHandler('newReference', array('myHandler', 'newReference')); $texy->addHandler('htmlComment', array('myHandler', 'htmlComment')); $texy->addHandler('htmlTag', array('myHandler', 'htmlTag')); $texy->addHandler('script', array('myHandler', 'script')); //$texy->addHandler('paragraph', array('myHandler', 'paragraph')); $texy->addHandler('figure', array('myHandler', 'figure')); $texy->addHandler('heading', array('myHandler', 'heading')); $texy->addHandler('horizline', array('myHandler', 'horizline')); $texy->addHandler('block', array('myHandler', 'block')); $texy->addHandler('afterList', array('myHandler', 'afterList')); $texy->addHandler('afterDefinitionList', array('myHandler', 'afterDefinitionList')); $texy->addHandler('afterTable', array('myHandler', 'afterTable')); $texy->addHandler('afterBlockquote', array('myHandler', 'afterBlockquote')); $texy->addHandler('beforeParse', array('myHandler', 'beforeParse')); $texy->addHandler('afterParse', array('myHandler', 'afterParse')); class myHandler {
/** * @param Texy * @param TexyHtml */ public function __construct(Texy $texy, TexyHtml $element) { $this->texy = $texy; $this->element = $element; $this->patterns = $texy->getLinePatterns(); }