Code Monkey home page Code Monkey logo

jbbcode's Introduction

jBBCode

GitHub release Software License Build Status

jBBCode is a bbcode parser written in php 5.3. It's relatively lightweight and parses bbcodes without resorting to expensive regular expressions.

Documentation

For complete documentation and examples visit jbbcode.com.

A basic example

jBBCode includes a few optional, default bbcode definitions that may be loaded through the DefaultCodeDefinitionSet class. Below is a simple example of using these codes to convert a bbcode string to html.

<?php
require_once "/path/to/jbbcode/Parser.php";

$parser = new JBBCode\Parser();
$parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());

$text = "The default codes include: [b]bold[/b], [i]italics[/i], [u]underlining[/u], ";
$text .= "[url=http://jbbcode.com]links[/url], [color=red]color![/color] and more.";

$parser->parse($text);

print $parser->getAsHtml();

Composer

You may load jBBCode via composer. In your composer.json file:

"require": {
    "jbbcode/jbbcode": "1.3.*"
}

In your php file:

require 'vendor/autoloader.php';

$parser = new JBBCode\Parser();

Contribute

I would love help maintaining jBBCode. Look at open issues for ideas on what needs to be done. Before submitting a pull request, verify that all unit tests still pass.

Running unit tests

To run the unit tests, ensure that phpunit is installed, or install it through the composer dev dependencies. Then run phpunit from the project directory. If you're adding new functionality, writing additional unit tests is a great idea.

License

The project is under MIT license. Please see the license file for details.

jbbcode's People

Contributors

alexmichelet avatar art4 avatar bryant1410 avatar dasourcerer avatar fale avatar frastel avatar ingramz avatar jbowens avatar kubo2 avatar oohnoitz avatar schlaefer avatar shmax 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  avatar  avatar  avatar  avatar  avatar  avatar

jbbcode's Issues

Tag option parsing flaws

While working on #33 I noticed some inconsistencies in ending a tag option and proceeding to the next one:

  • in OPTION_STATE_VALUE, a trailing space is mandatory to detect the end of the value
  • in OPTION_STATE_QUOTED_VALUE, a peek-ahead is done to make sure a space (or end of tag content) comes next. If there is any other character, a ParserException is thrown and caught and all options will be interpreted as one.
  • in OPTION_STATE_JAVASCRIPT however, there is no such check.
    A tag like [video js=javascript: ok();x=y] is considered valid.

I can make a pull request once #33 has been decided, so the merges will not conflict.

I would also like to add single-quoted values ([tag opt='use " in here without problem']) and possibly backslash-escaping ([tag opt="this: \" is a double quote"]).

Another problem is using ] in a (quoted) tag option. Due to the current parser implementation this is impossible.
After all, the parser is not a complete DFSM since the tokenizer only knows [, ], and everything else as tokens.

Documentation suggestion

Just a suggestion about the examples on the web page, you should at least add the following notes to them as general recommendations.

  1. Before calling parse(..) it might be a good idea to use something like htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
  2. Consistently using double quotes in your html replacements when adding bbcodes (in conjunction with previous) will provide at least rudimentary XSS protection.

I know security can be seen as somewhat non-issue for a middleware like jbbcode, however, ideally the concept of {option} and {param} could be enhanced/expanded to allow things like {attribute} etc. with some limits, or at the very least allowing users to externally specify the default CodeDefinition to use for bbcode's added via addBBCode.

Yes it is possible of course by deriving Parser and re-implementing addBBCode, but a geniune interface for it would be nicer.

Content inside invalid-tag not parsing

Code definition from example to [color] with OptionValidator

$builder = new CodeDefinitionBuilder('color', '<span style="color: {option}">{param}</span>');
$builder->setUseOption(true)->setOptionValidator($CssColorValidator);

Here is text with invalid option in [color]

[b] bold text
  [color=!nvaL!d_color]
    [u] must be underline[/u]
  [/color]
[/b]

Result is

<b> bold text
[color=!nvaL!d_color] [u] must be underline [/u] [/color]
</b>

Tokenize.php 'strlen()'

En el archivo

$strLen = strlen($str);

Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated in ...\JBBCode\Tokenizer.php

Una posible solución fue añadir esto if($str == NULL) return; sobre dicha línea mencionada!

Parser does not recognize tag if bbcode is used in option

As said above:

I´m trying to use a "quote" CodeDefinition that can be used with or without option!
Both work, but when I want to use other jBBCode tags inside the option parameter of the quote tag, the first tag in the option loses its opening bracket and the parser can`t recognize the quote tag itself because of it!

E.G:
[quote=[b]test[/b]]testing[/quote]

Output:
[quote=b]test[/b]]test123[/quote]

I tried using quotation in the option, but it was the same result!

Anyone got an idea how I could fix/make a workaround for this?

Parsing table newlines issue

I have set definitions to parse BBC for table as:

    //table
    $builder = new \JBBCode\CodeDefinitionBuilder('table', '<table><tbody>{param}</tbody></table>');
    array_push($this->definitions, $builder->build());

    //thead
    $builder = new \JBBCode\CodeDefinitionBuilder('th', '<th>{param}</th>');
    array_push($this->definitions, $builder->build());

    //tr
    $builder = new \JBBCode\CodeDefinitionBuilder('tr', '<tr>{param}</tr>');
    array_push($this->definitions, $builder->build());

    //td
    $builder = new \JBBCode\CodeDefinitionBuilder('td', '<td>{param}</td>');
    array_push($this->definitions, $builder->build());

It forks fine except it requires all BBC in a table to be in single line. If any part of table is split to new line, empty line will be inserted on top of rendered TABLE.

When dealing with tables it is necessary to split table to several lines and even make indentation for elements to make it readable.

Is there a way to clean all new lines and spaces outside of TR and TD tags within a TABLE?

Strange Bug [Hope find a solution]

Hi,
i made 2 custom class code definitions, but the problem came when this two tags used in nested each other.

If color tag put in size tag, color won't be parsed, so it just produced like this :

xzc[color=#ff99ff]dsfd[/color]sfs

Sorry about my english.
Thank you.

class Size extends JBBCode\CodeDefinition {

    public function __construct()
    {
        parent::__construct();
        $this->setTagName("size");
        $this->setUseOption(true);
        $this->setParseContent(true);           
    }

    public function asHtml( JBBCode\ElementNode $el )
    {
        $ems=array(
            0.75
            ,0.95
            ,1.05
            ,1.45
            ,1.5
            ,2
            ,3
        );

        $content = "";
        foreach( $el->getChildren() as $child )
            $content .= $child->getAsBBCode();

        $attribute=abs(intval($el->getAttribute()));
        $attribute--;
        $em=isset($ems[$attribute]) ? $ems[$attribute] : $ems[2];

        return '<span style="font-size:'.$em.'em !important;">'.$content.'</span>';
    }
}

class Color extends JBBCode\CodeDefinition {

    public function __construct()
    {
        parent::__construct();
        $this->setTagName("color");
        $this->setUseOption(true);
        $this->setParseContent(true);
    }

    public function asHtml( JBBCode\ElementNode $el )
    {
        $content = "";
        foreach( $el->getChildren() as $child )
            $content .= $child->getAsBBCode();

        $color=$el->getAttribute();

        return '<span style="color:'.$color.' !important;">'.$content.'</span>';
    }
}

asText override by custom CodeDefinition

Hello, it is possible to override the getAsText method by a custom CodeDefinition?

For example, i have my own Youtube CodeDefinition, and when i call Parser.getAsText(), instead to show the Youtube URL/ID, i want to have 'Youtube Video'.

I tried to add a new public asText() function in my Youtube CodeDefinition, returning 'Youtube Video', but doesn't work, so i think has to be implemented by modifing the core...

I've tried, and failed, so can you help me getting this done? Thank you.

EDIT: I got it working.

Here how i did, if someone need this functionality, or improve it

ElementNode.php : Replace function

public function getAsText() {
    if( $this->codeDefinition ){
        return $this->codeDefinition->asText( $this );
    }else{
        $s="";
    foreach($this->getChildren() as $child)
        $s .= $child->getAsText();
    return $s;
    }
}

CodeDefinition.php : Add function

/**
 * Accepts an ElementNode that is defined by this CodeDefinition and returns the content without markup of the element.
 * This can be overridden by a custom CodeDefinitions so that the content can be directly manipulated.
 * 
 * @param el the element to return a text only representation of
 * 
 * @return the parsed text without markup of this element (INCLUDING ITS CHILDREN)
 */  
public function asText( ElementNode $el )
{
        $s="";
    foreach($el->getChildren() as $child)
        $s .= $child->getAsText();
    return $s;
}

and inside your custom CodeDefinition class, add:

...    

public function asText( JBBCode\ElementNode $el )
{
    return 'Your Custom Text';
}

...

I'm testing it right now to see if there are issues.

Incorrectly displays url

[url=http://lostpix.com/?v=2018-02-04_qa1th9680k10zvlhcm8qr6zkt.png][img]http://lostpix.com/thumbs/2018-02/04/qa1th9680k10zvlhcm8qr6zkt.png[/img][/url]

<a href="http://lostpix.com/?v"><img src="http://lostpix.com/thumbs/2018-02/04/qa1th9680k10zvlhcm8qr6zkt.png" alt=""></a>

similey replacement & other text changes

i'm enjoying jbbcode :)

i just had to hack the core for my needs to do some replacements on plain text. i had to parse such plain text to put in smileys and do some automagic link creation stuff.

for such i had to change TextNode like this:

    /**
     * Returns the text string value of this text node.
     *
     * @return string
     */
    public function getValue()
    {
        // I know, it hurts ...
        if ( get_class($this->getParent()) == 'JBBCode\DocumentElement' )
        {
            return nl2br(autoLinkUsers(parseSmileys($this->value)));
        }
        else
        {
            return $this->value;
        }
    }

if there is a cleaner solution to do this i would like to know. if not it may be good option to allow such stuff via an official api.

cheers,
alexander

url tag doesn't handle https

The default url tag defintion ignores the https protocoll and set all urls to http. Escpecially for intern links on a website it's a problem, because all bbcode formatted texts link to http content and ignores if you are browsing the site via https.
Has anybody a quick solution for this problem?

Please create new releases

The last release v1.2.1 was created in August 2013. On jbbcode.com v1.2.0 is called the "most recent version".

I've install jbbcode through composer and have to use dev-master#e38ee2110eea20bc3b63ea753f8d404cec87bbb5 as dependency to have the latest bugfixes and support for multiple parameters. This is annoying.

Would it be possible to create a new version? Imho it's time for v1.3. What do you think?

Allow TextNodes to be split

This could possibly address #4 and help with #9:

There is currently no good way to cleanly split the content of a TextNode into serveral nodes after parsing. Doing so is vital when dealing with smileys and/or standalone links as they are likely to clash when it comes to processing them through dedicated filters. and masking them later through the HTMLSafeVisitor. A rather pain-free approach would be to allow TextNodes themselves have children, which would involve:

  1. moving the appropriate logic out of ElementNode into Node;
  2. allow TextNodes to be split at arbitrary positions through a public method (e.g.: TextNode.insertNodeAt(int $position, Node $node[, int $length=1])

A welcome side-effect were that DocumentNode could extend either TextNode or even Node directly instead of being a descendant of ElementNode.

Is it possible to create valid table code-set?

Yes it's easy to create bb-codes for table [table], [th], [tr], [td] with CodeDefinitionBuilder like this

//table
$builder = new CodeDefinitionBuilder('table', '<table>{param}</table>');
array_push($this->definitions, $builder->build());

//thead
$builder = new CodeDefinitionBuilder('th', '<th>{param}</th>');
array_push($this->definitions, $builder->build());

//tr
$builder = new CodeDefinitionBuilder('tr', '<tr>{param}</tr>');
array_push($this->definitions, $builder->build());

//td
$builder = new CodeDefinitionBuilder('td', '<td>{param}</td>');
array_push($this->definitions, $builder->build());

But how to create definitions to parse [tr] only if it's inside [table][/table], and parse [td] if it's inside [tr][/tr]

Any solutions?

Wrong evaluation with bracket inside a tag

Hi,

I've found a bug while parsing a [ bracket inside a tag e.g. [b]:-[ [/b]. I've written 3 tests to specify the error. You can find them in this commit.

    public function testBracketInTag()
    {
        $this->assertProduces('[b]:-[[/b]', '<strong>:-[</strong>');
    }

    public function testBracketWithSpaceInTag()
    {
        $this->assertProduces('[b]:-[ [/b]', '<strong>:-[ </strong>');
    }

    public function testBracketWithTextInTag()
    {
        $this->assertProduces('[b]:-[ foobar[/b]', '<strong>:-[ foobar</strong>');
    }

As you can see the test testBracketInTag() works fine. The other tests testBracketWithSpaceInTag() and testBracketWithTextInTag() fails with something like <strong>:-[ /b]</strong>.

Here is the result of running the tests:

$ phpunit .
PHPUnit 4.0.17 by Sebastian Bergmann.

..........................................FF.................

Time: 208 ms, Memory: 2.75Mb

There were 2 failures:

1) SimpleEvaluationTest::testBracketWithSpaceInTag
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'<strong>:-[ </strong>'
+'<strong>:-[ /b]</strong>'

[...]jBBCode/JBBCode/tests/SimpleEvaluationTest.php:28
[...]jBBCode/JBBCode/tests/SimpleEvaluationTest.php:99

2) SimpleEvaluationTest::testBracketWithTextInTag
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-'<strong>:-[ foobar</strong>'
+'<strong>:-[ foobar/b]</strong>'

[...]jBBCode/JBBCode/tests/SimpleEvaluationTest.php:28
[...]jBBCode/JBBCode/tests/SimpleEvaluationTest.php:104

FAILURES!
Tests: 61, Assertions: 99, Failures: 2.

I haven't take a look in the code so far. Is there a chance for a quick bugfix?

Allow function as parameter of setOptionValidator() & setBodyValidator()

I need a number validator(for a [size] tag).

I would be very nice to be able to do a simple setOptionValidator('is_numeric');

rather than having to wrap is_numeric() inside a class just to use it in this context

class sizeValidator implements \JBBCode\InputValidator
{
    public function validate($input)
    {
        return is_numeric($input)
    }
}

setOptionValidator(new sizeValidator());

Would also allow for anonymous function as argument

setOptionValidator(function($input) { return is_numeric($input) });

html code cant see in [code] bbcode

Hello guys,

I used same code like from site :

$message = $_POST['message'];

//bbcode
$parser = new JBBCode\Parser();
$parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());

$builder = new JBBCode\CodeDefinitionBuilder('img', '<img style="max-width:700px;" src="{param}">');
$parser->addCodeDefinition($builder->build());
$builder = new JBBCode\CodeDefinitionBuilder('code', '<pre>{param}</pre>');
$builder->setParseContent(false);
$parser->addCodeDefinition($builder->build());

$parser->parse($message);
$mbb = $parser->getAsHtml();`

And when i insert some text in table i cant see HTML code..
Something like :

Lorem

Result is only:Lorem..

Any help?

Need help creating custom CodeDefinition

Hi,

i want to creade BBCode which looks like this:

[insertimg imgid=22 style=left border=1 alt="alttext"]

Point is, instead of image url, i need image id so I can buildimage name (finally, I should read image info from database) and provide proper HTML markup to show that image.

I made more or less everything that I needed except, i cannot use this BBCode without closing tag [/insertimg]. i want to get rid of that closing tag. I read all I could and searched for answer but could not get it.

Basicaly, now I have to put tag in this form:
[insertimg imgid=22 style=left border=1 alt="alttext"][/insertimg]
but i want it to be simpler, this form:
[insertimg imgid=22 style=left border=1 alt="alttext"]

Here is my code:

class bbcInsertImg extends \JBBCode\CodeDefinition {



  public function __construct()  {
    $this->parseContent = false;
    $this->useOption = true;
    $this->setTagName('insertimg');
    $this->nestLimit = -1;
  }

  public function asHtml(\JBBCode\ElementNode $pElement) {

  $m_attributes = $pElement->getAttribute();

    if (isset ($m_attributes['imgid'])) {
      $img_url = $m_attributes['imgid'] . '.jpg';
    } else {
      $img_url = '';
    }

    $bodyHtml = '<img src="' . $img_url . '"';

    $bodyHtml .= $this->AttribToHTML($pElement, 'style');
    $bodyHtml .= $this->AttribToHTML($pElement, 'border');
    $bodyHtml .= $this->AttribToHTML($pElement, 'alt');    

    $bodyHtml .= '>';    

    return $bodyHtml;

  }

  private function AttribToHTML($pElement, $pAttrib, $pDefaultValue = '') {

    $m_attributes = $pElement->getAttribute();

    if (isset ($m_attributes[$pAttrib])) {
      $m_result = ' ' . $pAttrib . '="' . $m_attributes[$pAttrib] . '"';
    } else {
      if (strlen ($pDefaultValue) > 0) {
        $m_result = ' ' . $pAttrib . '="' . $pDefaultValue . '"';      
      } else {
        $m_result = '';
      }
    }
    return $m_result;
  }

}

Cannot parse tag split into several lines - offered solution

I found out that if I split long BBCode tag into several lines, jBBCode cannot parse properly.

I fixed it by simple change in Tokenizer.php

On line 31 there is a command:
array_push($this->tokens, substr($str, $strStart, $index - $strStart));

Replace it with:
array_push($this->tokens, trim(preg_replace('/\s+/', ' ', substr($str, $strStart, $index - $strStart))));

And that is all. After this fix you can split tag into several lines.

I hope someone could add this fix into the git source. I do not use git.

Uninitialized string offset with brackets

When someone enters for example

[ ABC ] 

the parser outputs this:

Notice: Uninitialized string offset: 0 in jBBCode\Parser.php on line 569

Notice: Uninitialized string offset: 0 in jBBCode\Parser.php on line 576

newline to <br>

Hello,

Would it be possible to replace all newlines with linebreaks? I load submitted content through this parser, but by default all the newlines submitted by users are ignored. To display them via HTML they must be replaced with
's

http://www.php.net/manual/en/function.nl2br.php could be used for this.

e.g. Add above https://github.com/jbowens/jBBCode/blob/master/JBBCode/Parser.php#L156
$str = nl2br($str);

However my PHP isn't all that great so there may be better ways to do this.

EDIT: I added it in a pull request.... First time I've done this hope I'm not messing things up lol :)

parseContent = false and unclosed bbcodes

If an unclosed bbcode appears within an element defined by a code definition that disallows parsing of its contents, the getAsBBCode output will close the unclosed bbcode. There is a test in ParseContentTest.php that illustrates this bug.

/**
 * Tests that when a tag is not closed within an unparseable tag,
 * the BBCode output does not automatically close that tag (because
 * the contents were not parsed).
 */
public function testUnclosedTag() {

    $parser = new JBBCode\Parser();
    $parser->addCodeDefinitionSet(new JBBCode\DefaultCodeDefinitionSet());
    $parser->addBBCode('verbatim', '{param}', false, false);

    $parser->parse('[verbatim]i wonder [b]what will happen[/verbatim]');
    $this->assertEquals('i wonder [b]what will happen', $parser->getAsHtml());
    $this->assertEquals('[verbatim]i wonder [b]what will happen[/verbatim]', $parser->getAsBBCode());
}

Currently parseContent is a misnomer. jBBCode actually constructs a parse tree of a node's children regardless of the parseContent property. parseContent currently only affects how getAsHTML recurs (whether it calls getAsHTML on the children or getAsBBCode.

The parser should be updated to actually avoid parsing the contents of elements when parseContent is false.

Unparse function

What about to create unparse method to replace html-tag pairs from "Code Definition Set" to BB-codes?
For example I'am parsing text to html before saving it to DB.
If i want to edit saved text, i need to store 2 versions of text in DB - parsed (getAsHtml()) and unparsed (getAsBBCode())

License clarification

You may want to include a note that the particular variant of MIT license you use may also be referred as the Expat License. Or specifically state MIT license as listed by the OSI to resolve any ambiguity.

I have seen both the Expat and X11 licenses referred as the MIT License, Expat seems to be the more common one as well as also the one used by OSI under the name MIT license.

I know the text is on the page, but when searching information on compatible licenses your license may be listed under Expat instead, as is done by f.ex. GNU.

Reference:
http://directory.fsf.org/wiki/License:Expat
http://directory.fsf.org/wiki/License:X11

Support for list tags

Enhancement suggestion: Support for list tags [li] and its various attributes as well a [*] which indicated each new list item.

Or is this currently possible some how?

How to encode?

Hola, estoy buscando una forma de poder codificar ya sea con urlencode o base64_encode, pero si uso una de las funciones me devuelve {option} y no la url que deseo.
¿Como puedo hacerlo?
=== Traduction ===
Hello, I'm looking for a way to be able to encode with either urlencode or base64_encode, but if I use one of the functions it returns me {option} and not the url that I want.
How can I do it?

Parse returns

Hello,

I'm trying to put jBBCode into a project of mine. For that, the code I've written fetches data from a database and puts that code through jBBCode, however, jBBCode seems to ignore returns completely. So text written in separate paragraphs make just a single paragraph. Is there any way to put every block of text between the p-tag in HTML without users having to put additional BBCode in their comments?

Thanks in advance.

Does not recognize [/color] end tag

Just try your example.

$text = "The default codes include: [b]bold[/b], [i]italics[/i], [u]underlining[/u], ";
$text .= "[url=http://jbbcode.com]links[/url], [color=red]color![/color] and more.";

$parser->parse($text);

print htmlentities($parser->getAsHtml());

Generates The default codes include: <strong>bold</strong>, <em>italics</em>, <u>underlining</u>, <a href="http://jbbcode.com">links</a>, <span style="color: red">color![/color] and more.</span>

Adjacent text nodes

Currently, jBBCode makes no guarantees about consecutive, uninterrupted text being in the same text node. The parser will sometimes create adjacent text nodes. This isn't a problem, but it can make text manipulation through the NodeVisitor more difficult. It might be nice if after parsing, we traverse the graph and collapse adjacent text nodes into a single text node with the concatenated values.

color option validator

Right now you can enter arbitrary strings as the color for the default [color] bbcode. This could allow arbitrary CSS styles to be applied or worse, arbitrary javascript to be executed on an event. The [color] bbcode needs an InputValidator for its color option.

Problem with Composer/PHP Autoload Path and psr-0

There is a problem with the way that composer generates the autoload path for this class that causes the class to not be found.

Steps to reproduce:

  1. Create a new/blank folder
  2. Install jbbcode/jbbcode from pagagist via composer-
    php composer.phar require jbbcode/jbbcode
  3. Create a simple index.php
    include 'vendor/autoload.php';
    $parser = new JBBCode\Parser.php;
  1. Load the file, see the error:
    Fatal error: Class 'JBBCode\Parser' not found in /home/user/html/test/index.php on line 4

I played around with it a bit and I was able to fix it by creating a subfolder to the install folder called JBBCode and moving all of the files except composer.json there.
IE:

vendor/
    jbbcode/
         jbbcode/
              composer.json
              JBBCode/
                    Parser.php
                    ...

I can't figure out why this is, since psr-0 seems to suggest that the files should go in the vendor/jbbcode/jbbcode folder. Any way you slice it, though, something is funky.

Tags without closing

How to define for example the tag [hr] to replace with


? Without closing tag.

Class 'JBBCode\Parser' not found in Laravel

I installed the (newly refreshed) v1.2.0 of JBBCode from packagist in my instance of Laravel via composer. It appeared to install correctly, but I am unable to instantiate the parser (or any other) of the classes in the JBBCode namespace.

My vendor/composer/autoload_namespaces.php file appears correct:

    return array(
        'JBBCode' => array($vendorDir . '/jbbcode/jbbcode'),
    );

My instantiation in a controller is just:

    $parser = new JBBCode\Parser();

I consistently get an error of "Class 'JBBCode\Parser' not found"

I don't appear to be doing anything else weird or wrong. Have you tested this against a Laravel install?

Change value of Option

Is there a way to change the value of the option

Example:
I am using SCEditor to create my BBCode. In the editor it has font size which is create a bbcode tag of
[size=4]this is font size 4 ie 18px [/size]

Now I want JBBCode to read the 4 and then validate it, and then return the correct font size value in the validation function which is then placed in the html render.
eg.

style="font-size:18px">this is font size 4 ie 18px

However I keep getting

style="font-size:4px">this is font size 4 ie 18px

How do I change the option value for a new value.

I am using JBBCode to read this size using...
$builder = new CodeDefinitionBuilder('size', '

{param}

');
$builder->setUseOption(true)->setOptionValidator(new \JBBCode\validators\FontValidator());
array_push($this->definitions, $builder->build());

My fontValidator is...
public function validate($input)
{
if (is_numeric($input) && $input <= 7 && $input >= 1) {
switch ($input) {
case 1:
return 10;
break;
case 2:
return 13;
break;
case 3:
return 16;
break;
case 4:
return 18;
break;
case 5:
return 24;
break;
case 6:
return 32;
break;
case 7:
return 48;
break;
}
} else {
return 16;
}
}

Thank you so much if you help me

multiple tag options

Hi. Hope that great project is still maintained...
I was hopping to add a support for multiple tag options, specifically for img ALT text in format of:
[img alt="text" width="100" height="200"]url[/img]

Defined CodeDefinition class and start playing with the code.
Unfortunately the parser didn't get to my code since the tag name is assumed to be up to the "]" character or the "=" where the assumption is that the format will always be [tag=option].
/* There could be an attribute. */
$tagPieces = explode('=', $tagContent);
$tmpTagName = $tagPieces[0];

Before I deep dive into the parser code...
Is there anything that was already done in that direction?

Thanks.

How to skip parsing inside javascript tags

I have some html with javasript tag

<script> var i = 1; var arr = [1,2,3] var failed_variable = arr[i]; // this was replaced with arr<em> </script>

How to skip this replacion?

Remove Deprecated Methods in CodeDefinition Class

The methods incrementCounter(), decrementCounter(), resetCounter(), and getCounter() have been marked as deprecated for quite some time now and as far as I can tell, they are no longer touched by any code paths and are skewing code coverage statistics. I'd like to see them either removed or added to the code coverage blacklist. Thoughts?

Also, there's still setUseOption() and setParseContent(): These two do alter the behaviour of a CodeDefinition but are likewise marked as deprecated. What about them?

Getting list of all CodeDefinitions

I needed list of all code definitions Parser can handle, but could not find a way to get it.

I suggest expanding class Parser with something like this:

public function getCodeDefinitions() {
  return $this->bbcodes;
}

Extended Characters

It seems that some extended characters cause the whole things to fail without error and return null when calling getAsHtml();

For example: ’

convert bbcode to html

getAsBBCode() does not work for any code.

$parser->parse("<strong>wrgerege</strong>"); print($parser->getAsBBCode());

Support for CodeDefinition aliasing

Hi,

I have created a class Definition_Video extending CodeDefinition to support the [video] tag. The Definition_Video parse urls from vimeo.com, dailymotion.com and youtube.com.

Now I want support the [youtube] tag for BC and I created the Definition_Youtube class:

class Definition_Youtube extends Definition_Video
{

    public function __construct()
    {
        parent::__construct();

        $this->setTagName('youtube');
    }

}

and add the classes to the parser.

$parser->addCodeDefinition(new Definition_Video());
$parser->addCodeDefinition(new Definition_Youtube());

This works fine for me, but I have a lot more tag aliases and have to create a lot of classes. I wish to do something like this:

$definition = new Definition_Video();
$defintion->addAliasTagName('youtube');

$parser->addCodeDefinition($definiton);

I have also seen the deprecated CodeDefinition::setTagName() method, that allows easy aliasing as well:

$definition = new Definition_Video();
$parser->addCodeDefinition($definiton);

$defintion->setTagName('youtube');
$parser->addCodeDefinition($definiton);

Is there a reason why CodeDefinition::setTagName() method is marked as deprecated? Or is it possible to add an aliasing funtionality?

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.