cleanup and update of jquery-colorpicker dependency

This commit is contained in:
Darko Luketic 2021-11-29 01:25:11 +01:00
parent 665970e71a
commit d02db09056
63 changed files with 13398 additions and 4845 deletions

View File

@ -1,13 +0,0 @@
{
"folders":
[
{
"follow_symlinks": true,
"path": ".",
"folder_exclude_patterns": [
"min",
"trans"
]
}
]
}

View File

@ -1,18 +1,21 @@
<?php
require_once ('global.php');
require_once (CRAYON_RESOURCE_PHP);
require_once('global.php');
require_once(CRAYON_RESOURCE_PHP);
/* Manages fonts once they are loaded. */
class CrayonFonts extends CrayonUserResourceCollection {
// Properties and Constants ===============================================
const DEFAULT_FONT = 'monaco';
const DEFAULT_FONT_NAME = 'Monaco';
class CrayonFonts extends CrayonUserResourceCollection
{
// Properties and Constants ===============================================
// Methods ================================================================
const DEFAULT_FONT = 'monaco';
const DEFAULT_FONT_NAME = 'Monaco';
function __construct() {
$this->set_default(self::DEFAULT_FONT, self::DEFAULT_FONT_NAME);
// Methods ================================================================
function __construct()
{
$this->set_default(self::DEFAULT_FONT, self::DEFAULT_FONT_NAME);
$this->directory(CRAYON_FONT_PATH);
$this->relative_directory(CRAYON_FONT_DIR);
$this->extension('css');
@ -30,7 +33,6 @@ class CrayonFonts extends CrayonUserResourceCollection {
}
CrayonLog::debug($this->directory());
CrayonLog::debug($this->user_directory());
}
}
}
?>

View File

@ -629,5 +629,3 @@ class CrayonFormatter {
return ' ' . $dim_mode . ': ' . $hl->setting_val($name) . $dim_unit . ';';
}
}
?>

View File

@ -1,423 +1,449 @@
<?php
// Class includes
require_once ('global.php');
require_once (CRAYON_PARSER_PHP);
require_once (CRAYON_FORMATTER_PHP);
require_once (CRAYON_SETTINGS_PHP);
require_once (CRAYON_LANGS_PHP);
require_once('global.php');
require_once(CRAYON_PARSER_PHP);
require_once(CRAYON_FORMATTER_PHP);
require_once(CRAYON_SETTINGS_PHP);
require_once(CRAYON_LANGS_PHP);
/* The main class for managing the syntax highlighter */
class CrayonHighlighter {
// Properties and Constants ===============================================
private $id = '';
// URL is initially NULL, meaning none provided
private $url = NULL;
private $code = '';
private $formatted_code = '';
private $title = '';
private $line_count = 0;
private $marked_lines = array();
private $range = NULL;
private $error = '';
// Determine whether the code needs to be loaded, parsed or formatted
private $needs_load = FALSE;
private $needs_format = FALSE;
// Record the script run times
private $runtime = array();
// Whether the code is mixed
private $is_mixed = FALSE;
// Inline code on a single floating line
private $is_inline = FALSE;
private $is_highlighted = TRUE;
// Objects
// Stores the CrayonLang being used
private $language = NULL;
// A copy of the current global settings which can be overridden
private $settings = NULL;
// Methods ================================================================
function __construct($url = NULL, $language = NULL, $id = NULL) {
if ($url !== NULL) {
$this->url($url);
}
if ($language !== NULL) {
$this->language($language);
}
// Default ID
$id = $id !== NULL ? $id : uniqid();
$this->id($id);
}
/* Tries to load the code locally, then attempts to load it remotely */
private function load() {
if (empty($this->url)) {
$this->error('The specified URL is empty, please provide a valid URL.');
return;
}
// Try to replace the URL with an absolute path if it is local, used to prevent scripts
// from executing when they are loaded.
$url = $this->url;
if ($this->setting_val(CrayonSettings::DECODE_ATTRIBUTES)) {
$url = CrayonUtil::html_entity_decode($url);
}
$url = CrayonUtil::pathf($url);
$site_http = CrayonGlobalSettings::site_url();
$scheme = parse_url($url, PHP_URL_SCHEME);
// Try to replace the site URL with a path to force local loading
if (empty($scheme)) {
// No url scheme is given - path may be given as relative
$url = CrayonUtil::path_slash($site_http) . CrayonUtil::path_slash($this->setting_val(CrayonSettings::LOCAL_PATH)) . $url;
}
$http_code = 0;
// If available, use the built in wp remote http get function.
if (function_exists('wp_remote_get')) {
$url_uid = 'crayon_' . CrayonUtil::str_uid($url);
$cached = get_transient($url_uid, 'crayon-syntax');
CrayonSettingsWP::load_cache();
if ($cached !== FALSE) {
$content = $cached;
$http_code = 200;
} else {
$response = @wp_remote_get($url, array('sslverify' => false, 'timeout' => 20));
$content = wp_remote_retrieve_body($response);
$http_code = wp_remote_retrieve_response_code($response);
$cache = $this->setting_val(CrayonSettings::CACHE);
$cache_sec = CrayonSettings::get_cache_sec($cache);
if ($cache_sec > 1 && $http_code >= 200 && $http_code < 400) {
set_transient($url_uid, $content, $cache_sec);
CrayonSettingsWP::add_cache($url_uid);
}
}
} else if (in_array(parse_url($url, PHP_URL_SCHEME), array('ssl', 'http', 'https'))) {
// Fallback to cURL. At this point, the URL scheme must be valid.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// For https connections, we do not require SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, FALSE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
if (isset($_SERVER['HTTP_USER_AGENT'])) {
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
}
$content = curl_exec($ch);
$error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
}
if ($http_code >= 200 && $http_code < 400) {
$this->code($content);
} else {
if (empty($this->code)) {
// If code is also given, just use that
$this->error("The provided URL ('$this->url'), parsed remotely as ('$url'), could not be accessed.");
}
}
$this->needs_load = FALSE;
}
/* Central point of access for all other functions to update code. */
public function process() {
$tmr = new CrayonTimer();
$this->runtime = NULL;
if ($this->needs_load) {
$tmr->start();
$this->load();
$this->runtime[CRAYON_LOAD_TIME] = $tmr->stop();
}
if (!empty($this->error) || empty($this->code)) {
// Disable highlighting for errors and empty code
return;
}
if ($this->language === NULL) {
$this->language_detect();
}
if ($this->needs_format) {
$tmr->start();
try {
// Parse before hand to read modes
$code = $this->code;
// If inline, then combine lines into one
if ($this->is_inline) {
$code = preg_replace('#[\r\n]+#ms', '', $code);
if ($this->setting_val(CrayonSettings::TRIM_WHITESPACE)) {
$code = trim($code);
}
}
// Decode html entities (e.g. if using visual editor or manually encoding)
if ($this->setting_val(CrayonSettings::DECODE)) {
$code = CrayonUtil::html_entity_decode($code);
}
// Save code so output is plain output is the same
$this->code = $code;
// Allow mixed if langauge supports it and setting is set
CrayonParser::parse($this->language->id());
if (!$this->setting_val(CrayonSettings::MIXED) || !$this->language->mode(CrayonParser::ALLOW_MIXED)) {
// Format the code with the generated regex and elements
$this->formatted_code = CrayonFormatter::format_code($code, $this->language, $this);
} else {
// Format the code with Mixed Highlighting
$this->formatted_code = CrayonFormatter::format_mixed_code($code, $this->language, $this);
}
} catch (Exception $e) {
$this->error($e->message());
return;
}
$this->needs_format = FALSE;
$this->runtime[CRAYON_FORMAT_TIME] = $tmr->stop();
}
}
/* Used to format the glue in between code when finding mixed languages */
private function format_glue($glue, $highlight = TRUE) {
// TODO $highlight
return CrayonFormatter::format_code($glue, $this->language, $this, $highlight);
}
class CrayonHighlighter
{
// Properties and Constants ===============================================
private $id = '';
// URL is initially NULL, meaning none provided
private $url = NULL;
private $code = '';
private $formatted_code = '';
private $title = '';
private $line_count = 0;
private $marked_lines = array();
private $range = NULL;
private $error = '';
// Determine whether the code needs to be loaded, parsed or formatted
private $needs_load = FALSE;
private $needs_format = FALSE;
// Record the script run times
private $runtime = array();
// Whether the code is mixed
private $is_mixed = FALSE;
// Inline code on a single floating line
private $is_inline = FALSE;
private $is_highlighted = TRUE;
/* Sends the code to the formatter for printing. Apart from the getters and setters, this is
the only other function accessible outside this class. $show_lines can also be a string. */
function output($show_lines = TRUE, $print = TRUE) {
$this->process();
if (empty($this->error)) {
// If no errors have occured, print the formatted code
$ret = CrayonFormatter::print_code($this, $this->formatted_code, $show_lines, $print);
} else {
$ret = CrayonFormatter::print_error($this, $this->error, '', $print);
}
// Reset the error message at the end of the print session
$this->error = '';
// If $print = FALSE, $ret will contain the output
return $ret;
}
// Objects
// Stores the CrayonLang being used
private $language = NULL;
// A copy of the current global settings which can be overridden
private $settings = NULL;
// Getters and Setters ====================================================
function code($code = NULL) {
if ($code === NULL) {
return $this->code;
} else {
// Trim whitespace
if ($this->setting_val(CrayonSettings::TRIM_WHITESPACE)) {
$code = preg_replace("#(?:^\\s*\\r?\\n)|(?:\\r?\\n\\s*$)#", '', $code);
}
// Methods ================================================================
function __construct($url = NULL, $language = NULL, $id = NULL)
{
if ($url !== NULL) {
$this->url($url);
}
if ($language !== NULL) {
$this->language($language);
}
// Default ID
$id = $id !== NULL ? $id : uniqid();
$this->id($id);
}
/* Tries to load the code locally, then attempts to load it remotely */
private function load()
{
if (empty($this->url)) {
$this->error('The specified URL is empty, please provide a valid URL.');
return;
}
// Try to replace the URL with an absolute path if it is local, used to prevent scripts
// from executing when they are loaded.
$url = $this->url;
if ($this->setting_val(CrayonSettings::DECODE_ATTRIBUTES)) {
$url = CrayonUtil::html_entity_decode($url);
}
$url = CrayonUtil::pathf($url);
$site_http = CrayonGlobalSettings::site_url();
$scheme = parse_url($url, PHP_URL_SCHEME);
// Try to replace the site URL with a path to force local loading
if (empty($scheme)) {
// No url scheme is given - path may be given as relative
$url = CrayonUtil::path_slash($site_http) . CrayonUtil::path_slash($this->setting_val(CrayonSettings::LOCAL_PATH)) . $url;
}
$http_code = 0;
// If available, use the built in wp remote http get function.
if (function_exists('wp_remote_get')) {
$url_uid = 'crayon_' . CrayonUtil::str_uid($url);
$cached = get_transient($url_uid, 'crayon-syntax');
CrayonSettingsWP::load_cache();
if ($cached !== FALSE) {
$content = $cached;
$http_code = 200;
} else {
$response = @wp_remote_get($url, array('sslverify' => false, 'timeout' => 20));
$content = wp_remote_retrieve_body($response);
$http_code = wp_remote_retrieve_response_code($response);
$cache = $this->setting_val(CrayonSettings::CACHE);
$cache_sec = CrayonSettings::get_cache_sec($cache);
if ($cache_sec > 1 && $http_code >= 200 && $http_code < 400) {
set_transient($url_uid, $content, $cache_sec);
CrayonSettingsWP::add_cache($url_uid);
}
}
} else if (in_array(parse_url($url, PHP_URL_SCHEME), array('ssl', 'http', 'https'))) {
// Fallback to cURL. At this point, the URL scheme must be valid.
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// For https connections, we do not require SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, FALSE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
if (isset($_SERVER['HTTP_USER_AGENT'])) {
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
}
$content = curl_exec($ch);
$error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
}
if ($http_code >= 200 && $http_code < 400) {
$this->code($content);
} else {
if (empty($this->code)) {
// If code is also given, just use that
$this->error("The provided URL ('$this->url'), parsed remotely as ('$url'), could not be accessed.");
}
}
$this->needs_load = FALSE;
}
/* Central point of access for all other functions to update code. */
public function process()
{
$tmr = new CrayonTimer();
$this->runtime = NULL;
if ($this->needs_load) {
$tmr->start();
$this->load();
$this->runtime[CRAYON_LOAD_TIME] = $tmr->stop();
}
if (!empty($this->error) || empty($this->code)) {
// Disable highlighting for errors and empty code
return;
}
if ($this->language === NULL) {
$this->language_detect();
}
if ($this->needs_format) {
$tmr->start();
try {
// Parse before hand to read modes
$code = $this->code;
// If inline, then combine lines into one
if ($this->is_inline) {
$code = preg_replace('#[\r\n]+#ms', '', $code);
if ($this->setting_val(CrayonSettings::TRIM_WHITESPACE)) {
$code = trim($code);
}
}
// Decode html entities (e.g. if using visual editor or manually encoding)
if ($this->setting_val(CrayonSettings::DECODE)) {
$code = CrayonUtil::html_entity_decode($code);
}
// Save code so output is plain output is the same
$this->code = $code;
// Allow mixed if langauge supports it and setting is set
CrayonParser::parse($this->language->id());
if (!$this->setting_val(CrayonSettings::MIXED) || !$this->language->mode(CrayonParser::ALLOW_MIXED)) {
// Format the code with the generated regex and elements
$this->formatted_code = CrayonFormatter::format_code($code, $this->language, $this);
} else {
// Format the code with Mixed Highlighting
$this->formatted_code = CrayonFormatter::format_mixed_code($code, $this->language, $this);
}
} catch (Exception $e) {
$this->error($e->message());
return;
}
$this->needs_format = FALSE;
$this->runtime[CRAYON_FORMAT_TIME] = $tmr->stop();
}
}
/* Used to format the glue in between code when finding mixed languages */
private function format_glue($glue, $highlight = TRUE)
{
// TODO $highlight
return CrayonFormatter::format_code($glue, $this->language, $this, $highlight);
}
/* Sends the code to the formatter for printing. Apart from the getters and setters, this is
the only other function accessible outside this class. $show_lines can also be a string. */
function output($show_lines = TRUE, $print = TRUE)
{
$this->process();
if (empty($this->error)) {
// If no errors have occured, print the formatted code
$ret = CrayonFormatter::print_code($this, $this->formatted_code, $show_lines, $print);
} else {
$ret = CrayonFormatter::print_error($this, $this->error, '', $print);
}
// Reset the error message at the end of the print session
$this->error = '';
// If $print = FALSE, $ret will contain the output
return $ret;
}
// Getters and Setters ====================================================
function code($code = NULL)
{
if ($code === NULL) {
return $this->code;
} else {
// Trim whitespace
if ($this->setting_val(CrayonSettings::TRIM_WHITESPACE)) {
$code = preg_replace("#(?:^\\s*\\r?\\n)|(?:\\r?\\n\\s*$)#", '', $code);
}
if ($this->setting_val(CrayonSettings::TRIM_CODE_TAG)) {
$code = preg_replace('#^\s*<\s*code[^>]*>#msi', '', $code);
$code = preg_replace('#</\s*code[^>]*>\s*$#msi', '', $code);
}
$before = $this->setting_val(CrayonSettings::WHITESPACE_BEFORE);
if ($before > 0) {
$code = str_repeat("\n", $before) . $code;
}
$after = $this->setting_val(CrayonSettings::WHITESPACE_AFTER);
if ($after > 0) {
$code = $code . str_repeat("\n", $after);
}
if (!empty($code)) {
$this->code = $code;
$this->needs_format = TRUE;
}
}
}
$before = $this->setting_val(CrayonSettings::WHITESPACE_BEFORE);
if ($before > 0) {
$code = str_repeat("\n", $before) . $code;
}
$after = $this->setting_val(CrayonSettings::WHITESPACE_AFTER);
if ($after > 0) {
$code = $code . str_repeat("\n", $after);
}
function language($id = NULL) {
if ($id === NULL || !is_string($id)) {
return $this->language;
}
if ( ($lang = CrayonResources::langs()->get($id)) != FALSE || ($lang = CrayonResources::langs()->alias($id)) != FALSE ) {
// Set the language if it exists or look for an alias
$this->language = $lang;
} else {
$this->language_detect();
}
// Prepare the language for use, even if we have no code, we need the name
CrayonParser::parse($this->language->id());
}
function language_detect() {
// Attempt to detect the language
if (!empty($id)) {
$this->log("The language '$id' could not be loaded.");
}
$this->language = CrayonResources::langs()->detect($this->url, $this->setting_val(CrayonSettings::FALLBACK_LANG));
}
if (!empty($code)) {
$this->code = $code;
$this->needs_format = TRUE;
}
}
}
function url($url = NULL) {
if ($url === NULL) {
return $this->url;
} else {
$this->url = $url;
$this->needs_load = TRUE;
}
}
function language($id = NULL)
{
if ($id === NULL || !is_string($id)) {
return $this->language;
}
function title($title = NULL) {
if (!CrayonUtil::str($this->title, $title)) {
return $this->title;
}
}
if (($lang = CrayonResources::langs()->get($id)) != FALSE || ($lang = CrayonResources::langs()->alias($id)) != FALSE) {
// Set the language if it exists or look for an alias
$this->language = $lang;
} else {
$this->language_detect();
}
function line_count($line_count = NULL) {
if (!CrayonUtil::num($this->line_count, $line_count)) {
return $this->line_count;
}
}
// Prepare the language for use, even if we have no code, we need the name
CrayonParser::parse($this->language->id());
}
function marked($str = NULL) {
if ($str === NULL) {
return $this->marked_lines;
}
// If only an int is given
if (is_int($str)) {
$array = array($str);
return CrayonUtil::arr($this->marked_lines, $array);
}
// A string with ints separated by commas, can also contain ranges
$array = CrayonUtil::trim_e($str);
$array = array_unique($array);
$lines = array();
foreach ($array as $line) {
// Check for ranges
if (strpos($line, '-') !== FALSE) {
$ranges = CrayonUtil::range_str($line);
$lines = array_merge($lines, $ranges);
} else {
// Otherwise check the string for a number
$line = intval($line);
if ($line !== 0) {
$lines[] = $line;
}
}
}
return CrayonUtil::arr($this->marked_lines, $lines);
}
function range($str = NULL) {
if ($str === NULL) {
return $this->range;
} else {
$range = CrayonUtil::range_str_single($str);
if ($range) {
$this->range = $range;
}
}
return FALSE;
}
function language_detect()
{
// Attempt to detect the language
if (!empty($id)) {
$this->log("The language '$id' could not be loaded.");
}
$this->language = CrayonResources::langs()->detect($this->url, $this->setting_val(CrayonSettings::FALLBACK_LANG));
}
function log($var) {
if ($this->setting_val(CrayonSettings::ERROR_LOG)) {
CrayonLog::log($var);
}
}
function url($url = NULL)
{
if ($url === NULL) {
return $this->url;
} else {
$this->url = $url;
$this->needs_load = TRUE;
}
}
function id($id = NULL) {
if ($id == NULL) {
return $this->id;
} else {
$this->id = strval($id);
}
}
function error($string = NULL) {
if (!$string) {
return $this->error;
}
$this->error .= $string;
$this->log($string);
// Add the error string and ensure no further processing occurs
$this->needs_load = FALSE;
$this->needs_format = FALSE;
}
function title($title = NULL)
{
if (!CrayonUtil::str($this->title, $title)) {
return $this->title;
}
}
// Set and retreive settings
// TODO fix this, it's too limiting
function settings($mixed = NULL) {
if ($this->settings == NULL) {
$this->settings = CrayonGlobalSettings::get_obj();
}
if ($mixed === NULL) {
return $this->settings;
} else if (is_string($mixed)) {
return $this->settings->get($mixed);
} else if (is_array($mixed)) {
$this->settings->set($mixed);
return TRUE;
}
return FALSE;
}
function line_count($line_count = NULL)
{
if (!CrayonUtil::num($this->line_count, $line_count)) {
return $this->line_count;
}
}
/* Retrieve a single setting's value for use in the formatter. By default, on failure it will
* return TRUE to ensure FALSE is only sent when a setting is found. This prevents a fake
* FALSE when the formatter checks for a positive setting (Show/Enable) and fails. When a
* negative setting is needed (Hide/Disable), $default_return should be set to FALSE. */
// TODO fix this (see above)
function setting_val($name = NULL, $default_return = TRUE) {
if (is_string($name) && $setting = $this->settings($name)) {
return $setting->value();
} else {
// Name not valid
return (is_bool($default_return) ? $default_return : TRUE);
}
}
// Set a setting value
// TODO fix this (see above)
function setting_set($name = NULL, $value = TRUE) {
$this->settings->set($name, $value);
}
function marked($str = NULL)
{
if ($str === NULL) {
return $this->marked_lines;
}
// If only an int is given
if (is_int($str)) {
$array = array($str);
return CrayonUtil::arr($this->marked_lines, $array);
}
// A string with ints separated by commas, can also contain ranges
$array = CrayonUtil::trim_e($str);
$array = array_unique($array);
$lines = array();
foreach ($array as $line) {
// Check for ranges
if (strpos($line, '-') !== FALSE) {
$ranges = CrayonUtil::range_str($line);
$lines = array_merge($lines, $ranges);
} else {
// Otherwise check the string for a number
$line = intval($line);
if ($line !== 0) {
$lines[] = $line;
}
}
}
return CrayonUtil::arr($this->marked_lines, $lines);
}
// Used to find current index in dropdown setting
function setting_index($name = NULL) {
$setting = $this->settings($name);
if (is_string($name) && $setting->is_array()) {
return $setting->index();
} else {
// Returns -1 to avoid accidentally selecting an item in a dropdown
return CrayonSettings::INVALID;
}
}
function range($str = NULL)
{
if ($str === NULL) {
return $this->range;
} else {
$range = CrayonUtil::range_str_single($str);
if ($range) {
$this->range = $range;
}
}
return FALSE;
}
function formatted_code() {
return $this->formatted_code;
}
function log($var)
{
if ($this->setting_val(CrayonSettings::ERROR_LOG)) {
CrayonLog::log($var);
}
}
function runtime() {
return $this->runtime;
}
function is_highlighted($highlighted = NULL) {
if ($highlighted === NULL) {
return $this->is_highlighted;
} else {
$this->is_highlighted = $highlighted;
}
}
function is_mixed($mixed = NULL) {
if ($mixed === NULL) {
return $this->is_mixed;
} else {
$this->is_mixed = $mixed;
}
}
function is_inline($inline = NULL) {
if ($inline === NULL) {
return $this->is_inline;
} else {
$inline = CrayonUtil::str_to_bool($inline, FALSE);
$this->is_inline = $inline;
}
}
function id($id = NULL)
{
if ($id == NULL) {
return $this->id;
} else {
$this->id = strval($id);
}
}
function error($string = NULL)
{
if (!$string) {
return $this->error;
}
$this->error .= $string;
$this->log($string);
// Add the error string and ensure no further processing occurs
$this->needs_load = FALSE;
$this->needs_format = FALSE;
}
// Set and retreive settings
// TODO fix this, it's too limiting
function settings($mixed = NULL)
{
if ($this->settings == NULL) {
$this->settings = CrayonGlobalSettings::get_obj();
}
if ($mixed === NULL) {
return $this->settings;
} else if (is_string($mixed)) {
return $this->settings->get($mixed);
} else if (is_array($mixed)) {
$this->settings->set($mixed);
return TRUE;
}
return FALSE;
}
/* Retrieve a single setting's value for use in the formatter. By default, on failure it will
* return TRUE to ensure FALSE is only sent when a setting is found. This prevents a fake
* FALSE when the formatter checks for a positive setting (Show/Enable) and fails. When a
* negative setting is needed (Hide/Disable), $default_return should be set to FALSE. */
// TODO fix this (see above)
function setting_val($name = NULL, $default_return = TRUE)
{
if (is_string($name) && $setting = $this->settings($name)) {
return $setting->value();
} else {
// Name not valid
return (is_bool($default_return) ? $default_return : TRUE);
}
}
// Set a setting value
// TODO fix this (see above)
function setting_set($name = NULL, $value = TRUE)
{
$this->settings->set($name, $value);
}
// Used to find current index in dropdown setting
function setting_index($name = NULL)
{
$setting = $this->settings($name);
if (is_string($name) && $setting->is_array()) {
return $setting->index();
} else {
// Returns -1 to avoid accidentally selecting an item in a dropdown
return CrayonSettings::INVALID;
}
}
function formatted_code()
{
return $this->formatted_code;
}
function runtime()
{
return $this->runtime;
}
function is_highlighted($highlighted = NULL)
{
if ($highlighted === NULL) {
return $this->is_highlighted;
} else {
$this->is_highlighted = $highlighted;
}
}
function is_mixed($mixed = NULL)
{
if ($mixed === NULL) {
return $this->is_mixed;
} else {
$this->is_mixed = $mixed;
}
}
function is_inline($inline = NULL)
{
if ($inline === NULL) {
return $this->is_inline;
} else {
$inline = CrayonUtil::str_to_bool($inline, FALSE);
$this->is_inline = $inline;
}
}
}
?>

File diff suppressed because it is too large Load Diff

View File

@ -1,265 +1,275 @@
<?php
require_once ('global.php');
require_once (CRAYON_LANGS_PHP);
require_once('global.php');
require_once(CRAYON_LANGS_PHP);
/* Manages parsing the syntax for any given language, constructing the regex, and validating the
elements. */
class CrayonParser {
// Properties and Constants ===============================================
const CASE_INSENSITIVE = 'CASE_INSENSITIVE';
const MULTI_LINE = 'MULTI_LINE';
const SINGLE_LINE = 'SINGLE_LINE';
const ALLOW_MIXED = 'ALLOW_MIXED';
//const NO_END_TAG = '(?![^<]*>)'; // No longer used
const HTML_CHAR = 'HTML_CHAR';
const HTML_CHAR_REGEX = '<|>|(&([\w-]+);?)|[ \t]+';
const CRAYON_ELEMENT = 'CRAYON_ELEMENT';
const CRAYON_ELEMENT_REGEX = '\{\{crayon-internal:[^\}]*\}\}';
const CRAYON_ELEMENT_REGEX_CAPTURE = '\{\{crayon-internal:([^\}]*)\}\}';
private static $modes = array(self::CASE_INSENSITIVE => TRUE, self::MULTI_LINE => TRUE, self::SINGLE_LINE => TRUE, self::ALLOW_MIXED => TRUE);
class CrayonParser
{
// Properties and Constants ===============================================
const CASE_INSENSITIVE = 'CASE_INSENSITIVE';
const MULTI_LINE = 'MULTI_LINE';
const SINGLE_LINE = 'SINGLE_LINE';
const ALLOW_MIXED = 'ALLOW_MIXED';
//const NO_END_TAG = '(?![^<]*>)'; // No longer used
const HTML_CHAR = 'HTML_CHAR';
const HTML_CHAR_REGEX = '<|>|(&([\w-]+);?)|[ \t]+';
const CRAYON_ELEMENT = 'CRAYON_ELEMENT';
const CRAYON_ELEMENT_REGEX = '\{\{crayon-internal:[^\}]*\}\}';
const CRAYON_ELEMENT_REGEX_CAPTURE = '\{\{crayon-internal:([^\}]*)\}\}';
// Methods ================================================================
private function __construct() {}
private static $modes = array(self::CASE_INSENSITIVE => TRUE, self::MULTI_LINE => TRUE, self::SINGLE_LINE => TRUE, self::ALLOW_MIXED => TRUE);
/**
* Parse all languages stored in CrayonLangs.
* Avoid using this unless you must list the details in language files for all languages.
* @return array Array of all loaded CrayonLangs.
*/
public static function parse_all() {
$langs = CrayonResources::langs()->get();
if (empty($langs)) {
return FALSE;
}
foreach ($langs as $lang) {
self::parse($lang->id());
}
return $langs;
}
// Methods ================================================================
private function __construct()
{
}
/* Read a syntax file and parse the regex rules within it, this may require several other
files containing lists of keywords and such to be read. Updates the parsed elements and
regex in the CrayonLang with the given $id. */
public static function parse($id) {
// Verify the language is loaded and has not been parsed before
if ( !($lang = CrayonResources::langs()->get($id)) ) {
CrayonLog::syslog("The language with id '$id' was not loaded and could not be parsed.");
return FALSE;
} else if ($lang->is_parsed()) {
return;
}
// Read language file
$path = CrayonResources::langs()->path($id);
/**
* Parse all languages stored in CrayonLangs.
* Avoid using this unless you must list the details in language files for all languages.
* @return array Array of all loaded CrayonLangs.
*/
public static function parse_all()
{
$langs = CrayonResources::langs()->get();
if (empty($langs)) {
return FALSE;
}
foreach ($langs as $lang) {
self::parse($lang->id());
}
return $langs;
}
/* Read a syntax file and parse the regex rules within it, this may require several other
files containing lists of keywords and such to be read. Updates the parsed elements and
regex in the CrayonLang with the given $id. */
public static function parse($id)
{
// Verify the language is loaded and has not been parsed before
if (!($lang = CrayonResources::langs()->get($id))) {
CrayonLog::syslog("The language with id '$id' was not loaded and could not be parsed.");
return FALSE;
} else if ($lang->is_parsed()) {
return;
}
// Read language file
$path = CrayonResources::langs()->path($id);
CrayonLog::debug('Parsing language ' . $path);
if ( ($file = CrayonUtil::lines($path, 'wcs')) === FALSE ) {
if (($file = CrayonUtil::lines($path, 'wcs')) === FALSE) {
CrayonLog::debug('Parsing failed ' . $path);
return FALSE;
}
return FALSE;
}
// Extract the language name
$name_pattern = '#^[ \t]*name[ \t]+([^\r\n]+)[ \t]*#mi';
preg_match($name_pattern, $file, $name);
if (count($name) > 1) {
$name = $name[1];
$lang->name($name);
$file = preg_replace($name_pattern, '', $file);
} else {
$name = $lang->id();
}
// Extract the language name
$name_pattern = '#^[ \t]*name[ \t]+([^\r\n]+)[ \t]*#mi';
preg_match($name_pattern, $file, $name);
if (count($name) > 1) {
$name = $name[1];
$lang->name($name);
$file = preg_replace($name_pattern, '', $file);
} else {
$name = $lang->id();
}
// Extract the language version
$version_pattern = '#^[ \t]*version[ \t]+([^\r\n]+)[ \t]*#mi';
preg_match($version_pattern, $file, $version);
if (count($version) > 1) {
$version = $version[1];
$lang->version($version);
$file = preg_replace($version_pattern, '', $file);
}
// Extract the language version
$version_pattern = '#^[ \t]*version[ \t]+([^\r\n]+)[ \t]*#mi';
preg_match($version_pattern, $file, $version);
if (count($version) > 1) {
$version = $version[1];
$lang->version($version);
$file = preg_replace($version_pattern, '', $file);
}
// Extract the modes
$mode_pattern = '#^[ \t]*(' . implode('|', array_keys(self::$modes)) . ')[ \t]+(?:=[ \t]*)?([^\r\n]+)[ \t]*#mi';
preg_match_all($mode_pattern, $file, $mode_matches);
if (count($mode_matches) == 3) {
for ($i = 0; $i < count($mode_matches[0]); $i++) {
$lang->mode($mode_matches[1][$i], $mode_matches[2][$i]);
}
$file = preg_replace($mode_pattern, '', $file);
}
// Extract the modes
$mode_pattern = '#^[ \t]*(' . implode('|', array_keys(self::$modes)) . ')[ \t]+(?:=[ \t]*)?([^\r\n]+)[ \t]*#mi';
preg_match_all($mode_pattern, $file, $mode_matches);
if (count($mode_matches) == 3) {
for ($i = 0; $i < count($mode_matches[0]); $i++) {
$lang->mode($mode_matches[1][$i], $mode_matches[2][$i]);
}
$file = preg_replace($mode_pattern, '', $file);
}
/* Add reserved Crayon element. This is used by Crayon internally. */
$crayon_element = new CrayonElement(self::CRAYON_ELEMENT, $path, self::CRAYON_ELEMENT_REGEX);
$lang->element(self::CRAYON_ELEMENT, $crayon_element);
/* Add reserved Crayon element. This is used by Crayon internally. */
$crayon_element = new CrayonElement(self::CRAYON_ELEMENT, $path, self::CRAYON_ELEMENT_REGEX);
$lang->element(self::CRAYON_ELEMENT, $crayon_element);
// Extract elements, classes and regex
$pattern = '#^[ \t]*([\w:]+)[ \t]+(?:\[([\w\t ]*)\][ \t]+)?([^\r\n]+)[ \t]*#m';
preg_match_all($pattern, $file, $matches);
// Extract elements, classes and regex
$pattern = '#^[ \t]*([\w:]+)[ \t]+(?:\[([\w\t ]*)\][ \t]+)?([^\r\n]+)[ \t]*#m';
preg_match_all($pattern, $file, $matches);
if (!empty($matches[0])) {
$elements = $matches[1];
$classes = $matches[2];
$regexes = $matches[3];
} else {
CrayonLog::syslog("No regex patterns and/or elements were parsed from language file at '$path'.");
}
if (!empty($matches[0])) {
$elements = $matches[1];
$classes = $matches[2];
$regexes = $matches[3];
} else {
CrayonLog::syslog("No regex patterns and/or elements were parsed from language file at '$path'.");
}
// Remember state in case we encounter catchable exceptions
$error = FALSE;
for ($i = 0; $i < count($matches[0]); $i++) {
// References
$name = &$elements[$i];
$class = &$classes[$i];
$regex = &$regexes[$i];
$name = trim(strtoupper($name));
// Ensure both the element and regex are valid
if (empty($name) || empty($regex)) {
CrayonLog::syslog("Element(s) and/or regex(es) are missing in '$path'.");
$error = TRUE;
continue;
}
// Look for fallback element
$pieces = explode(':', $name);
if (count($pieces) == 2) {
$name = $pieces[0];
$fallback = $pieces[1];
} else if (count($pieces) == 1) {
$name = $pieces[0];
$fallback = '';
} else {
CrayonLog::syslog("Too many colons found in element name '$name' in '$path'");
$error = TRUE;
continue;
}
// Create a new CrayonElement
$element = new CrayonElement($name, $path);
$element->fallback($fallback);
if (!empty($class)) {
// Avoid setting known css to blank
$element->css($class);
}
if ($element->regex($regex) === FALSE) {
$error = TRUE;
continue;
}
// Add the regex to the element
$lang->element($name, $element);
$state = $error ? CrayonLang::PARSED_ERRORS : CrayonLang::PARSED_SUCCESS;
$lang->state($state);
}
// Remember state in case we encounter catchable exceptions
$error = FALSE;
for ($i = 0; $i < count($matches[0]); $i++) {
// References
$name = &$elements[$i];
$class = &$classes[$i];
$regex = &$regexes[$i];
$name = trim(strtoupper($name));
// Ensure both the element and regex are valid
if (empty($name) || empty($regex)) {
CrayonLog::syslog("Element(s) and/or regex(es) are missing in '$path'.");
$error = TRUE;
continue;
}
// Look for fallback element
$pieces = explode(':', $name);
if (count($pieces) == 2) {
$name = $pieces[0];
$fallback = $pieces[1];
} else if (count($pieces) == 1) {
$name = $pieces[0];
$fallback = '';
} else {
CrayonLog::syslog("Too many colons found in element name '$name' in '$path'");
$error = TRUE;
continue;
}
// Create a new CrayonElement
$element = new CrayonElement($name, $path);
$element->fallback($fallback);
if (!empty($class)) {
// Avoid setting known css to blank
$element->css($class);
}
if ($element->regex($regex) === FALSE) {
$error = TRUE;
continue;
}
// Add the regex to the element
$lang->element($name, $element);
$state = $error ? CrayonLang::PARSED_ERRORS : CrayonLang::PARSED_SUCCESS;
$lang->state($state);
}
/* Prevents < > and other html entities from being printed as is, which could lead to actual html tags
* from the printed code appearing on the page - not good. This can also act to color any HTML entities
* that are not picked up by previously defined elements.
*/
$html = new CrayonElement(self::HTML_CHAR, $path, self::HTML_CHAR_REGEX);
$lang->element(self::HTML_CHAR, $html);
}
/* Prevents < > and other html entities from being printed as is, which could lead to actual html tags
* from the printed code appearing on the page - not good. This can also act to color any HTML entities
* that are not picked up by previously defined elements.
*/
$html = new CrayonElement(self::HTML_CHAR, $path, self::HTML_CHAR_REGEX);
$lang->element(self::HTML_CHAR, $html);
}
// Validates regex and accesses data stored in a CrayonElement
public static function validate_regex($regex, $element) {
if (is_string($regex) && @get_class($element) == CRAYON_ELEMENT_CLASS) {
// If the (?alt) tag has been used, insert the file into the regex
$file = self::regex_match('#\(\?alt:(.+?)\)#', $regex);
if ( count($file) == 2 ) {
// Element 0 has full match, 1 has captured groups
for ($i = 0; $i < count($file[1]); $i++) {
$file_lines = CrayonUtil::lines(dirname($element->path()) . crayon_s() . $file[1][$i], 'rcwh');
if ($file_lines !== FALSE) {
$file_lines = implode('|', $file_lines);
// If any spaces exist, treat them as whitespace
$file_lines = preg_replace('#[ \t]+#msi', '\s+', $file_lines);
$regex = str_replace($file[0][$i], "(?:$file_lines)", $regex);
} else {
CrayonLog::syslog("Parsing of '{$element->path()}' failed, an (?alt) tag failed for the element '{$element->name()}'" );
return FALSE;
}
}
}
// Validates regex and accesses data stored in a CrayonElement
public static function validate_regex($regex, $element)
{
if (is_string($regex) && @get_class($element) == CRAYON_ELEMENT_CLASS) {
// If the (?alt) tag has been used, insert the file into the regex
$file = self::regex_match('#\(\?alt:(.+?)\)#', $regex);
if (count($file) == 2) {
// Element 0 has full match, 1 has captured groups
for ($i = 0; $i < count($file[1]); $i++) {
$file_lines = CrayonUtil::lines(dirname($element->path()) . crayon_s() . $file[1][$i], 'rcwh');
if ($file_lines !== FALSE) {
$file_lines = implode('|', $file_lines);
// If any spaces exist, treat them as whitespace
$file_lines = preg_replace('#[ \t]+#msi', '\s+', $file_lines);
$regex = str_replace($file[0][$i], "(?:$file_lines)", $regex);
} else {
CrayonLog::syslog("Parsing of '{$element->path()}' failed, an (?alt) tag failed for the element '{$element->name()}'");
return FALSE;
}
}
}
// If the (?default:element) function is used, replace the regex with the default, if exists
$def = self::regex_match('#\(\?default(?:\:(\w+))?\)#', $regex);
if ( count($def) == 2 ) {
// Load default language
$default = CrayonResources::langs()->get(CrayonLangs::DEFAULT_LANG);
// If default has not been loaded, we can't use it, skip the element
if (!$default) {
CrayonLog::syslog(
"Could not use default regex in the element '{$element->name()}' in '{$element->path()}'");
return FALSE;
}
for ($i = 0; $i < count($def[1]); $i++) {
// If an element has been provided
$element_name = ( !empty($def[1][$i]) ) ? $def[1][$i] : $element->name();
if (($default_element = $default->element($element_name)) != FALSE) {
$regex = str_replace($def[0][$i], '(?:' . $default_element->regex() .')', $regex);
} else {
CrayonLog::syslog("The language at '{$element->path()}' referred to the Default Language regex for element '{$element->name()}', which did not exist.");
// If the (?default:element) function is used, replace the regex with the default, if exists
$def = self::regex_match('#\(\?default(?:\:(\w+))?\)#', $regex);
if (count($def) == 2) {
// Load default language
$default = CrayonResources::langs()->get(CrayonLangs::DEFAULT_LANG);
// If default has not been loaded, we can't use it, skip the element
if (!$default) {
CrayonLog::syslog(
"Could not use default regex in the element '{$element->name()}' in '{$element->path()}'");
return FALSE;
}
for ($i = 0; $i < count($def[1]); $i++) {
// If an element has been provided
$element_name = (!empty($def[1][$i])) ? $def[1][$i] : $element->name();
if (($default_element = $default->element($element_name)) != FALSE) {
$regex = str_replace($def[0][$i], '(?:' . $default_element->regex() . ')', $regex);
} else {
CrayonLog::syslog("The language at '{$element->path()}' referred to the Default Language regex for element '{$element->name()}', which did not exist.");
if (CRAYON_DEBUG) {
CrayonLog::syslog("Default language URL: " . CrayonResources::langs()->url(CrayonLangs::DEFAULT_LANG));
CrayonLog::syslog("Default language Path: " . CrayonResources::langs()->path(CrayonLangs::DEFAULT_LANG));
}
return FALSE;
}
}
}
return FALSE;
}
}
}
// If the (?html) tag is used, escape characters in html (<, > and &)
$html = self::regex_match('#\(\?html:(.+?)\)#', $regex);
if ( count($html) == 2 ) {
for ($i = 0; $i < count($html[1]); $i++) {
$regex = str_replace($html[0][$i], htmlentities($html[1][$i]), $regex);
}
}
// If the (?html) tag is used, escape characters in html (<, > and &)
$html = self::regex_match('#\(\?html:(.+?)\)#', $regex);
if (count($html) == 2) {
for ($i = 0; $i < count($html[1]); $i++) {
$regex = str_replace($html[0][$i], htmlentities($html[1][$i]), $regex);
}
}
// Ensure all parenthesis are atomic to avoid conflicting with element matches
$regex = CrayonUtil::esc_atomic($regex);
// Ensure all parenthesis are atomic to avoid conflicting with element matches
$regex = CrayonUtil::esc_atomic($regex);
// Escape #, this is our delimiter
$regex = CrayonUtil::esc_hash($regex);
// Escape #, this is our delimiter
$regex = CrayonUtil::esc_hash($regex);
// Test if regex is valid
if (@preg_match("#$regex#", '') === FALSE) {
CrayonLog::syslog("The regex for the element '{$element->name()}' in '{$element->path()}' is not valid.");
return FALSE;
}
// Test if regex is valid
if (@preg_match("#$regex#", '') === FALSE) {
CrayonLog::syslog("The regex for the element '{$element->name()}' in '{$element->path()}' is not valid.");
return FALSE;
}
return $regex;
} else {
return '';
}
}
return $regex;
} else {
return '';
}
}
public static function validate_css($css) {
if (is_string($css)) {
// Remove dots in CSS class and convert to lowercase
$css = str_replace('.', '', $css);
$css = strtolower($css);
$css = explode(' ', $css);
$css_str = '';
foreach ($css as $c) {
if (!empty($c)) {
$css_str .= $c . ' ';
}
}
return trim($css_str);
} else {
return '';
}
}
public static function validate_css($css)
{
if (is_string($css)) {
// Remove dots in CSS class and convert to lowercase
$css = str_replace('.', '', $css);
$css = strtolower($css);
$css = explode(' ', $css);
$css_str = '';
foreach ($css as $c) {
if (!empty($c)) {
$css_str .= $c . ' ';
}
}
return trim($css_str);
} else {
return '';
}
}
public static function regex_match($pattern, $subject) {
if (preg_match_all($pattern, $subject, $matches)) {
return $matches;
}
return array();
}
public static function regex_match($pattern, $subject)
{
if (preg_match_all($pattern, $subject, $matches)) {
return $matches;
}
return array();
}
public static function modes() {
return self::$modes;
}
public static function modes()
{
return self::$modes;
}
public static function is_mode($name) {
return is_string($name) && array_key_exists($name, self::$modes);
}
public static function is_mode($name)
{
return is_string($name) && array_key_exists($name, self::$modes);
}
}
?>

View File

@ -1,296 +1,333 @@
<?php
require_once ('global.php');
require_once (CRAYON_LANGS_PHP);
require_once (CRAYON_THEMES_PHP);
require_once (CRAYON_FONTS_PHP);
require_once('global.php');
require_once(CRAYON_LANGS_PHP);
require_once(CRAYON_THEMES_PHP);
require_once(CRAYON_FONTS_PHP);
class CrayonResources {
private static $langs = NULL;
private static $themes = NULL;
private static $fonts = NULL;
class CrayonResources
{
private static $langs = NULL;
private static $themes = NULL;
private static $fonts = NULL;
private function __construct() {}
private function __construct()
{