Code Monkey home page Code Monkey logo

textformatter's Introduction

Overview

s9e\TextFormatter is a text formatting library that supports BBCode, Markdown, HTML and other markup via plugins. The library is written in PHP, with a JavaScript port also available for client-side preview (see below.)

Packagist Version Scrutinizer Quality Score Code Coverage Documentation

Installation

The best way to install s9e\TextFormatter is via Composer. See Installation.

composer require s9e/text-formatter

Examples

If you can only read one example, read how to use a bundle.

You can run the scripts directly from the examples directory and you will find in the manual a description of each plugin as well as other examples.

Versioning

Versioning is meant to follow Semantic Versioning. You can read about API changes in the documentation.

Online demo

You can try the JavaScript version in this BBCodes + other stuff demo, or this Markdown + stuff (Fatdown) demo.

Development tools

The following tools are used during development.

textformatter's People

Contributors

clarkwinkelmann avatar davwheat avatar gmartenscb avatar joshyphp avatar marc1706 avatar primehalo avatar un1matr1x avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

textformatter's Issues

Noparse inside noparse not matched correctly

Hi!

The following:

[noparse]
[noparse][/noparse]
[/noparse]

Will produce:

[noparse]
[/noparse]

When I would expect the output to be without whitespaces like:

[noparse][/noparse]

The XML (after parsing) is as follows:

<r><NOPARSE><s>[ignore]</s><br/>
    [ignore]<e>[/ignore]</e></NOPARSE><br/>
    [/ignore]</r>

Which seems to me is totally incorrect?

The usage / template I use are [NOPARSE #ignoreTags=true]{TEXT}[/NOPARSE](usage) and {TEXT}(template)

Is the behaviour intended and am I missing something, or is this a bug?

Sincerely
Rik

FancyPants configuration

Hi,

I would like to be able to enable / disable certain parts of the fancypants plugin. Is this possible?

For example, I want to be able to parse (TM) and (C), but not conver quote pairs to fancy quotes.

My suggested fix for this would be to allow additional configuration like this for example:
$configurator->FancyPants->matchQuotes = true;

Emoticons with Markdown

I try to use Emoticons with Markdown for forum messages plugin.

Emoticons present in Forum bundle and not in Fatdown.
Ok. try enable: (read code comments)

use s9e\TextFormatter\Configurator;

        $configurator = new Configurator;

        $configurator->plugins->load('Autoemail');//Fatdown & Forum default
        $configurator->plugins->load('Autolink');//Fatdown & Forum default
        $configurator->plugins->load('Escaper');//Fatdown default
        $configurator->plugins->load('FancyPants');//Fatdown default
        $configurator->plugins->load('HTMLComments');//Fatdown default
        $configurator->plugins->load('HTMLElements');//Fatdown default
        $configurator->plugins->load('HTMLEntities');//Fatdown default
        $configurator->plugins->load('Litedown');//Fatdown default
//        $configurator->plugins->load('MediaEmbed');//Fatdown & Forum default

// here if load 'MediaEmbed' 'BBcodes' auto added

        $configurator->plugins->load('PipeTables');//Fatdown default
//        $configurator->plugins->load('BBCodes');//Forum default
//        $configurator->plugins->load('Emoji');//Forum default
        $configurator->plugins->load('Emoticons');//Forum default

        $configurator->Emoticons->add(':)', '<img src="happy.png" alt=":)" title="Happy">');
        $configurator->Emoticons->add(';)', '<img src="happy.png" alt=";)" title="Happy">');
        
// here i see all 10 plugins i add with 2 emoticon, all ok.

        extract($configurator->finalize());

// but here after finalize i see 9 plugins without 'Emoticons' 
  1. possible use Emoticons with Markdown?
  2. possible add 'MediaEmbed' without BBcodes?

now i try build 2 parser configuration markdown and bbcodes.

Parse BBcode tags with uid

I'm migrating a forum for a client using an old version of phpBB. All of the posts are written with some sort of "uid" embedded in each bbcode tag which is unique for every post. It looks like this:

[u:d73bfb9507]Standard Edition[/u:d73bfb9507]
[size=18:d73bfb9507]Links[/size:d73bfb9507]
[quote:160984a301="Username"]This is an example post in your phpBB 2 installation. You may delete this post, this topic and even this forum if you like since everything seems to be working![/quote:160984a301]

I pasted this snippet in to the demo and it doesn't appear to recognize this structure. If I remove the :d73bfb9507 bit from each tag it works except for the size tag.

Cannot access protected property s9e\TextFormatter\Plugins\Autolink\Configurator::$matchWww

Code:

$configurator = new \s9e\TextFormatter\Configurator;
$configurator->rootRules->enableAutoLineBreaks();
$configurator->plugins->load('Litedown');
$configurator->plugins->load('Autoemail');
$configurator->Autolink->matchWww = true;

gives error:
Cannot access protected property s9e\TextFormatter\Plugins\Autolink\Configurator::$matchWww
PHP 5.6.20

Official documentation:
http://s9etextformatter.readthedocs.org/Plugins/Autolink/Synopsis/

Changing arrow-up symbol in phpBB BBcode template results in error

I wanted to choose a different symbol for the link to original post so I changed the arrow-up symbol in the BBcode.html inside prosilvers template (from ↑ to ⋙) but I then get the following error:

[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7414: DOMXPath::evaluate(): Undefined namespace prefix
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7414: DOMXPath::evaluate(): Invalid expression
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7414: DOMXPath::evaluate(): Undefined namespace prefix
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7414: DOMXPath::evaluate(): Invalid expression
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7414: DOMXPath::evaluate(): Undefined namespace prefix
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7414: DOMXPath::evaluate(): Invalid expression
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7500: DOMXPath::query(): Undefined namespace prefix
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7500: DOMXPath::query(): Invalid expression
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7500: Invalid argument supplied for foreach()
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7410: DOMXPath::evaluate(): Undefined namespace prefix
[phpBB Debug] PHP Warning: in file [ROOT]/vendor/s9e/text-formatter/src/Configurator.php on line 7410: DOMXPath::evaluate(): Invalid expression

Fatal error: Uncaught Error: Call to a member function removeChild() on null in .../phpBB/vendor/s9e/text-formatter/src/Configurator.php:7475 Stack trace: #0 .../phpBB/vendor/s9e/text-formatter/src/Configurator.php(7380): s9e\TextFormatter\Configurator\TemplateNormalizations\OptimizeChoose->optimizeChooseElement() #1 .../phpBB/vendor/s9e/text-formatter/src/Configurator.php(5100): s9e\TextFormatter\Configurator\TemplateNormalizations\OptimizeChoose->normalize(Object(DOMElement)) #2 .../phpBB/vendor/s9e/text-formatter/src/Configurator.php(2673): s9e\TextFormatter\Configurator\TemplateNormalizer->normalizeTemplate('

<xs...') #3 .../phpBB/vendor/s9e/text-formatter/src/Configurator.php(5086): s9e\TextFormatter\Configurator\Items\Template->normalize(Object(s9e\TextFo in .../phpBB/vendor/s9e/text-formatter/src/Configurator.php on line 7475

Contradiction in the documentation

At: https://github.com/s9e/TextFormatter/blob/master/docs/Rules.md
On: defaultChildRule
In:

If defaultChildRule is set to 'deny', all tags that are not targeted by an allowChild rule will be denied. By default, defaultChildRule is set to 'deny', which means that all tags are allowed as children unless they are targeted by a denyChild rule.

The explanation in both sentences contradicts itself. Did you mean that defaultChildRule defaults to allow instead of deny

Where is the js BBCode tag parser

Can you please take me to where the BBCode tag parser for the javascript part is?
I'm interested in the parts that parse each specific tag according to its settings and restrictions, not the part that deals with the actual HTML output building, just where it processes the restrictions and decides the actual transformations to use.

bbcode list support

doesn't support list in bbcode.
this examples not work:

Ordered list
[ol]
    [li]Item one[/il]
    [li]Item two[/il]
[/ol]
Unordered list
[ul]
    [li]Item one[/il]
    [li]Item two[/il]
[/ul]
Another variant
[list]
    [li]Item one[/il]
    [li]Item two[/il]
[/list]

Issues with strpos with 0.8.0

PHP Warning:  strpos() expects parameter 1 to be string, object given in /home/travis/build/phpbb/phpbb/phpBB/vendor/s9e/text-formatter/src/Configurator.php on line 2582
PHP Warning:  strpos() expects parameter 1 to be string, object given in /home/travis/build/phpbb/phpbb/phpBB/vendor/s9e/text-formatter/src/Configurator.php on line 2584

etc...

https://travis-ci.org/phpbb/phpbb/jobs/166266901

Custom Plugins

Hello,

Is it possible to write custom plugins?

As far as I can tell, the Configurator that is shipped with the default installation of TextFormatter has the classname hardcoded to $className = 's9e\\TextFormatter\\Plugins\\' . $pluginName . '\\Configurator';, which makes it hard to do a custom plugin!

Thanks!

Adding custom site with template fails

Adding custom site with custom template (not iframe, not flash) fails - template is not generated because template builder has only 3 template types: choose flash and iframe.

[Markdown] Reference-style links not working in posts

Reference-style Markdown links aren't working.

In the following example the first markdown link (Google) doesn't get turned into a hyperlink once the post is made, while the second one (this one) works as expected:

This [Google][1] link doesn't work while [this one](https://google.com "Google") does.
    [1]: https://google.com "Google"

Ties to flarum/framework/issues/630

Execute a callback when tag is used

Hi,

I'm working on a website where I have the requirement to execute a callback when a given tag is being used. For example, I want to send a message to a user (via a text message) that he has been mentioned in a thread. I would love to be able to simply register a callback to, for example, the quote-tag if this is possible, that checks if the referenced "author" variable is some person that is registered to my site.

[quote=Rik]...[/quote]

Nice post!

Would then need to call something like this (just a simplified pseudocode example):

Parser::tag('quote')->callback(function($quote) {
        $user = User::find($quote->author);
        $user->notify('You have been quoted');
    });

What would be the best way to do this with your package?
Is this something that is (natively) supported, or if not, is this something you would be willing to implement?

Thanks in advance!

BBcode image mark malformed

It's me, again.. :)

I have a problem with images with alt option :

$xml = TextFormatter::parse("[img=myimage]https://i.giphy.com/pWWT4gCzW1V9S.gif[/img]");
$html = TextFormatter::render($xml);

echo $html;

Result :

<img alt="" title="" src="myimage"><a rel="nofollow noreferrer" target="_blank" href="https://i.giphy.com/pWWT4gCzW1V9S.gif">https://i.giphy.com/pWWT4gCzW1V9S.gif</a>[/img]

Expected :

<img src="https://i.giphy.com/pWWT4gCzW1V9S.gif" alt="myimage">

example

BBCode conversion

Hi,

I work on a fluxbb to flarum converter in php, I would like to know how to properly convert bbcode posts to flarum lang. I thought I understood that flarum core use your s9e/TextFormatter, that's true ?

Here my code :

<?php

...

$postData = array(
    ':id' => $post['id'],
    ':discussion_id' => $post['topic_id'],
    ':number' => $currentPostNumber,
    ':time' => ConvertTimestampToDatetime(intval($post['posted'])),
    ':user_id' => $userId,
    ':type' => 'comment',
    ':content' => FormatText($post['message']),
    ':edit_time' => ($post['edited']) ? ConvertTimestampToDatetime(intval($post['edited'])) : null,
    ':edit_user_id' => ($post['edited_by']) ? GetUserID($dbFlarum, $post['edited_by']) : null,
    ':is_approved' => 1
);

$query = RunPreparedQuery($dbFlarum, $postData, "INSERT INTO posts(id,discussion_id,number,time,user_id,type,content,edit_time,edit_user_id,is_approved) VALUES(:id,:discussion_id,:number,:time,:user_id,:type,:content,:edit_time,:edit_user_id,:is_approved)");
$postsMigrated += $query->rowCount();

...

function FormatText($text) {
  $text = preg_replace('#\:\w+#', '', $text);
  $text = ConvertBBCodeToFlarumLang($text);
  $text = str_replace("&quot;","\"",$text);
  $text = preg_replace('|[[\/\!]*?[^\[\]]*?]|si', '', $text);
  // Wrap text lines with paragraph tags
  $explodedText = explode("\n", $text);
  foreach ($explodedText as $key => $value)
  {
    // Only wrap in a paragraph tag if the line has actual text
    if(strlen($value) > 1)
      $explodedText[$key] = '<p>' . $value . '</p>';
  }
  $text = implode("\n", $explodedText);
  return $text;
}

function ConvertBBCodeToFlarumLang($text) {
  $text = preg_replace('#\[b](.+)\[\/b]#', "<B><s>[b]</s>$1<e>[/b]</e></B>", $text);
  $text = preg_replace('#\[i](.+)\[\/i]#', "<I><s>[i]</s>$1<e>[/i]</e></I>", $text);
  $text = preg_replace('#\[u](.+)\[\/u]#', "<U><s>[u]</s>$1<e>[/u]</e></U>", $text);
  $text = preg_replace('#\[s](.+)\[\/s]#', "<S><s>[s]</s>$1<e>[/s]</e></S>", $text);
  $text = preg_replace('#\[h](.+)\[\/h]#', "<H1><s># </s>$1</H1>", $text);
  $text = preg_replace('#\[center](.+)\[\/center]#', "<CENTER><s>[center]</s>$1<e>[/center]</e></CENTER>", $text);
  $text = preg_replace('#\[color=\#(\w+)](.+)\[\/color]#', "<COLOR color=\"#$1\"><s>[color=]</s>$2<e>[/color]</e></COLOR>", $text);
  $text = preg_replace('#\[quote](.+)\[\/quote]#', "<QUOTE><i>&gt;</i>$1</QUOTE>", $text);
  $text = preg_replace('#\[quote=(.+)](.+)\[\/quote]#', "<QUOTE author=\"$1\"><s>[quote=$1]</s><p>$2</p><e>[/quote]</e></QUOTE>", $text);
  $text = preg_replace('#\[url](.+)\[\/url]#', "<URL url=\"$1\"><s>[url=$1]</s>$1<e>[/url]</e></URL>", $text);
  $text = preg_replace('#\[url=(.+)](.+)\[\/url]#', "<URL url=\"$1\"><s>[url=$1]</s>$2<e>[/url]</e></URL>", $text);
  $text = preg_replace('#\[img](.+)\[\/img]#', "<IMG src=\"$1\"><s>[img]</s>$1<e>[/img]</e></IMG>", $text);
  $text = preg_replace('#\[img=(.+)](.+)\[\/img]#', "<IMG alt=\"$1\" src=\"$2\"><s>![</s>$1<e>]($2)</e></IMG>", $text);
  $text = preg_replace('#\[code](.+)\[\/code]#is', "<CODE><s>```</s>$1<e>```</e></CODE>", $text);
  $text = preg_replace('#\[pre](.+)\[\/pre]#is', "<CODE><s>```</s>$1<e>```</e></CODE>", $text);
  $text = preg_replace('#\[list=\*](.+)\[\/list]#is', "<LIST><s>[list=*]</s>$1<e>[/list]</e></LIST>", $text);
  $text = preg_replace('#\[\*](.+)\[\/\*]#is', "<LI><s>[*]</s><p>$1</p><e>[/*]</e></LI>", $text);
  return $text;
}

it seems to work, but posts doesn't look nice. Here some examples : https://beta-import.mondedie.fr/

Can you give me some hints/suggestions for improving my converter ? I intend to make it open-source when it will be stable.

Thank you in advance :)
Best regards.

feature request: vube.com

Vube.com is a YouTube competitor. But unlike YouTube pays people who have popular videos without adding ads to their videos.

I would like to see this added, please.

Here is an example of their embed code

<iframe type="text/html" width="640" height="435" src="http://vube.com/embed/video/wovO34HWbY?userId=6ZdBfCnF8E&autoplay=false&fit=true" allowfullscreen frameborder="0"> </iframe>

Here is their share link
http://vube.com/s/v7JeV6

No whitespace check for emoticons

If I set up an emoticon for :/, then it's replaced into URLs, like:

http😕/example.org

I think emoticons should only be replaced if they have whitespace on either side.

emoji path

is it possible to set emoji path to use different emojis, like apple, google...

Error when BBCode is enabled after Autolink/Autoemail

Easy to work around, but thought it would be worth reporting nonetheless.

$configurator->Autolink;
$configurator->BBCodes->addFromRepository('URL');

Results in a Tag 'URL' already exists error. Similar thing when you do the EMAIL BBCode/Autoemail.

This works fine though:

$configurator->BBCodes->addFromRepository('URL');
$configurator->Autolink;

cleanup bbcode

Hi, Is it possible to clean up bbcode with this library?

example :

$text_with_bbcode='[b]text[/b]';
echo TextFormatter::removebbcode($text_with_bbcode); // text

Thanks for your time.

Release 0.1.0

It would be helpful if you could tag v0.1.0 and start semver. This would allow me/others to composer require the package with "minimum-stability": "stable", and without the @dev suffix for the package version (which is causing problems for me given that TextFormatter is a sub-dependency).

Is it possible to use PHP functions in XSLT templates?

Sorry, this is a support request, not an issue!

For example, if my template is:

<a href="{url}" class="UserMention">@<xsl:value-of select="@username"/></a>

Where I want {url} to be dynamically generated from a PHP function which is passed a couple of attributes, like:

function ($id, $username) use ($urlService) {
    return $urlService->generateUrlToUser($id, $username);
}

Markdown quote levels

Hi @JoshyPHP

today use last (0.9.0) version :)

with test message:

> --- **admin** *[wrote:](/forum/post/30#p30)*
>> --- **admin** *[wrote:](/forum/post/29#p29)*
>>> --- **admin** *[wrote:](/forum/post/26#p26)*
>>>> --- **admin** *[wrote:](/forum/post/26#p26)*
>>>>
>>>>> --- **admin** *[wrote:](/forum/post/25#p25)*
>>>>
>>>>>> --- **odmin** *[wrote:](/forum/post/3#p3)*
>>>>>
>>>>>>1. rewrewerwr
>>>>>>2. wrwrwreer
>>>>>>3. werwerer
>>>>>>4. wrewerrew
>>>>>>5. 234232424
>>>>>>6. dfgdfggfdg  
>>>>>>
>>>>>>> sdfsdfsdfsdf
>>>>>>>> sdfsdfsdfsdf
>>>>>>>>> sdfsdfsdfsdf
>>>>>>
>>>>>>```php
>>>>>>        if ($already_registered) {
>>>>>>            throw new  RunBBException(__('Registration flood'), 429);
>>>>>>        }
>>>>>>```
>>>>>
>>>>>check quote with code
>>>>
>>>>and more 8)
>>
>>and more 8)
>
>
>and more 8)

parser return:

array (3)
    0 => "debug" (5)
    1 => "Skipping end tag with no start tag" (34)
    2 => array (1)
        tag => s9e\TextFormatter\Parser\Tag #62f1
            attributes protected => array ()
            cascade protected => array ()
            endTag protected => NULL
            flags protected => 268
            invalid protected => FALSE
            len protected => 0
            name protected => "QUOTE" (5)
            pos protected => 500
            sortPriority protected => 0
            startTag protected => s9e\TextFormatter\Parser\Tag #f0cd { ... }
            type protected => 2

if qoutes reduce to one level then no problem
for information: SimpleMDE editor i use show this fine

github show fine too.

Escaping Litedown

How can I escape Litedown Markdown? In Markdown that is accomplished by using a backslash, like bold (not). Thanks!

Support for [video] tag

We are planning to use TextFormatter for our forum software MyBB 2.0.

Most BBCodes we've had in previous versions work out-of-the box however MediaEmbed doesn't recognize embedded videos.

Examples:

[video=youtube]https://www.youtube.com/watch?v=BRHapKieNm4[/video]
[video=vimeo]https://vimeo.com/140588069[/video]

Is there an option to use [video] instead of or in addition to [media]? AFAIK the [video] tag is quite common.

Add feature to sanitize attributes values

what currently is missing:

  • a way to specifying whitelisted value kind (numerical, alphabetical, numerical + css sizes, etc)
  • filter style attribute to allow only some css attributes like color or font
  • filter class attribute to allow only some specific classes

for first problem HTMLElements::allowAttribute can also accept a third argument which can be a string (which can be numerical, alphabetical, ...) or regex (which is useful for some specific usage. like sanitize src value).
this argument also could be callable function but I think that not gonna available in front-end then.

with implementing this the two other problem also can be fixed but if HTMLElements had some method for whitelisting css styles and classes for specific tags that'd be great.

Quotes in attributes cause BBCode not to be parsed

If [font] has quotes around a particular font like below the BBcode is not parsed.

[font=Lato, "Helvetica Neue", Helvetica, Arial, sans-serif]...[/font]

Though, without the quotes, works perfectly fine.

[font=Lato, Helvetica, Arial, sans-serif]...[/font]

Is there any work around for this?

Getting configuration data after configuring

Is there a way to get the results of the configured data after all has been set in a way that is easy to work with from code?
For example, I input many tags using the CodeMonkey method and then I want to get the list of all tags that were input and all their configurations. How do I do that?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.