Class BBCode

This is the BBCode Library class, it is responsible for most of the internal parsing of the input into HTML.

Hierarchy

  • BBCode

Constructors

Properties

Methods

addEmoji addRule autoDetectURLs cleanupWSByEatingInput cleanupWSByIteratingPointer cleanupWSByPoppingStack clearEmoji clearRules collectText collectTextReverse computeCurrentClass doEnhancedTag doLimit doTag dumpStack fillTemplate finishTag fixupOutput generateOutput getAllowAmpersand getAllowEscape getDebug getDefaultEmoji getDefaultEmojiDir getDefaultEmojiURL getDefaultEmojis getDefaultLocalImgDir getDefaultLocalImgURL getDefaultRule getDefaultRuleHTML getDefaultRules getDefaultWikiURL getDetectURLs getEmailTemplate getEmoji getEmojiDir getEmojiURL getEnableEmoji getEscapeContent getIgnoreNewlines getLimit getLimitPrecision getLimitTail getLocalImgDir getLocalImgURL getLogLevel getMaxEmoji getPlainMode getPostTrim getPreTrim getQuoteTemplate getRoot getRule getRuleHTML getTagMarker getURLPattern getURLTarget getURLTargetable getURLTemplate getWikiURL getWikiURLTemplate htmlEncode isValidEmail isValidTLD isValidURL limitText nl2br parse parseEndTagToken parseStartTagToken processEmoji processIsolatedTag processVerbatimTag rebuildEmoji removeEmoji removeRule rewindToClass setAllowAmpersand setAllowEscape setDebug setDefaultEmoji setDefaultEmojis setDefaultRule setDefaultRules setDetectURLs setEmailTemplate setEmojiDir setEmojiURL setEnableEmoji setEscapeContent setIgnoreNewlines setLimit setLimitPrecision setLimitTail setLocalImgDir setLocalImgURL setLogLevel setMaxEmoji setPlainMode setPostTrim setPreTrim setQuoteTemplate setRoot setRootBlock setRootInline setRuleHTML setTagMarker setURLPattern setURLTarget setURLTargetable setURLTemplate setWikiURL setWikiURLTemplate unHTMLEncode updateParamsForMissingEndTag wikify

Constructors

  • Initialize a new instance of the BBCode class.

    Parameters

    • Optional library: BBCodeLibrary

      The BBCode Library Class, It's possible to create your own via extending BBCodeLibrary

    Returns BBCode

Properties

allowAmpersand: boolean

If true, we use String.replaceAll() instead of htmlEncode().

allowEscape: boolean

Whether to allow Escape Characters in parsing to prevent parsing specific tags or not

currentClass: ClassType

The current class (auto-computed).

debug: boolean

Enable debugging mode

defaults: BBCodeLibrary

The standard library (an instance of class BBCodeLibrary).

detectURLs: boolean

Should we audo-detect URLs and convert them to links?

emailTemplate: string

The default template used with the default [email] tag.

emoji: any

The current list of emoji.

emojiDir: string

The host filesystem path to emoji (should be an absolute path).

emojiEnabled: boolean

Whether or not to perform emoji-parsing.

emojiRegex: any

This is a regex, precomputed from the list of emoji above.

emojiUrl: string

The URL path to emoji (possibly a relative path).

escapeContent: boolean

Encode HTML. POTENTIALLY DANGEROUS IF DISABLED. ONLY DISABLE IF YOU KNOW WHAT YOURE DOING.

ignoreNewlines: any

If true, newlines will be treated as normal whitespace.

BBCodeLexer created when calling parse

limitPrecision: number

How accurate should we be if we're cutting off text?

limitTail: string

What to add if the output is cut off.

localImgDir: string

The host filesystem path to local images (should be an absolute path).

localImgUrl: string

The URL path to local images (possibly a relative path).

lostStartTags: Record<string, number>

For repair when tags are badly mis-nested.

maxEmoji: number

Maximum number of emoji that can be used in parse

outputLimit: number

The maximum number of text characters to output.

plainMode: boolean

Don't output tags: Just output text/whitespace/newlines only.

postTrim: string

How to trim the whitespace at the end of the input.

preTrim: string

How to trim the whitespace at the start of the input.

quoteTemplate: string

The default template used with the default [quote] tag.

rootClass: ClassType

The root container class.

ruleHtml: any

The default HTML to output for a [rule] tag.

stack: StackType[]

The token stack is used to perform a document-tree walk

startTags: Record<string, number[]>

An associative array of locations of start tags on the stack.

tagMarker: string

Set to '[', '<', '{', or '('.

tagRules: Record<string, TagRules>

List of tag rules currently in use.

textLength: number

The number of text characters output so far.

urlPattern: string

What to convert auto-detected URLs into.

urlTarget: string | boolean

If non-false, [url] tags will use this target and no other.

urlTargetable: boolean

If true, [url] tags can accept a target="..." parameter.

urlTemplate: string

The default template used with the default [url] tag.

wasLimited: boolean

Set to true if the output was cut off.

wikiUrl: string

URL prefix used for [[wiki]] links.

wikiUrlTemplate: string

The default template used when rendering wiki links.

BBCODE_RELEASE: string = '2023-08-16'

Current release date

BBCODE_VERSION: string = version

Current version number

Methods

  • Adds an emoji to the parser

    Parameters

    • code: string

      Name for the Emoji

    • image: string

      Image file

    Returns BBCode

  • Search through the input for URLs, or things that are URL-like and replace with anchor tags.

    We search for several possibilities here:

    First format (HTTP/HTTPS/FTP): <"http://" or "https://" or "ftp://">

    Second format (implicit HTTP):

    Third format (e-mail): "@"

    In short, we look for domains and protocols, and if we find them, we consume any paths or parameters after them, stopping at the first whitespace.

    We use the same split-and-match technique used by the lexer and the emoji parser, since it's the fastest way to perform tokenization in PHP.

    Once we find the URL, we convert it according to the rule given in this.urlPattern.

    Note that the input string is plain text, not HTML or BBCode. The return value must be an array of alternating pairs of plain text (even indexes) and HTML (odd indexes).

    Parameters

    • string: string

      The string to detect the URLs in.

    Returns any[]

    Returns an array in the form [text, anchor, text, anchor, ...].

  • Read tokens from the input, and remove whitespace/newline tokens from the input according to the rules in the given pattern.

    Parameters

    • Optional pattern: string

      Pattern for cleanup

    Returns void

  • Read tokens from the given position in the stack, going forward as we match the rules in the given pattern. Returns the first position after the pattern.

    Parameters

    • pattern: string

      Pattern for cleanup

    • pos: number

      Position to start the cleanup

    • array: StackType[]

      Stack to cleanup

    Returns number

  • Walk down from the top of the stack, and remove whitespace/newline tokens from the top according to the rules in the given pattern.

    Parameters

    • pattern: string

      Pattern for cleanup

    • array: StackType[]

      Array to cleanup

    Returns void

  • Collect a series of text strings from a token stack and return them as a single string.

    Parameters

    • array: StackType[]

      The token stack.

    • start: number = 0

      The starting index in array to process.

    Returns string

    Returns the stack text from all the elements in the stack.

  • Collect a series of text strings from a token stack in reverse and return them as a single string.

    Parameters

    • array: StackType[]

      The token stack.

    • start: number = 0

      The starting index in array to process.

    • end: number = 0

      The ending index in array to process.

    Returns string

    Returns the stack text from all the elements in the stack.

  • Format an enhanced tag, which is like a simple tag but uses a short HTML template for its formatting instead.

    The variables you may use are the parameters of the tag, and '_default' for its default value, '_name' for its name, and 'content' for its contents (body). Note that in enhanced mode, the tag parameters' keys must match [a-zA-Z0-9:-]+, that is, alphanumeric, with underscore, colon, or hyphen.

    Parameters

    Returns string

  • If we've reached the text limit, clean up the stack, push the limit tail, set the we-hit-the-limit flag, and return.

    Returns void

  • Process a tag:

    action is one of BBCODE_CHECK or BBCODE_OUTPUT. During BBCODE_CHECK, contents will always be the empty string, and this function should return true if the tag is legal based on the available information; or it should return false if the tag is illegal. During BBCODE_OUTPUT, contents will always be valid, and this function should return HTML.

    tagName is the name of the tag being processed.

    defaultValue is the default value given; for example, in [url=foo], it's "foo"+ This value has NOT been passed through htmlEncode().

    params is an array of key: value parameters associated with the tag; for example, in [emoji src=smile alt=:-)], it's ['src': "smile", 'alt': ":-)"]. These keys and values have NOT beel passed through htmlEncode().

    contents is the body of the tag during BBCODE_OUTPUT. For example, in [b]Hello[/b], it's "Hello"+ THIS VALUE IS ALWAYS HTML, not BBCode.

    For BBCODE_CHECK, this must return true (if the tag definition is valid) or false (if the tag definition is not valid); for BBCODE_OUTPUT, this function must return HTML output.

    Parameters

    Returns any

  • Fill an HTML template using variable inserts, which look like this: {$variable} or {$variable/flags} or even {$myarray.george.father/flags}

    You may use any variable provided in the parameter array; and you may use the special dot (.) operator to access members of array variables or of object variables.

    You may add formatting flags to the variable to control how the text parameters are cleaned up. For example, {$variable/u} causes the variable to be urlencoded(). The available flags are:

    v - Verbatim. Do not apply any formatting to the variable; use its exact text, however the user provided it. This overrides all other flags.

    b - Apply basename(). n - Apply nl2br(). t - Trim. This causes all initial and trailing whitespace to be trimmed (removed). w - Clean up whitespace. This causes all non-newline whitespace, such as control codes and tabs, to be collapsed into individual space characters.

    e - Apply HTMLEncode(). h - Apply htmlEncode(). k - Apply Wikify(). u - Apply urlencode().

    Note that only one of the e, h, k, or u "formatting flags" may be specified; these flags are mutually-exclusive.

    Parameters

    • template: string

      Template string

    • inserts: boolean | TagType

      Inserts Array

    • defaults: Record<string, string> = {}

      Default Value Object

    Returns string

  • Parameters

    • tagName: string

    Returns string | false

  • Properly encode tag content.

    Go through a string containing plain text and do three things on it: Replace < and > and & and " with HTML-safe equivalents, and replace emoji like :-) with tags, and replace any embedded URLs with ... links.

    Parameters

    • string: string

      The string to process.

    Returns string

    Returns the processed version of string.

  • Output everything on the stack from pos to the top, inclusive, as plain text, and return it.

    This is a little more complicated than necessary, because if we encounter end-tag-optional tags in here, they're not to be outputted as plain text: They're fully legit, and need to be processed with the plain text after them as their body. This returns a list of tokens in the REVERSE of output order.

    Parameters

    • pos: number

      The position to start on the stack.

    Returns StackType[]

    Returns an array of output tokens.

  • Get if Ampersand should be allowed or not.

    Returns boolean

  • Get if escape characters are allowed

    Returns boolean

  • Get if Debug mode is enabled

    Returns boolean

  • Get an Emoji from the Default Emoji List.

    Parameters

    • code: string

      Emoji Name

    Returns string | false

  • Get the default emoji directory

    Returns string

  • Get the default emoji URL

    Returns string

  • Get the default local image Directory

    Returns string

  • Get the default local img URL

    Returns string

  • Gets a rule from the default rules list

    Parameters

    • name: string

      Rule to get from the defaults

    Returns false | TagRules

  • Gets the default Rule HTML

    Returns string

  • Get the default wiki URL

    Returns string

  • Get if URL Detection is enabled

    Returns boolean

  • Get the current email template

    Returns string

  • Get an Emoji from the defined emoji, returns false if nothing found.

    Parameters

    • code: string

      Emoji Name

    Returns any

  • Get the current Emoji Directory

    Returns string

  • Get the current Emoji URL

    Returns string

  • Get if Emoji parsing is enabled.

    Returns boolean

  • Get the current value of escapeContent.

    Returns boolean

  • Get if newlines are ignored.

    Returns any

  • Get the current maximum output limit.

    Returns number

  • Get the current Limit Tail

    Returns string

  • Get the current local image directory

    Returns string

  • Get the current local img URL

    Returns string

  • Get the Max Emoji amount.

    Returns number

  • Get if plain mode is enabled

    Returns boolean

  • Get the current template to use for quote tags

    Returns string

  • Returns the current Rule HTML

    Returns any

  • Get the current Tag Marker

    Returns string

  • Get the current URL Pattern

    Returns string

  • Get the current forced url target

    Returns string | boolean

  • Whether [url] tags acan accept a target="..." parameter

    Returns boolean

  • Get the current URL Template

    Returns string

  • Get the current Wiki URL

    Returns string

  • Get the current wiki template

    Returns string

  • Escape HTML characters.

    This function is used to wrap around calls to htmlEncode() for plain text so that you can add your own text-evaluation code if you want. For example, you might want to make foo turn into foo, or something like that. The default behavior is just to call htmlEncode() and be done with it, but if you inherit and override this function, you can do pretty much anything you want.

    Note that htmlEncode() is still used directly for doing things like cleaning up URLs in tags; this function is applied to plain text only.

    Parameters

    • string: string

      The string to replace.

    Returns string

    Returns an encoded version of string.

  • Returns true if the given string is a valid e-mail address.

    This allows everything that RFC821 allows, including e-mail addresses that make no sense.

    Parameters

    • string: string

      The email address to validate.

    Returns boolean

    Returns true if string is an email address or false otherwise.

  • Check that a host name has a valid top level domain.

    Parameters

    • host: string

      The host or TLD to check.

    • allowIPs: boolean = false

      Whether or not IPv4 strings should count as valid.

    Returns boolean

    Returns true if host has a valid TLD or false otherwise.

  • Returns true if the given string is a valid URL.

    If emailToo is false, this checks for:

    http :// domain [:port] [/] [any single-line string]
    https :// domain [:port] [/] [any single-line string]
    ftp :// domain [:port] [/] [any single-line string]

    If emailToo is true (the default), this also allows the mailto protocol:

    mailto : name @ domain
    

    Parameters

    • string: string

      The URL to validate.

    • emailToo: boolean = true

      Whether or not a mailto: link is also valid.

    Returns boolean

    Returns true if string is a valid URL or false otherwise.

  • We have a string that's too long, so chop it off at a suitable break so that it's no longer than limit characters, if at all possible (if there's nowhere to break before that, we just chop at limit).

    Parameters

    • string: string

      String to limit text length

    • limit: number

      Maximum text length

    Returns string

  • Converts Windows, Unix, or Mac newlines to a
    , and regularizes the output to just use Unix-style newlines to boot.

    Parameters

    • string: string

    Returns string

  • Parse a BBCode string and convert it into HTML.

    Core parser. This is where all the magic begins and ends. Core parsing routine. Call with a BBCode string, and it returns an HTML string.

    Parameters

    • string: string

      The BBCode string to parse.

    Returns string

    Returns the HTML version of string.

  • Called when the parser has read a this.BBCODE_ENDTAG token.

    Returns void

  • Called when the parser has read a Token.BBCODE_TAG token.

    Returns void

  • Replace the emoji codes in a string with image tags.

    Go through a string containing plain text and do two things on it: Replace < and > and & and " with HTML-safe equivalents, and replace emoji like :-) with tags.

    Parameters

    • string: string

      The string to process.

    Returns string

    Returns the processed version of string.

  • Process an isolated tag, a tag that is not allowed to have an end tag.

    Parameters

    • tagName: string

      The name of the tag.

    • tagParams: boolean | TagType

      All of the parameters passed to the tag.

    • tagRule: TagRules

      The rule governing the tag.

    Returns void

  • Process a verbatim tag, a tag whose contents (body) must not be processed at all.

    Parameters

    • tagName: string

      The name of the tag.

    • tagParams: boolean | TagType

      All of the parameters passed to the tag.

    • tagRule: TagRules

      The rule governing the tag.

    Returns void

  • We're transitioning into a class that's not allowed inside the current one (like they tried to put a [center] tag inside a [b] tag), so we need to unwind the stack, outputting content until we're inside a valid state again. To do this, we need to walk back down the stack, searching for a class that's in the given list; when we find one, we output everything above it. Then we output everything on the stack from the given height to the top, inclusive, and pop everything in that range. This leaves a BBCODE_TEXT element on the stack that is the fully-outputted version of the content, and its class will be the same as that of the stack element before it (or root_class if there is no element before it).

    This returns true if the stack could be rewound to a safe state, or false if no such "safe state" existed.

    Parameters

    • classList: string[]

    Returns boolean

  • Set if the parser should allow Ampersand or not.

    Parameters

    • enable: boolean = true

    Returns BBCode

  • Set Debug mode, if enabled it will log debug events.

    Parameters

    • enable: boolean = true

      Whether to enable debug mode or not

    Returns BBCode

    Default

    true
    
  • Reset an emoji from the defaultEmoji list.

    Parameters

    • code: string

      Emoji Name

    Returns BBCode

  • Resets a rule by name from the default tag rules.

    Parameters

    • name: string

      Rule to change to default

    Returns void

  • Set the template to use for emails

    Parameters

    • template: string

      template html

    Returns BBCode

  • Sets whether emoji should be enabled, when enabled emoji like ":)" will be turned into an HTML image.

    Parameters

    • enable: boolean = true

      Whether emoji should be enabled

    Returns BBCode

    Default

    true
    
  • Set whether content should be escaped or not. POTENTIALLY DANGEROUS IF DISABLED. ONLY DISABLE IF YOU KNOW WHAT YOURE DOING.

    Parameters

    • escapeContent: boolean

    Returns BBCode

  • Sets whether the parser should ignore newlines or not.

    Parameters

    • ignore: boolean = true

      Whether to ignore newlines

    Returns BBCode

  • Set the maximum amount of output characters before the output gets cut off

    Parameters

    • limit: number = 0

      maximum characters

    Returns BBCode

  • Set what gets appended to the end of a string when the string is too long.

    Parameters

    • tail: string = "..."

      What to append

    Returns BBCode

  • Set the directory path to local images

    Parameters

    • path: string

      directory path

    Returns BBCode

  • Set the URL path to use for local images

    Parameters

    • path: string

      url path

    Returns BBCode

  • Set the maximum amount of emoji that can be parsed in a single string.

    Parameters

    • count: number

      Maximum Emoji

    Returns BBCode

  • If plain mode is enabled, it will only output the values as defined in the plain_start and plain_end in the Tag Library, see TagRules

    Parameters

    • enable: boolean = true

      Enable or Disable Plain Mode

    Returns BBCode

    Default

    true
    
  • Controls how (non-newline) whitespace and newlines are treated when placed in proximity to this tag or to its end tag. For each setting, you use a simple pattern comprised of the following characters to describe what to remove:

    • s: Remove any non-newline whitespace found.
    • n: Remove a single newline, if one exists.
    • a: Remove as many spaces and newlines as are found.

    Common Examples:

    • s: Remove all non-newline whitespace
    • sn: Remove all non-newline whitespace, then a single newline if it exists.
    • ns: Remove a single newline if it exists, then all non-newline whitespace.
    • sns: Remove all non-newline whitespace, then a single newline if it exists, then any non-newline whitespace found past that newline.

    Parameters

    • trim: string = "a"

    Returns BBCode

  • Controls how (non-newline) whitespace and newlines are treated when placed in proximity to this tag or to its end tag. For each setting, you use a simple pattern comprised of the following characters to describe what to remove:

    • s: Remove any non-newline whitespace found.
    • n: Remove a single newline, if one exists.
    • a: Remove as many spaces and newlines as are found.

    Common Examples:

    • s: Remove all non-newline whitespace
    • sn: Remove all non-newline whitespace, then a single newline if it exists.
    • ns: Remove a single newline if it exists, then all non-newline whitespace.
    • sns: Remove all non-newline whitespace, then a single newline if it exists, then any non-newline whitespace found past that newline.

    Parameters

    • trim: string = "a"

    Returns BBCode

  • Set the template to use for quote tags

    Parameters

    • template: string

    Returns BBCode

  • Sets the HTML to use when converting a rule tag

    Parameters

    • html: any

      HTML for Rule tag

    Returns BBCode

  • Sets the URL pattern for a URL, example: <a href="{$url/h}" class="bbcode_url"{$target/v}>{$content/v}</a>

    Parameters

    • pattern: any

      The HTML pattern for a URL

    Returns BBCode

  • If non-false, [url] tags will use this target and no other.

    Parameters

    • target: any

    Returns BBCode

  • If true, [url] tags can accept a target="..." parameter.

    Parameters

    • enable: boolean

    Returns BBCode

  • Get the wiki URL use for wiki tags and replacements

    Parameters

    • url: string

      URL to use for wikis

    Returns BBCode

  • Set the the default template used when rendering wiki links.

    Parameters

    • template: string

    Returns BBCode

  • This function comes from the html_entities module

    Parameters

    • string: string

      The string to be decoded

    Returns string

  • If an end-tag is required/optional but missing, we simulate it here so that the rule handlers still see a valid '_endtag' parameter. This way, all rules always see valid '_endtag' parameters except for rules for isolated tags.

    Parameters

    Returns void

  • This takes an arbitrary string and makes it a wiki-safe string: It converts all characters to be within [a-zA-Z0-9'",.:_-] by converting everything else to _ characters, compacts multiple _ characters together, and trims initial and trailing _ characters. So, for example, [[Washington, D.C.]] would become "Washington_D.C+", safe to pass through a URL or anywhere else. All characters in the extended-character range (0x7F-0xFF) will be URL-encoded.

    Parameters

    • string: string

    Returns string

Generated using TypeDoc